answer
stringlengths
17
10.2M
package org.lantern; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ChatManager; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.RosterListener; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.lastbamboo.common.p2p.P2PConstants; import org.lastbamboo.common.portmapping.NatPmpService; import org.lastbamboo.common.portmapping.PortMapListener; import org.lastbamboo.common.portmapping.PortMappingProtocol; import org.lastbamboo.common.portmapping.UpnpService; import org.littleshoot.commom.xmpp.XmppP2PClient; import org.littleshoot.commom.xmpp.XmppUtils; import org.littleshoot.p2p.P2P; import org.littleshoot.util.CommonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.hoodcomputing.natpmp.NatPmpException; /** * Handles logging in to the XMPP server and processing trusted users through * the roster. */ public class XmppHandler implements ProxyStatusListener, ProxyProvider { private static final String LANTERN_JID = "lantern-controller@appspot.com"; private static final Logger LOG = LoggerFactory.getLogger(XmppHandler.class); private final Set<ProxyHolder> proxySet = new HashSet<ProxyHolder>(); private final Queue<ProxyHolder> proxies = new ConcurrentLinkedQueue<ProxyHolder>(); private final Set<URI> peerProxySet = new HashSet<URI>(); private final Queue<URI> peerProxies = new ConcurrentLinkedQueue<URI>(); private final Set<URI> anonymousProxySet = new HashSet<URI>(); private final Queue<URI> anonymousProxies = new ConcurrentLinkedQueue<URI>(); private final Set<ProxyHolder> laeProxySet = new HashSet<ProxyHolder>(); private final Queue<ProxyHolder> laeProxies = new ConcurrentLinkedQueue<ProxyHolder>(); private final XmppP2PClient client; private boolean displayedUpdateMessage = false; private static final String ID; private static final String UNCENSORED_ID = "-lan-"; private static final String CENSORED_ID = "-lac-"; static { if (CensoredUtils.isCensored()) { ID = CENSORED_ID; } else { ID = UNCENSORED_ID; } SmackConfiguration.setPacketReplyTimeout(30 * 1000); } private final int sslProxyRandomPort; private final Timer updateTimer = new Timer(true); private Chat hubChat; private final SystemTray tray; private volatile long lastInfoMessageScheduled = 0L; private final MessageListener typedListener = new MessageListener() { @Override public void processMessage(final Chat ch, final Message msg) { // Note the Chat will always be null here. We try to avoid using // actual Chat instances due to Smack's strange and inconsistent // behavior with message listeners on chats. final String part = msg.getFrom(); LOG.info("Got chat participant: {} with message:\n {}", part, msg.toXML()); if (part.startsWith(LANTERN_JID)) { LOG.info("Lantern controlling agent response"); final String body = msg.getBody(); LOG.info("Body: {}", body); final Object obj = JSONValue.parse(body); final JSONObject json = (JSONObject) obj; final JSONArray servers = (JSONArray) json.get(LanternConstants.SERVERS); final Long delay = (Long) json.get(LanternConstants.UPDATE_TIME); if (delay != null) { final long now = System.currentTimeMillis(); final long elapsed = now - lastInfoMessageScheduled; if (elapsed < 10000) { LOG.info("Ignoring duplicate info request scheduling- "+ "scheduled request {} milliseconds ago.", elapsed); return; } lastInfoMessageScheduled = now; updateTimer.schedule(new TimerTask() { @Override public void run() { sendInfoRequest(); } }, delay); LOG.info("Scheduled next info request in {} milliseconds", delay); } if (servers == null) { LOG.info("XMPP: "+XmppUtils.toString(msg)); } else { final Iterator<String> iter = servers.iterator(); while (iter.hasNext()) { final String server = iter.next(); addProxy(server); } if (!servers.isEmpty() && ! Configurator.configured()) { Configurator.configure(); tray.activate(); } } // This is really a JSONObject, but that itself is a map. final Map<String, String> update = (Map<String, String>) json.get(LanternConstants.UPDATE_KEY); LOG.info("Already displayed update? {}", displayedUpdateMessage); if (update != null && !displayedUpdateMessage) { LOG.info("About to show update..."); displayedUpdateMessage = true; LanternHub.display().asyncExec (new Runnable () { @Override public void run () { LanternHub.systemTray().addUpdate(update); //final LanternBrowser lb = new LanternBrowser(true); //lb.showUpdate(update); } }); } } final Integer type = (Integer) msg.getProperty(P2PConstants.MESSAGE_TYPE); if (type != null) { LOG.info("Not processing typed message"); processTypedMessage(msg, type); } } }; /** * Creates a new XMPP handler. * * @param keyStoreManager The class for managing certificates. * @param sslProxyRandomPort The port of the HTTP proxy that other peers * will relay to. * @param plainTextProxyRandomPort The port of the HTTP proxy running * only locally and accepting plain-text sockets. */ public XmppHandler(final int sslProxyRandomPort, final int plainTextProxyRandomPort, final SystemTray tray) { this.sslProxyRandomPort = sslProxyRandomPort; this.tray = tray; String email = LanternUtils.getStringProperty("google.user"); String pwd = LanternUtils.getStringProperty("google.pwd"); if (StringUtils.isBlank(email)) { if (!LanternUtils.runWithUi()) { email = askForEmail(); } else { LOG.error("No user name"); throw new IllegalStateException("No user name"); } } if (StringUtils.isBlank(pwd)) { if (!LanternUtils.runWithUi()) { pwd = askForPassword(); } else { LOG.error("No password."); throw new IllegalStateException("No password"); } } try { /* final String libName = System.mapLibraryName("jnltorrent"); final JLibTorrent libTorrent = new JLibTorrent(Arrays.asList(new File (new File(".."), libName), new File (libName), new File ("lib", libName)), true); */ final InetSocketAddress plainTextProxyRelayAddress = new InetSocketAddress("127.0.0.1", plainTextProxyRandomPort); NatPmpService natPmpService = null; try { natPmpService = new NatPmp(); } catch (final NatPmpException e) { LOG.error("Could not map", e); // We just use a dummy one in this case. natPmpService = new NatPmpService() { @Override public void removeNatPmpMapping(int arg0) { } @Override public int addNatPmpMapping( final PortMappingProtocol arg0, int arg1, int arg2, PortMapListener arg3) { return -1; } }; } final UpnpService upnpService = new Upnp(); this.client = P2P.newXmppP2PHttpClient("shoot", natPmpService, upnpService, new InetSocketAddress(this.sslProxyRandomPort), //newTlsSocketFactory(), SSLServerSocketFactory.getDefault(),//newTlsServerSocketFactory(), newTlsSocketFactory(), newTlsServerSocketFactory(), //SocketFactory.getDefault(), ServerSocketFactory.getDefault(), plainTextProxyRelayAddress, false); // This is a global, backup listener added to the client. We might // get notifications of messages twice in some cases, but that's // better than the alternative of sometimes not being notified // at all. LOG.info("Adding message listener..."); this.client.addMessageListener(typedListener); this.client.login(email, pwd, ID); final XMPPConnection connection = this.client.getXmppConnection(); LOG.info("Connection ID: {}", connection.getConnectionID()); // Here we handle allowing the server to subscribe to our presence. connection.addPacketListener(new PacketListener() { @Override public void processPacket(final Packet pack) { LOG.info("Responding to subscribtion request from {} and to {}", pack.getFrom(), pack.getTo()); final Presence packet = new Presence(Presence.Type.subscribed); packet.setTo(pack.getFrom()); packet.setFrom(pack.getTo()); connection.sendPacket(packet); } }, new PacketFilter() { @Override public boolean accept(final Packet packet) { //LOG.info("Filtering incoming packet:\n{}", packet.toXML()); if(packet instanceof Presence) { final Presence pres = (Presence) packet; if(pres.getType().equals(Presence.Type.subscribe)) { LOG.info("Got subscribe packet!!"); final String from = pres.getFrom(); if (from.startsWith("lantern-controller@") && from.endsWith("lantern-controller.appspotchat.com")) { LOG.info("Got lantern subscription request!!"); return true; } else { LOG.info("Ignoring subscription request from: {}", from); } } } else { LOG.info("Filtered out packet: ", packet.toXML()); //XmppUtils.printMessage(packet); } return false; } }); updatePresence(); final ChatManager chatManager = connection.getChatManager(); this.hubChat = chatManager.createChat(LANTERN_JID, typedListener); sendInfoRequest(); configureRoster(); } catch (final IOException e) { final String msg = "Could not log in!!"; LOG.warn(msg, e); throw new Error(msg, e); } catch (final XMPPException e) { final String msg = "Could not configure roster!!"; LOG.warn(msg, e); throw new Error(msg, e); } } private String askForEmail() { System.out.print("Please enter your gmail e-mail, as in johndoe@gmail.com: "); return readLine(); } private String askForPassword() { System.out.print("Please enter your gmail password: "); return readLine(); } private String readLine() { // open up standard input final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { return br.readLine(); } catch (final IOException ioe) { System.out.println("IO error trying to read your name!"); } return ""; } private void updatePresence() { // This is for Google Talk compatibility. Surprising, all we need to // do is grab our Google Talk shared status, signifying support for // their protocol, and then we don't interfere with GChat visibility. final Packet status = LanternUtils.getSharedStatus( this.client.getXmppConnection()); LOG.info("Status:\n{}", status.toXML()); final XMPPConnection conn = this.client.getXmppConnection(); LOG.info("Sending presence available"); conn.sendPacket(new Presence(Presence.Type.available)); final Presence forHub = new Presence(Presence.Type.available); forHub.setTo(LANTERN_JID); conn.sendPacket(forHub); } private void configureRoster() throws XMPPException { final XMPPConnection xmpp = this.client.getXmppConnection(); final Roster roster = xmpp.getRoster(); // Make sure we look for Lantern packets. final RosterEntry lantern = roster.getEntry(LANTERN_JID); if (lantern == null) { LOG.info("Creating roster entry for Lantern..."); roster.createEntry(LANTERN_JID, "Lantern", null); } roster.setSubscriptionMode(Roster.SubscriptionMode.manual); roster.addRosterListener(new RosterListener() { @Override public void entriesDeleted(final Collection<String> addresses) { LOG.info("Entries deleted"); } @Override public void entriesUpdated(final Collection<String> addresses) { LOG.info("Entries updated: {}", addresses); } @Override public void presenceChanged(final Presence presence) { //LOG.info("Processing presence changed: {}", presence); processPresence(presence); } @Override public void entriesAdded(final Collection<String> addresses) { LOG.info("Entries added: "+addresses); } }); // Now we add all the existing entries to get people who are already // online. final Collection<RosterEntry> entries = roster.getEntries(); for (final RosterEntry entry : entries) { final Iterator<Presence> presences = roster.getPresences(entry.getUser()); while (presences.hasNext()) { final Presence p = presences.next(); processPresence(p); } } LOG.info("Finished adding listeners"); } private void processPresence(final Presence p) { final String from = p.getFrom(); LOG.info("Got presence: {}", p.toXML()); if (isLanternHub(from)) { LOG.info("Got Lantern hub presence"); } else if (isLanternJid(from)) { addOrRemovePeer(p, from); } } private void sendInfoRequest() { // Send an "info" message to gather proxy data. final Message msg = new Message(); final JSONObject json = new JSONObject(); final StatsTracker statsTracker = LanternHub.statsTracker(); json.put(LanternConstants.COUNTRY_CODE, CensoredUtils.countryCode()); //json.put(LanternConstants.USER_NAME, this.user); //json.put(LanternConstants.PASSWORD, this.pwd); json.put(LanternConstants.BYTES_PROXIED, statsTracker.getBytesProxied()); json.put(LanternConstants.DIRECT_BYTES, statsTracker.getDirectBytes()); json.put(LanternConstants.REQUESTS_PROXIED, statsTracker.getProxiedRequests()); json.put(LanternConstants.DIRECT_REQUESTS, statsTracker.getDirectRequests()); json.put(LanternConstants.WHITELIST_ADDITIONS, LanternUtils.toJsonArray(Whitelist.getAdditions())); json.put(LanternConstants.WHITELIST_REMOVALS, LanternUtils.toJsonArray(Whitelist.getRemovals())); json.put(LanternConstants.VERSION_KEY, LanternConstants.VERSION); final String str = json.toJSONString(); LOG.info("Reporting data: {}", str); msg.setBody(str); try { LOG.info("Sending info message to Lantern Hub"); this.hubChat.sendMessage(msg); Whitelist.whitelistReported(); statsTracker.clear(); } catch (final XMPPException e) { LOG.error("Could not send INFO message", e); } } private void addOrRemovePeer(final Presence p, final String from) { LOG.info("Processing peer: {}", from); final URI uri; try { uri = new URI(from); } catch (final URISyntaxException e) { LOG.error("Could not create URI from: {}", from); return; } final TrustedContactsManager tcm = LanternHub.getTrustedContactsManager(); final boolean trusted = tcm.isJidTrusted(from); if (p.isAvailable()) { LOG.info("Adding from to peer JIDs: {}", from); if (trusted) { addTrustedProxy(uri); } else { addAnonymousProxy(uri); } } else { LOG.info("Removing JID for peer '"+from+"' with presence: {}", p); removePeer(uri); } } private boolean isLanternHub(final String from) { return from.startsWith("lantern-controller@") && from.contains("lantern-controller.appspot"); } private void sendErrorMessage(final InetSocketAddress isa, final String message) { final Message msg = new Message(); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.ERROR_TYPE); final String errorMessage = "Error: "+message+" with host: "+isa; msg.setProperty(XmppMessageConstants.MESSAGE, errorMessage); try { this.hubChat.sendMessage(msg); } catch (final XMPPException e) { LOG.error("Error sending message", e); } } private void processTypedMessage(final Message msg, final Integer type) { final String from = msg.getFrom(); LOG.info("Processing typed message from {}", from); /* final URI uri; try { uri = new URI(from); } catch (final URISyntaxException e) { LOG.error("Could not create URI from: {}", from); return; } if (!this.peerProxySet.contains(uri)) { LOG.warn("Ignoring message from untrusted peer: {}", from); LOG.warn("Peer not in: {}", this.peerProxySet); return; } */ switch (type) { case (XmppMessageConstants.INFO_REQUEST_TYPE): LOG.info("Handling INFO request from {}", from); processInfoData(msg); sendInfoResponse(from); break; case (XmppMessageConstants.INFO_RESPONSE_TYPE): LOG.info("Handling INFO response from {}", from); processInfoData(msg); break; default: LOG.warn("Did not understand type: "+type); break; } } private void sendInfoResponse(final String from) { final Message msg = new Message(); // The from becomes the to when we're responding. msg.setTo(from); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.INFO_RESPONSE_TYPE); msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress()); msg.setProperty(P2PConstants.CERT, LanternHub.getKeyStoreManager().getBase64Cert()); this.client.getXmppConnection().sendPacket(msg); } private void processInfoData(final Message msg) { LOG.info("Processing INFO data from request or response."); final String mac = (String) msg.getProperty(P2PConstants.MAC); final String base64Cert = (String) msg.getProperty(P2PConstants.CERT); LOG.info("Base 64 cert: {}", base64Cert); if (StringUtils.isNotBlank(base64Cert)) { LOG.info("Got certificate:\n"+ new String(Base64.decodeBase64(base64Cert))); try { // Add the peer if we're able to add the cert. LanternHub.getKeyStoreManager().addBase64Cert(mac, base64Cert); } catch (final IOException e) { LOG.error("Could not add cert??", e); } } else { LOG.error("No cert for peer?"); } } private void addProxy(final String cur) { LOG.info("Considering proxy: {}", cur); final String jid = this.client.getXmppConnection().getUser().trim(); final String emailId = LanternUtils.jidToUser(jid); LOG.info("We are: {}", jid); LOG.info("Service name: {}", this.client.getXmppConnection().getServiceName()); if (jid.equals(cur.trim())) { LOG.info("Not adding ourselves as a proxy!!"); return; } if (cur.contains("appspot")) { addLaeProxy(cur); } else if (cur.startsWith(emailId+"/")) { try { addTrustedProxy(new URI(cur)); } catch (final URISyntaxException e) { LOG.error("Error with proxy URI", e); } } else if (cur.contains("@")) { try { addAnonymousProxy(new URI(cur)); } catch (final URISyntaxException e) { LOG.error("Error with proxy URI", e); } } else { addGeneralProxy(cur); } } private void addTrustedProxy(final URI cur) { LOG.info("Considering trusted peer proxy: {}", cur); addPeerProxy(cur, this.peerProxySet, this.peerProxies); } private void addAnonymousProxy(final URI cur) { LOG.info("Considering anonymous proxy"); addPeerProxy(cur, this.anonymousProxySet, this.anonymousProxies); } private void addPeerProxy(final URI cur, final Set<URI> peerSet, final Queue<URI> peerQueue) { LOG.info("Considering peer proxy"); synchronized (peerSet) { if (!peerSet.contains(cur)) { LOG.info("Actually adding peer proxy: {}", cur); peerSet.add(cur); peerQueue.add(cur); sendAndRequestCert(cur); } else { LOG.info("We already know about the peer proxy"); } } } private void sendAndRequestCert(final URI cur) { LOG.info("Requesting cert from {}", cur); final Message msg = new Message(); msg.setProperty(P2PConstants.MESSAGE_TYPE, XmppMessageConstants.INFO_REQUEST_TYPE); msg.setTo(cur.toASCIIString()); // Set our certificate in the request as well -- we want to make // extra sure these get through! msg.setProperty(P2PConstants.MAC, LanternUtils.getMacAddress()); msg.setProperty(P2PConstants.CERT, LanternHub.getKeyStoreManager().getBase64Cert()); this.client.getXmppConnection().sendPacket(msg); } private void addLaeProxy(final String cur) { LOG.info("Adding LAE proxy"); addProxyWithChecks(this.laeProxySet, this.laeProxies, new ProxyHolder(cur, new InetSocketAddress(cur, 443))); } private void addGeneralProxy(final String cur) { final String hostname = StringUtils.substringBefore(cur, ":"); final int port = Integer.parseInt(StringUtils.substringAfter(cur, ":")); final InetSocketAddress isa = new InetSocketAddress(hostname, port); addProxyWithChecks(proxySet, proxies, new ProxyHolder(hostname, isa)); } private void addProxyWithChecks(final Set<ProxyHolder> set, final Queue<ProxyHolder> queue, final ProxyHolder ph) { if (set.contains(ph)) { LOG.info("We already know about proxy "+ph+" in {}", set); return; } final Socket sock = new Socket(); try { sock.connect(ph.isa, 60*1000); synchronized (set) { if (!set.contains(ph)) { set.add(ph); queue.add(ph); LOG.info("Queue is now: {}", queue); } } } catch (final IOException e) { LOG.error("Could not connect to: {}", ph); sendErrorMessage(ph.isa, e.getMessage()); onCouldNotConnect(ph.isa); } finally { try { sock.close(); } catch (final IOException e) { LOG.info("Exception closing", e); } } } private final Map<String, String> secretKeys = new ConcurrentHashMap<String, String>(); private String getSecretKey(final String jid) { synchronized (secretKeys) { if (secretKeys.containsKey(jid)) { return secretKeys.get(jid); } final String key = CommonUtils.generateBase64Key(); secretKeys.put(jid, key); return key; } } protected boolean isLanternJid(final String from) { // Here's the format we're looking for: "-la-" if (from.contains("/"+UNCENSORED_ID)) { LOG.info("Returning Lantern TRUE for from: {}", from); return true; } return false; } @Override public void onCouldNotConnect(final InetSocketAddress proxyAddress) { // This can happen in several scenarios. First, it can happen if you've // actually disconnected from the internet. Second, it can happen if // the proxy is blocked. Third, it can happen when the proxy is simply // down for some reason. LOG.info("COULD NOT CONNECT TO STANDARD PROXY!! Proxy address: {}", proxyAddress); // For now we assume this is because we've lost our connection. //onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress), // this.proxySet, this.proxies); } @Override public void onCouldNotConnectToLae(final InetSocketAddress proxyAddress) { LOG.info("COULD NOT CONNECT TO LAE PROXY!! Proxy address: {}", proxyAddress); // For now we assume this is because we've lost our connection. //onCouldNotConnect(new ProxyHolder(proxyAddress.getHostName(), proxyAddress), // this.laeProxySet, this.laeProxies); } private void onCouldNotConnect(final ProxyHolder proxyAddress, final Set<ProxyHolder> set, final Queue<ProxyHolder> queue){ LOG.info("COULD NOT CONNECT!! Proxy address: {}", proxyAddress); synchronized (this.proxySet) { set.remove(proxyAddress); queue.remove(proxyAddress); } } @Override public void onCouldNotConnectToPeer(final URI peerUri) { removePeer(peerUri); } @Override public void onError(final URI peerUri) { removePeer(peerUri); } private void removePeer(final URI uri) { // We always remove from both since their trusted status could have // changed removePeerUri(uri); removeAnonymousPeerUri(uri); } private void removePeerUri(final URI peerUri) { LOG.info("Removing peer with URI: {}", peerUri); remove(peerUri, this.peerProxySet, this.peerProxies); } private void removeAnonymousPeerUri(final URI peerUri) { LOG.info("Removing anonymous peer with URI: {}", peerUri); remove(peerUri, this.anonymousProxySet, this.anonymousProxies); } private void remove(final URI peerUri, final Set<URI> set, final Queue<URI> queue) { LOG.info("Removing peer with URI: {}", peerUri); synchronized (set) { set.remove(peerUri); queue.remove(peerUri); } } @Override public InetSocketAddress getLaeProxy() { return getProxy(this.laeProxies); } @Override public InetSocketAddress getProxy() { return getProxy(this.proxies); } @Override public URI getAnonymousProxy() { LOG.info("Getting anonymous proxy"); return getProxyUri(this.anonymousProxies); } @Override public URI getPeerProxy() { LOG.info("Getting peer proxy"); final URI proxy = getProxyUri(this.peerProxies); if (proxy == null) { LOG.info("Peer proxies {} and anonymous proxies {}", this.peerProxies, this.anonymousProxies); } return proxy; } private URI getProxyUri(final Queue<URI> queue) { if (queue.isEmpty()) { LOG.info("No proxy URIs"); return null; } final URI proxy = queue.remove(); queue.add(proxy); LOG.info("FIFO queue is now: {}", queue); return proxy; } private InetSocketAddress getProxy(final Queue<ProxyHolder> queue) { if (queue.isEmpty()) { LOG.info("No proxy addresses"); return null; } final ProxyHolder proxy = queue.remove(); queue.add(proxy); LOG.info("FIFO queue is now: {}", queue); return proxy.isa; } public XmppP2PClient getP2PClient() { return client; } private static final class ProxyHolder { private final String id; private final InetSocketAddress isa; private ProxyHolder(final String id, final InetSocketAddress isa) { this.id = id; this.isa = isa; } @Override public String toString() { return "ProxyHolder [isa=" + isa + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isa == null) ? 0 : isa.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProxyHolder other = (ProxyHolder) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (isa == null) { if (other.isa != null) return false; } else if (!isa.equals(other.isa)) return false; return true; } } private ServerSocketFactory newTlsServerSocketFactory() { LOG.info("Creating TLS server socket factory"); String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } try { final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(LanternHub.getKeyStoreManager().keyStoreAsInputStream(), LanternHub.getKeyStoreManager().getKeyStorePassword()); // Set up key manager factory to use our key store final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, LanternHub.getKeyStoreManager().getCertificatePassword()); // Initialize the SSLContext to work with our key managers. final SSLContext serverContext = SSLContext.getInstance("TLS"); serverContext.init(kmf.getKeyManagers(), null, null); return serverContext.getServerSocketFactory(); } catch (final KeyStoreException e) { throw new Error("Could not create SSL server socket factory.", e); } catch (final NoSuchAlgorithmException e) { throw new Error("Could not create SSL server socket factory.", e); } catch (final CertificateException e) { throw new Error("Could not create SSL server socket factory.", e); } catch (final IOException e) { throw new Error("Could not create SSL server socket factory.", e); } catch (final UnrecoverableKeyException e) { throw new Error("Could not create SSL server socket factory.", e); } catch (final KeyManagementException e) { throw new Error("Could not create SSL server socket factory.", e); } } private SocketFactory newTlsSocketFactory() { LOG.info("Creating TLS socket factory"); try { final SSLContext clientContext = SSLContext.getInstance("TLS"); clientContext.init(null, LanternHub.getKeyStoreManager().getTrustManagers(), null); return clientContext.getSocketFactory(); } catch (final NoSuchAlgorithmException e) { LOG.error("No TLS?", e); throw new Error("No TLS?", e); } catch (final KeyManagementException e) { LOG.error("Key managmement issue?", e); throw new Error("Key managmement issue?", e); } } }
package org.petapico.npop; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPOutputStream; import net.trustyuri.TrustyUriException; import org.nanopub.MalformedNanopubException; import org.nanopub.MultiNanopubRdfHandler; import org.nanopub.MultiNanopubRdfHandler.NanopubHandler; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.NanopubRdfHandler; import org.nanopub.NanopubUtils; import org.nanopub.trusty.FixTrustyNanopub; import org.openrdf.model.URI; import org.openrdf.model.impl.ContextStatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; public class Reuse { @com.beust.jcommander.Parameter(description = "input-nanopubs", required = true) private List<File> inputNanopubs = new ArrayList<File>(); @com.beust.jcommander.Parameter(names = "-x", description = "Nanopubs to be reused (if not given, an initial dataset is created)") private File reuseNanopubFile; @com.beust.jcommander.Parameter(names = "-n", description = "Output new nanopubs") private boolean outputNew = false; @com.beust.jcommander.Parameter(names = "-o", description = "Output file (requires option -n to be set)") private File outputFile; @com.beust.jcommander.Parameter(names = "-a", description = "Output file of all nanopublications (-x file needs to be a full nanopub file)") private File allOutputFile; @com.beust.jcommander.Parameter(names = "-c", description = "Output cache file, which can afterwards be used for argument -x or to create an index)") private File cacheFile; @com.beust.jcommander.Parameter(names = "-r", description = "Append line to this table file") private File tableFile; @com.beust.jcommander.Parameter(names = "--in-format", description = "Format of the input nanopubs: trig, nq, trix, trig.gz, ...") private String inFormat; @com.beust.jcommander.Parameter(names = "--reuse-format", description = "Format of the nanopubs to be reused: trig, nq, trix, trig.gz, ...") private String reuseFormat; @com.beust.jcommander.Parameter(names = "--out-format", description = "Format of the output nanopubs: trig, nq, trix, trig.gz, ...") private String outFormat; @com.beust.jcommander.Parameter(names = "-f", description = "Fingerprinting options") private String fingerprintOptions; @com.beust.jcommander.Parameter(names = "-s", description = "Add npx:supersedes backlinks for changed nanopublications") private boolean addSupersedesBacklinks = false; @com.beust.jcommander.Parameter(names = "-t", description = "Topic options") private String topicOptions; public static void main(String[] args) { NanopubImpl.ensureLoaded(); Reuse obj = new Reuse(); JCommander jc = new JCommander(obj); try { jc.parse(args); } catch (ParameterException ex) { jc.usage(); System.exit(1); } obj.init(); try { obj.run(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private static final String multipleNanopubs = "MULTI"; private static final String matchedNanopub = "MATCHED"; private RDFFormat rdfInFormat, rdfReuseFormat, rdfOutFormat; private PrintStream outputStream = System.out; private PrintStream allOutputStream; private PrintStream cacheStream; private Map<String,String> reusableNanopubs = new HashMap<>(); private Map<String,String> existingTopics = new HashMap<>(); private Map<String,String> reuseNanopubMap = new HashMap<>(); private int reusableCount, uniqueReusableCount, inputCount, reuseCount, inTopicDuplCount, outTopicDuplCount, topicMatchErrors, topicMatchCount; private Fingerprint fingerprint; private Topic topic; private void init() { try { fingerprint = Fingerprint.getInstance(fingerprintOptions); } catch (ParameterException ex) { System.err.println(ex); } try { topic = Topic.getInstance(topicOptions); } catch (ParameterException ex) { System.err.println(ex); } } private void run() throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException, TrustyUriException { reusableCount = 0; uniqueReusableCount = 0; inputCount = 0; reuseCount = 0; inTopicDuplCount = 0; topicMatchCount = 0; topicMatchErrors = 0; if (outputFile == null) { if (outFormat == null) { outFormat = "trig"; } rdfOutFormat = Rio.getParserFormatForFileName("file." + outFormat); } else { rdfOutFormat = Rio.getParserFormatForFileName(outputFile.getName()); } if (reuseNanopubFile == null) { // Initial dataset creation } else if (reuseNanopubFile.getName().endsWith(".txt")) { // Reuse nanopubs from cache file if (allOutputFile != null) { throw new RuntimeException("-x needs to specify a full nanopub file if -a is specified"); } BufferedReader br = null; try { br = new BufferedReader(new FileReader(reuseNanopubFile)); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; String[] columns = line.split(" "); String uri = columns[0]; String fingerprint = columns[1]; reusableNanopubs.put(fingerprint, uri); reusableCount++; if (addSupersedesBacklinks) { String topic = columns[2]; recordTopic(topic, uri); } } } finally { if (br != null) br.close(); } } else { // Reuse nanopubs from full nanopub file if (reuseFormat != null) { rdfReuseFormat = Rio.getParserFormatForFileName("file." + reuseFormat); } else { rdfReuseFormat = Rio.getParserFormatForFileName(reuseNanopubFile.toString()); } MultiNanopubRdfHandler.process(rdfReuseFormat, reuseNanopubFile, new NanopubHandler() { @Override public void handleNanopub(Nanopub np) { try { String fp = fingerprint.getFingerprint(np); String uri = np.getUri().toString(); reusableNanopubs.put(fp, uri); reusableCount++; if (addSupersedesBacklinks) { recordTopic(topic.getTopic(np), uri); } if (allOutputFile != null) { reuseNanopubMap.put(fp, NanopubUtils.writeToString(np, rdfOutFormat)); } } catch (IOException ex) { throw new RuntimeException(ex); } catch (RDFHandlerException ex) { throw new RuntimeException(ex); } } }); } uniqueReusableCount = reusableNanopubs.size(); // Reuse matching nanopubs: if (cacheFile != null) { cacheStream = new PrintStream(cacheFile); } for (File inputFile : inputNanopubs) { if (inFormat != null) { rdfInFormat = Rio.getParserFormatForFileName("file." + inFormat); } else { rdfInFormat = Rio.getParserFormatForFileName(inputFile.toString()); } if (outputFile != null) { if (outputFile.getName().endsWith(".gz")) { outputStream = new PrintStream(new GZIPOutputStream(new FileOutputStream(outputFile))); } else { outputStream = new PrintStream(new FileOutputStream(outputFile)); } } if (allOutputFile != null) { if (allOutputFile.getName().endsWith(".gz")) { allOutputStream = new PrintStream(new GZIPOutputStream(new FileOutputStream(allOutputFile))); } else { allOutputStream = new PrintStream(new FileOutputStream(allOutputFile)); } } MultiNanopubRdfHandler.process(rdfInFormat, inputFile, new NanopubHandler() { @Override public void handleNanopub(Nanopub np) { try { process(np); } catch (Exception ex) { throw new RuntimeException(ex); } } }); outputStream.flush(); if (outputStream != System.out) { outputStream.close(); } if (allOutputStream != null) { allOutputStream.flush(); allOutputStream.close(); } if (cacheStream != null) { cacheStream.flush(); cacheStream.close(); } if (tableFile != null) { PrintStream st = new PrintStream(new FileOutputStream(tableFile, true)); if (addSupersedesBacklinks) { st.println(inputFile.getName() + "," + reusableCount + "," + inputCount + "," + reuseCount + "," + topicMatchCount + "," + inTopicDuplCount + "," + outTopicDuplCount + "," + topicMatchErrors); } else { st.println(inputFile.getName() + "," + reusableCount + "," + inputCount + "," + reuseCount); } st.close(); } System.err.println("Older dataset count (unique): " + reusableCount + " (" + uniqueReusableCount + ")"); System.err.println("Newer dataset count: " + inputCount); System.err.println("Reuse count: " + reuseCount); if (addSupersedesBacklinks) { System.err.println("Topic match count: " + topicMatchCount); System.err.println("Duplicate topics in older dataset: " + inTopicDuplCount); System.err.println("Duplicate topics in newer dataset: " + outTopicDuplCount); System.err.println("Total topic matching errors: " + topicMatchErrors); } } } private void recordTopic(String topic, String uri) { if (existingTopics.containsKey(topic)) { existingTopics.put(topic, multipleNanopubs); inTopicDuplCount++; topicMatchErrors++; } else { existingTopics.put(topic, uri); } } private void process(Nanopub np) throws IOException, RDFHandlerException, MalformedNanopubException, TrustyUriException { inputCount++; String fp = fingerprint.getFingerprint(np); String t = null; if (addSupersedesBacklinks) { t = topic.getTopic(np); } String uri = np.getUri().toString(); if (reusableNanopubs.containsKey(fp)) { reuseCount++; uri = reusableNanopubs.get(fp); if (addSupersedesBacklinks) { String et = existingTopics.get(t); if (et == multipleNanopubs || et == matchedNanopub) { topicMatchErrors++; } existingTopics.put(t, matchedNanopub); } if (allOutputStream != null) { allOutputStream.println(reuseNanopubMap.get(fp)); } } else { if (addSupersedesBacklinks) { if (existingTopics.containsKey(t)) { String et = existingTopics.get(t); if (et == multipleNanopubs) { topicMatchErrors++; } else if (et == matchedNanopub) { topicMatchErrors++; outTopicDuplCount++; } else { topicMatchCount++; String oldNpUri = existingTopics.get(t); existingTopics.put(t, matchedNanopub); np = addSupersedesBacklink(np, new URIImpl(oldNpUri)); uri = np.getUri().toString(); } } } if (outputNew) { NanopubUtils.writeToStream(np, outputStream, rdfOutFormat); } if (allOutputStream != null) { NanopubUtils.writeToStream(np, allOutputStream, rdfOutFormat); } } if (cacheStream != null) { if (addSupersedesBacklinks) { cacheStream.println(uri + " " + fp + " " + t); } else { cacheStream.println(uri + " " + fp); } } } private Nanopub addSupersedesBacklink(final Nanopub newNp, final URI oldUri) throws RDFHandlerException, MalformedNanopubException, TrustyUriException { SupersedesLinkAdder linkAdder = new SupersedesLinkAdder(oldUri, newNp); NanopubUtils.propagateToHandler(newNp, linkAdder); return FixTrustyNanopub.fix(linkAdder.getNanopub()); } private class SupersedesLinkAdder extends NanopubRdfHandler { private URI oldUri; private Nanopub newNp; public SupersedesLinkAdder(URI oldUri, Nanopub newNp) { this.oldUri = oldUri; this.newNp = newNp; } @Override public void endRDF() throws RDFHandlerException { handleStatement(new ContextStatementImpl( newNp.getUri(), Nanopub.SUPERSEDES, oldUri, newNp.getPubinfoUri())); super.endRDF(); } } }
/** * @file 2016/12/07 */ package quiz.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; /** * MySQL * * @author Yuka Yoshikawa * */ public class SqlDataStore implements DataStore { /** * @DB * * @DB EnglishWordQuiz * @ EnglishWord * * @userID root * @password root * */ /** JDBC */ private final String driver = "com.mysql.jdbc.Driver"; private final String jdbc = "jdbc:mysql://localhost/englishwordquiz"; private final String user = "root"; private final String pass = "root"; private Connection con = null; /** SQL */ private Statement ps = null; /** * A DB * * @see quiz.model.DataStore#open() */ @Override public void open() throws Exception { /* JDBC */ Class.forName(driver); con = DriverManager.getConnection(jdbc, user, pass); } /** * A DB * * @throws java.lang.Exception * * * @note throws */ @Override public void close() throws Exception { if (ps != null) { ps.close(); } if (con != null) { con.close(); } } /** * A * * @throws java.lang.Exception * * * @note throws */ @Override public ArrayList<EnglishWordBean> getAll() throws Exception { String sql = "select * from englishword "; ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(sql); ArrayList<EnglishWordBean> allData = new ArrayList<EnglishWordBean>(); while (rs.next()) { EnglishWordBean bean = new EnglishWordBean(); bean.setId(rs.getInt("id")); bean.setWord(rs.getString("word")); bean.setPart(Part.getPart(rs.getString("part"))); bean.setMean(rs.getString("mean")); bean.setUpdateTime(rs.getTimestamp("updated_at")); allData.add(bean); } return allData; } /** * A1 * * @throws java.lang.Exception * * * @note throws */ @Override public void insert(EnglishWordBean bean) throws Exception { String sql = "insert into englishword (word, part, mean ) values ( '" + bean.getWord() + "' , '" + bean.getPart().toString() + "' , '" + bean.getMean() + "'"; ps = con.createStatement(); ps.executeUpdate(sql); } /** * C1 * * @throws java.lang.Exception * * * @note throws */ @Override public void update(EnglishWordBean bean) throws Exception { // TODO C1 } /** * B1 * * @throws java.lang.Exception * * * @note throws */ @Override public void delete(EnglishWordBean bean) throws Exception { // TODO B1 } /** * A1 * * @throws java.lang.Exception * * * @note throws */ @Override public EnglishWordBean searchWord(EnglishWordBean bean) throws Exception { String sql = "select * from englishword where word like '" + bean.getWord() + "' " + "and mean like '%" + bean.getMean() + "%' order by updated_at desc limit 1 "; ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(sql); EnglishWordBean searchBean = new EnglishWordBean(); if (rs.next()) { searchBean.setId(rs.getInt("id")); searchBean.setWord(rs.getString("word")); searchBean.setPart(Part.getPart(rs.getString("part"))); searchBean.setMean(rs.getString("mean")); searchBean.setUpdateTime(rs.getTimestamp("updated_at")); } return searchBean; } /** * A1 * * @throws java.lang.Exception * * * @note throws */ @Override public EnglishWordBean getRandom() throws Exception { String sql = "select * from englishword order by rand() limit 1 "; ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(sql); EnglishWordBean randomBean = new EnglishWordBean(); if (rs.next()) { randomBean.setId(rs.getInt("id")); randomBean.setWord(rs.getString("word")); randomBean.setPart(Part.getPart(rs.getString("part"))); randomBean.setMean(rs.getString("mean")); randomBean.setUpdateTime(rs.getTimestamp("updated_at")); } return randomBean; } }
package refactoring; import java.io.IOException; import java.util.List; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.emftext.language.java.commons.Commentable; import org.emftext.language.java.containers.CompilationUnit; import org.emftext.language.java.expressions.ExpressionsFactory; import org.emftext.language.java.expressions.UnaryExpression; import org.emftext.language.java.expressions.impl.ExpressionsFactoryImpl; import org.emftext.language.java.literals.BooleanLiteral; import org.emftext.language.java.literals.LiteralsFactory; import org.emftext.language.java.literals.impl.LiteralsFactoryImpl; import org.emftext.language.java.members.Method; import org.emftext.language.java.resource.JaMoPPUtil; import org.emftext.language.java.statements.Assert; import org.emftext.language.java.statements.LocalVariableStatement; import org.emftext.language.java.statements.StatementsFactory; import org.emftext.language.java.statements.impl.StatementsFactoryImpl; /* * projects needed in the build path: * * org.emftext.language.java.resource * org.emftext.language.java.resource * * as JaMoPP maven repo seems broken right now. * * TODO: use maven dependency instead as soon as possible */ /** * A simple demonstration of using JaMoPP to modify existing .java files. * * @author Christian Busch */ public class Refactoring { public static void main(String[] args) { JaMoPPUtil.initialize(); // initialize everything (has to be done once.) ResourceSet resSet = new ResourceSetImpl(); Resource resource = resSet.getResource( URI.createURI("src/test/java/input/CalculatorPow.java"), true); CompilationUnit cu = (CompilationUnit) resource.getContents().get(0); List<Method> methods = cu.getContainedClass().getMethods(); EObject content = methods.get(0).getFirstChildByType( LocalVariableStatement.class); StatementsFactory statFac = new StatementsFactoryImpl(); ExpressionsFactory expFac = new ExpressionsFactoryImpl(); LiteralsFactory litFac = new LiteralsFactoryImpl(); Assert newAss = statFac.createAssert(); UnaryExpression exp = expFac.createUnaryExpression(); BooleanLiteral boo = litFac.createBooleanLiteral(); boo.setValue(false); exp.setChild(boo); newAss.setCondition(exp); ((Commentable) content).addBeforeContainingStatement(newAss); try { resource.save(null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package techreborn.init; import net.fabricmc.fabric.api.loot.v1.FabricLootPoolBuilder; import net.fabricmc.fabric.api.loot.v1.event.LootTableLoadingCallback; import net.minecraft.item.ItemConvertible; import net.minecraft.item.Items; import net.minecraft.loot.LootPool; import net.minecraft.loot.entry.ItemEntry; import net.minecraft.loot.entry.LootPoolEntry; import net.minecraft.loot.function.SetCountLootFunction; import net.minecraft.loot.function.SetDamageLootFunction; import net.minecraft.loot.provider.number.UniformLootNumberProvider; import techreborn.config.TechRebornConfig; import techreborn.init.TRContent.Ingots; import techreborn.init.TRContent.Parts; public class ModLoot { public static void init() { LootPoolEntry copperIngot = makeEntry(Items.COPPER_INGOT); LootPoolEntry tinIngot = makeEntry(Ingots.TIN); LootPoolEntry leadIngot = makeEntry(Ingots.LEAD); LootPoolEntry silverIngot = makeEntry(Ingots.SILVER); LootPoolEntry refinedIronIngot = makeEntry(Ingots.REFINED_IRON); LootPoolEntry advancedAlloyIngot = makeEntry(Ingots.ADVANCED_ALLOY); LootPoolEntry basicFrame = makeEntry(TRContent.MachineBlocks.BASIC.frame.asItem()); LootPoolEntry basicCircuit = makeEntry(Parts.ELECTRONIC_CIRCUIT); LootPoolEntry rubberSapling = makeEntry(TRContent.RUBBER_SAPLING, 25); LootPool poolBasic = FabricLootPoolBuilder.builder().withEntry(copperIngot).withEntry(tinIngot) .withEntry(leadIngot).withEntry(silverIngot).withEntry(refinedIronIngot).withEntry(advancedAlloyIngot) .withEntry(basicFrame).withEntry(basicCircuit).withEntry(rubberSapling).rolls(UniformLootNumberProvider.create(1.0f, 2.0f)) .build(); LootPoolEntry aluminumIngot = makeEntry(Ingots.ALUMINUM); LootPoolEntry electrumIngot = makeEntry(Ingots.ELECTRUM); LootPoolEntry invarIngot = makeEntry(Ingots.INVAR); LootPoolEntry nickelIngot = makeEntry(Ingots.NICKEL); LootPoolEntry steelIngot = makeEntry(Ingots.STEEL); LootPoolEntry zincIngot = makeEntry(Ingots.ZINC); LootPoolEntry advancedFrame = makeEntry(TRContent.MachineBlocks.ADVANCED.frame.asItem()); LootPoolEntry advancedCircuit = makeEntry(Parts.ADVANCED_CIRCUIT); LootPoolEntry dataStorageChip = makeEntry(Parts.DATA_STORAGE_CHIP); LootPool poolAdvanced = FabricLootPoolBuilder.builder().withEntry(aluminumIngot).withEntry(electrumIngot) .withEntry(invarIngot).withEntry(nickelIngot).withEntry(steelIngot).withEntry(zincIngot) .withEntry(advancedFrame).withEntry(advancedCircuit).withEntry(dataStorageChip).rolls(UniformLootNumberProvider.create(1.0f, 3.0f)) .build(); LootPoolEntry chromeIngot = makeEntry(Ingots.CHROME); LootPoolEntry iridiumIngot = makeEntry(Ingots.IRIDIUM); LootPoolEntry platinumIngot = makeEntry(Ingots.PLATINUM); LootPoolEntry titaniumIngot = makeEntry(Ingots.TITANIUM); LootPoolEntry tungstenIngot = makeEntry(Ingots.TUNGSTEN); LootPoolEntry tungstensteelIngot = makeEntry(Ingots.TUNGSTENSTEEL); LootPoolEntry industrialFrame = makeEntry(TRContent.MachineBlocks.INDUSTRIAL.frame.asItem()); LootPoolEntry industrialCircuit = makeEntry(Parts.INDUSTRIAL_CIRCUIT); LootPoolEntry energyFlowChip = makeEntry(Parts.ENERGY_FLOW_CHIP); LootPool poolIndustrial = FabricLootPoolBuilder.builder().withEntry(chromeIngot).withEntry(iridiumIngot) .withEntry(platinumIngot).withEntry(titaniumIngot).withEntry(tungstenIngot).withEntry(tungstensteelIngot) .withEntry(industrialFrame).withEntry(industrialCircuit).withEntry(energyFlowChip).rolls(UniformLootNumberProvider.create(1.0f, 3.0f)) .build(); LootPoolEntry rubber = ItemEntry.builder(Parts.RUBBER).weight(10).build(); LootPoolEntry treeTap = ItemEntry.builder(TRContent.TREE_TAP).weight(10) .apply(SetDamageLootFunction.builder(UniformLootNumberProvider.create(0.0f, 0.9f))).build(); LootPool poolFishingJunk = FabricLootPoolBuilder.builder().withEntry(rubber).withEntry(treeTap).build(); LootTableLoadingCallback.EVENT.register((resourceManager, lootManager, ident, supplier, setter) -> { String stringId = ident.toString(); if (!stringId.startsWith("minecraft:chests")) { return; } if (TechRebornConfig.enableOverworldLoot) { switch (stringId) { case "minecraft:chests/abandoned_mineshaft", "minecraft:chests/desert_pyramid", "minecraft:chests/igloo_chest", "minecraft:chests/jungle_temple", "minecraft:chests/simple_dungeon", "minecraft:chests/shipwreck_treasure", "minecraft:chest/underwater_ruin_small", "minecraft:chests/village/village_weaponsmith", "minecraft:chests/village/village_armorer", "minecraft:chests/village/village_toolsmith" -> supplier.withPool(poolBasic); case "minecraft:chests/stronghold_corridor", "minecraft:chests/stronghold_crossing", "minecraft:chests/stronghold_library", "minecraft:chest/underwater_ruin_big", "minecraft:chests/pillager_outpost" -> supplier.withPool(poolAdvanced); case "minecraft:chests/woodland_mansion", "minecraft:chests/ancient_city" -> supplier.withPool(poolIndustrial); } } if (TechRebornConfig.enableNetherLoot) { if (stringId.equals("minecraft:chests/nether_bridge") || stringId.equals("minecraft:chests/bastion_bridge") || stringId.equals("minecraft:chests/bastion_hoglin_stable") || stringId.equals("minecraft:chests/bastion_treasure") || stringId.equals("minecraft:chests/bastion_other")) { supplier.withPool(poolAdvanced); } } if (TechRebornConfig.enableEndLoot) { if (stringId.equals("minecraft:chests/end_city_treasure")) { supplier.withPool(poolIndustrial); } } if (TechRebornConfig.enableFishingJunkLoot) { if (stringId.equals("minecraft:gameplay/fishing/junk")) { supplier.withPool(poolFishingJunk); } } }); } /** * Makes loot entry from item provided * * @param item {@link ItemConvertible} Item to include into LootEntry * @return {@link LootPoolEntry} Entry for item provided */ private static LootPoolEntry makeEntry(ItemConvertible item) { return makeEntry(item, 5); } /** * Makes loot entry from item provided with weight provided * * @param item {@link ItemConvertible} Item to include into LootEntry * @param weight {@code int} Weight of that item * @return {@link LootPoolEntry} Entry for item and weight provided */ private static LootPoolEntry makeEntry(ItemConvertible item, int weight) { return ItemEntry.builder(item).weight(weight) .apply(SetCountLootFunction.builder(UniformLootNumberProvider.create(1.0f, 2.0f))).build(); } }
package teetime.framework; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import teetime.framework.signal.ISignal; import teetime.framework.validation.InvalidPortConnection; public abstract class Stage { private final String id; private final static Map<String, Integer> instancesCounter = new HashMap<String, Integer>(); /** * A unique logger instance per stage instance */ protected final Logger logger; // NOPMD protected Stage() { this.id = this.nameInstance(); this.logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + this.id); } public String getId() { return this.id; } @Override public String toString() { return this.getClass().getName() + ": " + this.getId(); } private String nameInstance() { int instances = 0; String id; String simpleName = this.getClass().getSimpleName(); if (instancesCounter.containsKey(simpleName)) { instances = instancesCounter.get(simpleName); } id = simpleName + "-" + instances; instancesCounter.put(simpleName, ++instances); return id; } // public abstract Stage getParentStage(); // public abstract void setParentStage(Stage parentStage, int index); /** * * @param invalidPortConnections * <i>(Passed as parameter for performance reasons)</i> */ public abstract void validateOutputPorts(List<InvalidPortConnection> invalidPortConnections); protected abstract void executeWithPorts(); protected abstract void onSignal(ISignal signal, InputPort<?> inputPort); protected abstract TerminationStrategy getTerminationStrategy(); protected abstract void terminate(); protected abstract boolean shouldBeTerminated(); }
package teetime.framework; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import teetime.framework.signal.ISignal; import teetime.framework.validation.InvalidPortConnection; public abstract class Stage { // NOPMD (should not start with "Abstract") private final String id; private static final Map<String, Integer> INSTANCES_COUNTER = new ConcurrentHashMap<String, Integer>(); /** * A unique logger instance per stage instance */ protected final Logger logger; // NOPMD protected Stage() { this.id = this.createId(); this.logger = LoggerFactory.getLogger(this.getClass().getName() + "-" + this.id); } public String getId() { return this.id; } @Override public String toString() { return this.getClass().getName() + ": " + this.getId(); } private String createId() { String simpleName = this.getClass().getSimpleName(); Integer numInstances = INSTANCES_COUNTER.get(simpleName); if (null == numInstances) { numInstances = 0; } String newId = simpleName + "-" + numInstances; INSTANCES_COUNTER.put(simpleName, ++numInstances); return newId; } // public abstract Stage getParentStage(); // public abstract void setParentStage(Stage parentStage, int index); /** * * @param invalidPortConnections * <i>(Passed as parameter for performance reasons)</i> */ public abstract void validateOutputPorts(List<InvalidPortConnection> invalidPortConnections); protected abstract void executeWithPorts(); protected abstract void onSignal(ISignal signal, InputPort<?> inputPort); protected abstract TerminationStrategy getTerminationStrategy(); protected abstract void terminate(); protected abstract boolean shouldBeTerminated(); }
package think.rpgitems; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.server.ServerLoadEvent; import org.bukkit.plugin.InvalidDescriptionException; import org.bukkit.plugin.InvalidPluginException; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.librazy.nclangchecker.LangKey; import think.rpgitems.data.Font; import think.rpgitems.item.ItemManager; import think.rpgitems.power.PowerManager; import think.rpgitems.power.PowerTicker; import think.rpgitems.power.Trigger; import think.rpgitems.power.impl.BasePower; import think.rpgitems.support.WGSupport; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RPGItems extends JavaPlugin { private static int serial; private static String pluginMCVersion; private static String serverMCVersion; public static Logger logger; public static RPGItems plugin; private static Events listener; List<Plugin> managedPlugins = new ArrayList<>(); public I18n i18n; public Configuration cfg; @Override public void onLoad() { plugin = this; logger = this.getLogger(); String version = getDescription().getVersion(); Pattern serialPattern = Pattern.compile("\\d+\\.\\d+\\.(\\d+)-mc([\\d.]+)"); Matcher serialMatcher = serialPattern.matcher(version); if (serialMatcher.matches()) { serial = Integer.parseInt(serialMatcher.group(1)); pluginMCVersion = serialMatcher.group(2); } String serverVersion = Bukkit.getVersion(); Pattern mcVersionPattern = Pattern.compile("\\(MC:\\s+([\\d.]+)\\)"); Matcher mcVersionMatcher = mcVersionPattern.matcher(serverVersion); if (mcVersionMatcher.find()) { serverMCVersion = mcVersionMatcher.group(1); } logger.log(Level.INFO, "Plugin serial: '" + serial + "', native version: '" + pluginMCVersion + "', server version: '" + serverMCVersion + "'."); cfg = new Configuration(this); cfg.load(); i18n = new I18n(this, cfg.language); PowerManager.addDescriptionResolver(RPGItems.plugin, (power, property) -> { if (property == null) { @LangKey(skipCheck = true) String powerKey = "power.properties." + power.getKey() + ".main_description"; return I18n.format(powerKey); } @LangKey(skipCheck = true) String key = "power.properties." + power.getKey() + "." + property; if (I18n.getInstance().hasKey(key)) { return I18n.format(key); } @LangKey(skipCheck = true) String baseKey = "power.properties.base." + property; if (I18n.getInstance().hasKey(baseKey)) { return I18n.format(baseKey); } return null; }); PowerManager.registerPowers(RPGItems.plugin, BasePower.class.getPackage().getName()); saveDefaultConfig(); Font.load(); WGSupport.load(); loadExtensions(); } public void loadExtensions() { File extDir = new File(plugin.getDataFolder(), "ext"); if (extDir.isDirectory() || extDir.mkdirs()) { File[] files = extDir.listFiles((d, n) -> n.endsWith(".jar")); if (files == null) return; for (File file : files) { try { Plugin plugin = Bukkit.getPluginManager().loadPlugin(file); String message = String.format("Loading %s", plugin.getDescription().getFullName()); plugin.getLogger().info(message); plugin.onLoad(); managedPlugins.add(plugin); logger.info("Loaded extension: " + plugin.getName()); } catch (InvalidPluginException | InvalidDescriptionException e) { logger.log(Level.SEVERE, "Error loading extension: " + file.getName(), e); } } } else { logger.severe("Error creating extension directory ./ext"); } } @Override public void onEnable() { Trigger.stopAcceptingRegistrations(); plugin = this; if (plugin.cfg.version.startsWith("0.") && Double.parseDouble(plugin.cfg.version) < 0.5) { Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "======================================"); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "You current version of RPGItems config is not supported."); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Please run your server with latest version of RPGItems 3.5 before update."); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "======================================"); throw new IllegalStateException(); } else if (plugin.cfg.version.equals("0.5")) { cfg.pidCompat = true; } if (Bukkit.class.getPackage().getImplementationVersion().startsWith("git-Bukkit-")) { Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "======================================"); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "RPGItems plugin requires Spigot API, Please make sure you are using Spigot."); Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "======================================"); } try { Bukkit.spigot(); } catch (NoSuchMethodError e) { getCommand("rpgitem").setExecutor((sender, command, label, args) -> { sender.sendMessage(ChatColor.RED + "======================================"); sender.sendMessage(ChatColor.RED + "RPGItems plugin requires Spigot API, Please make sure you are using Spigot."); sender.sendMessage(ChatColor.RED + "======================================"); return true; }); } if (cfg.localeInv) { Events.useLocaleInv = true; } Handler commandHandler = new Handler(this, i18n); getCommand("rpgitem").setExecutor(commandHandler); getCommand("rpgitem").setTabCompleter(commandHandler); getServer().getPluginManager().registerEvents(new ServerLoadListener(), this); managedPlugins.forEach(Bukkit.getPluginManager()::enablePlugin); } public static int getSerial() { return serial; } public static String getPluginMCVersion() { return pluginMCVersion; } public static String getServerMCVersion() { return serverMCVersion; } private class ServerLoadListener implements Listener { @EventHandler public void onServerLoad(ServerLoadEvent event) { HandlerList.unregisterAll(this); getServer().getPluginManager().registerEvents(listener = new Events(), RPGItems.this); WGSupport.init(RPGItems.this); logger.info("Loading RPGItems..."); ItemManager.load(RPGItems.this); logger.info("Done"); new PowerTicker().runTaskTimer(RPGItems.this, 0, 1); } } @Override public void onDisable() { WGSupport.unload(); HandlerList.unregisterAll(listener); getCommand("rpgitem").setExecutor(null); getCommand("rpgitem").setTabCompleter(null); this.getServer().getScheduler().cancelTasks(plugin); ItemManager.unload(); managedPlugins.forEach(Bukkit.getPluginManager()::disablePlugin); } }
package uelbox; import javax.el.ELContext; import javax.el.ELResolver; import javax.el.FunctionMapper; import javax.el.ValueExpression; import javax.el.VariableMapper; import org.apache.commons.lang3.Validate; /** * ELContext wrapper which wraps the ELResolver and may shadow variables, locale * settings, and context objects. */ public abstract class ELContextWrapper extends ELContext { private final ELResolver elResolver; private final VariableMapper variableMapper; protected final ELContext wrapped; /** * Create a new ELContextWrapper. * * @param wrapped */ protected ELContextWrapper(ELContext wrapped) { this.wrapped = Validate.notNull(wrapped); this.elResolver = Validate.notNull(wrap(wrapped.getELResolver())); this.variableMapper = new SimpleVariableMapper() { @Override public ValueExpression resolveVariable(String variable) { if (containsVariable(variable)) { return super.resolveVariable(variable); } return ELContextWrapper.this.wrapped.getVariableMapper().resolveVariable(variable); } }; setLocale(wrapped.getLocale()); } /** * Create a wrapped ELResolver for use with the wrapped {@link ELContext}. * * @param elResolver * to wrap * @return {@link ELResolver} */ protected abstract ELResolver wrap(ELResolver elResolver); @Override public ELResolver getELResolver() { return elResolver; } @Override public FunctionMapper getFunctionMapper() { return wrapped.getFunctionMapper(); } @Override public VariableMapper getVariableMapper() { return variableMapper; } @Override @SuppressWarnings("rawtypes") public Object getContext(Class key) { final Object result = super.getContext(key); return result == null ? wrapped.getContext(key) : result; } /** * Convenience method to return a typed context object when key resolves per * documented convention to an object of the same type. * * @param key * @param <T> * @return T * @see ELContext#getContext(Class) */ public final <T> T getTypedContext(Class<T> key) { return UEL.getContext(this, key); } }
package peergos.server.space; import peergos.server.sql.*; import peergos.server.util.Logging; import peergos.shared.*; import peergos.shared.crypto.hash.*; import peergos.shared.io.ipfs.cid.*; import java.sql.*; import java.util.*; import java.util.function.*; import java.util.logging.*; public class JdbcUsageStore implements UsageStore { private static final Logger LOG = Logging.LOG(); private Supplier<Connection> conn; private final SqlSupplier commands; private volatile boolean isClosed; public JdbcUsageStore(Supplier<Connection> conn, SqlSupplier commands) { this.conn = conn; this.commands = commands; init(commands); } private Connection getConnection() { return getConnection(true, true); } private Connection getConnection(boolean autocommit, boolean serializable) { Connection connection = conn.get(); try { if (autocommit) connection.setAutoCommit(true); if (serializable) connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); return connection; } catch (SQLException e) { throw new RuntimeException(e); } } private synchronized void init(SqlSupplier commands) { if (isClosed) return; try (Connection conn = getConnection()) { commands.createTable(commands.createUsageTablesCommand(), conn); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void initialized() { // TODO can we remove this method? } @Override public void addUserIfAbsent(String username) { try (Connection conn = getConnection(true, false); PreparedStatement userInsert = conn.prepareStatement(commands.insertOrIgnoreCommand("INSERT ", "INTO users (name) VALUES(?)")); PreparedStatement select = conn.prepareStatement("SELECT id FROM users WHERE name = ?;"); PreparedStatement usageInsert = conn.prepareStatement(commands.insertOrIgnoreCommand("INSERT ", "INTO userusage (user_id, total_bytes, errored) VALUES(?, ?, ?)"))) { userInsert.setString(1, username); userInsert.executeUpdate(); select.setString(1, username); ResultSet resultSet = select.executeQuery(); resultSet.next(); int userId = resultSet.getInt(1); usageInsert.setInt(1, userId); usageInsert.setLong(2, 0); usageInsert.setBoolean(3, false); usageInsert.executeUpdate(); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public void confirmUsage(String username, PublicKeyHash writer, long usageDelta, boolean errored) { int userId = getUserId(username); try (Connection conn = getConnection(true, false); PreparedStatement insert = conn.prepareStatement( "UPDATE userusage SET total_bytes = total_bytes + ?, errored = ? " + "WHERE user_id = ?;"); PreparedStatement insertPending = conn.prepareStatement( "UPDATE pendingusage SET pending_bytes = ? " + "WHERE writer_id = (SELECT id FROM writers WHERE key_hash = ?);")) { insert.setLong(1, usageDelta); insert.setBoolean(2, errored); insert.setInt(3, userId); int count = insert.executeUpdate(); if (count != 1) throw new IllegalStateException("Didn't update one record!"); insertPending.setLong(1, 0); insertPending.setBytes(2, writer.toBytes()); int count2 = insertPending.executeUpdate(); if (count2 != 1) throw new IllegalStateException("Didn't update one record!"); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public void addPendingUsage(String username, PublicKeyHash writer, int size) { int writerId = getWriterId(writer); try (Connection conn = getConnection(true, false); PreparedStatement insert = conn.prepareStatement("UPDATE pendingusage SET pending_bytes = pending_bytes + ? " + "WHERE writer_id = ?;")) { insert.setLong(1, size); insert.setInt(2, writerId); int count = insert.executeUpdate(); if (count != 1) throw new IllegalStateException("Didn't update one record!"); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public UserUsage getUsage(String username) { int userId = getUserId(username); try (Connection conn = getConnection(); PreparedStatement search = conn.prepareStatement("SELECT pu.writer_id, pu.pending_bytes, uu.total_bytes, uu.errored " + "FROM userusage uu, pendingusage pu WHERE uu.user_id = pu.user_id AND uu.user_id = ?;"); PreparedStatement writerSearch = conn.prepareStatement("SELECT key_hash FROM writers WHERE id = ?;")) { search.setInt(1, userId); ResultSet resultSet = search.executeQuery(); Map<PublicKeyHash, Long> pending = new HashMap<>(); long totalBytes = -1; boolean errored = false; while (resultSet.next()) { writerSearch.setInt(1, resultSet.getInt(1)); ResultSet writerRes = writerSearch.executeQuery(); writerRes.next(); PublicKeyHash writer = PublicKeyHash.decode(writerRes.getBytes(1)); pending.put(writer, resultSet.getLong(2)); if (totalBytes == -1) { totalBytes = resultSet.getLong(3); errored = resultSet.getBoolean(4); } } return new UserUsage(totalBytes, errored, pending); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } private int getUserId(String username) { try (Connection conn = getConnection(); PreparedStatement userSelect = conn.prepareStatement("SELECT id FROM users WHERE name = ?;")) { userSelect.setString(1, username); ResultSet resultSet = userSelect.executeQuery(); resultSet.next(); return resultSet.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } private int getWriterId(PublicKeyHash writer) { try (Connection conn = getConnection(); PreparedStatement writerSelect = conn.prepareStatement("SELECT id FROM writers WHERE key_hash = ?;")) { writerSelect.setBytes(1, writer.toBytes()); ResultSet writerRes = writerSelect.executeQuery(); writerRes.next(); return writerRes.getInt(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public void addWriter(String owner, PublicKeyHash writer) { try (Connection conn = getConnection(true, false); PreparedStatement writerInsert = conn.prepareStatement(commands.insertOrIgnoreCommand("INSERT ", "INTO writers (key_hash) VALUES(?)")); PreparedStatement userSelect = conn.prepareStatement("SELECT id FROM users WHERE name = ?;"); PreparedStatement writerSelect = conn.prepareStatement("SELECT id FROM writers WHERE key_hash = ?;"); PreparedStatement defaultPendingInsert = conn.prepareStatement(commands.insertOrIgnoreCommand( "INSERT ", "INTO pendingusage (user_id, writer_id, pending_bytes) VALUES(?, ?, ?)")); PreparedStatement usageInsert = conn.prepareStatement(commands.insertOrIgnoreCommand("INSERT ", "INTO writerusage (writer_id, user_id, direct_size) VALUES(?, ?, ?)"))) { writerInsert.setBytes(1, writer.toBytes()); writerInsert.executeUpdate(); userSelect.setString(1, owner); ResultSet resultSet = userSelect.executeQuery(); resultSet.next(); int userId = resultSet.getInt(1); writerSelect.setBytes(1, writer.toBytes()); ResultSet writerRes = writerSelect.executeQuery(); writerRes.next(); int writerId = writerRes.getInt(1); defaultPendingInsert.setInt(1, userId); defaultPendingInsert.setInt(2, writerId); defaultPendingInsert.setInt(3, 0); defaultPendingInsert.executeUpdate(); usageInsert.setInt(1, writerId); usageInsert.setInt(2, userId); usageInsert.setInt(3, 0); usageInsert.executeUpdate(); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public Set<PublicKeyHash> getAllWriters() { try (Connection conn = getConnection(); PreparedStatement insert = conn.prepareStatement("SELECT key_hash FROM writers;")) { Set<PublicKeyHash> res = new HashSet<>(); ResultSet resultSet = insert.executeQuery(); while (resultSet.next()) res.add(PublicKeyHash.decode(resultSet.getBytes(1))); return res; } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } private String getOwner(PublicKeyHash writer) { int writerId = getWriterId(writer); try (Connection conn = getConnection(); PreparedStatement search = conn.prepareStatement("SELECT u.name FROM users u, writerusage wu WHERE u.id = wu.user_id AND wu.writer_id = ?;")) { search.setInt(1, writerId); ResultSet resultSet = search.executeQuery(); resultSet.next(); return resultSet.getString(1); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } private PublicKeyHash getWriter(int writerId) { try (Connection conn = getConnection(); PreparedStatement search = conn.prepareStatement("SELECT key_hash FROM writers WHERE id = ?;")) { search.setInt(1, writerId); ResultSet resultSet = search.executeQuery(); resultSet.next(); return PublicKeyHash.decode(resultSet.getBytes(1)); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public WriterUsage getUsage(PublicKeyHash writer) { String owner = getOwner(writer); int writerId = getWriterId(writer); Set<PublicKeyHash> owned = new HashSet<>(); try (Connection conn = getConnection(); PreparedStatement ownedSearch = conn.prepareStatement("SELECT owned_id FROM ownedkeys WHERE parent_id = ?;"); PreparedStatement usageSearch = conn.prepareStatement("SELECT target, direct_size FROM writerusage WHERE writer_id = ?;"); PreparedStatement search = conn.prepareStatement("SELECT key_hash FROM writers WHERE id = ?;")) { ownedSearch.setInt(1, writerId); ResultSet ownedRes = ownedSearch.executeQuery(); while (ownedRes.next()) { search.setInt(1, ownedRes.getInt(1)); ResultSet resultSet = search.executeQuery(); resultSet.next(); PublicKeyHash ownedKey = PublicKeyHash.decode(resultSet.getBytes(1)); owned.add(ownedKey); } usageSearch.setInt(1, writerId); ResultSet usageRes = usageSearch.executeQuery(); usageRes.next(); MaybeMultihash target = Optional.ofNullable(usageRes.getBytes(1)) .map(x -> MaybeMultihash.of(Cid.cast(x))) .orElse(MaybeMultihash.empty()); return new WriterUsage(owner, target, usageRes.getLong(2), owned); } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } @Override public void updateWriterUsage(PublicKeyHash writer, MaybeMultihash target, Set<PublicKeyHash> removedOwnedKeys, Set<PublicKeyHash> addedOwnedKeys, long retainedStorage) { int writerId = getWriterId(writer); try (Connection conn = getConnection(true, false); PreparedStatement insert = conn.prepareStatement("UPDATE writerusage SET target=?, direct_size=? WHERE writer_id = ?;"); PreparedStatement writerSelect = conn.prepareStatement("SELECT id FROM writers WHERE key_hash = ?;"); PreparedStatement deleteOwned = conn.prepareStatement("DELETE FROM ownedkeys WHERE owned_id = ?;"); PreparedStatement insertOwned = conn.prepareStatement("INSERT INTO ownedkeys (parent_id, owned_id) VALUES(?, ?);")) { insert.setBytes(1, target.isPresent() ? target.get().toBytes() : null); insert.setLong(2, retainedStorage); insert.setInt(3, writerId); int count = insert.executeUpdate(); if (count != 1) throw new IllegalStateException("Didn't update one record!"); for (PublicKeyHash removed : removedOwnedKeys) { writerSelect.setBytes(1, removed.toBytes()); ResultSet writerRes = writerSelect.executeQuery(); writerRes.next(); int ownedId = writerRes.getInt(1); deleteOwned.setInt(1, ownedId); deleteOwned.executeUpdate(); } for (PublicKeyHash added : addedOwnedKeys) { writerSelect.setBytes(1, added.toBytes()); ResultSet writerRes = writerSelect.executeQuery(); writerRes.next(); int ownedId = writerRes.getInt(1); insertOwned.setInt(1, writerId); insertOwned.setInt(2, ownedId); insertOwned.execute(); } } catch (SQLException sqe) { LOG.log(Level.WARNING, sqe.getMessage(), sqe); throw new RuntimeException(sqe); } } public synchronized void close() { if (isClosed) return; isClosed = true; } }
package org.bimserver.servlets; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.bimserver.BimServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RootServlet extends HttpServlet { private static final long serialVersionUID = -6631574771887074019L; private static final Logger LOGGER = LoggerFactory.getLogger(RootServlet.class); private WebServiceServlet11 soap11Servlet; private WebServiceServlet12 soap12Servlet; private SyndicationServlet syndicationServlet; private JsonApiServlet jsonApiServlet; private UploadServlet uploadServlet; private DownloadServlet downloadServlet; private BimServer bimServer; @Override public void init() throws ServletException { super.init(); bimServer = (BimServer) getServletContext().getAttribute("bimserver"); jsonApiServlet = new JsonApiServlet(bimServer, getServletContext()); syndicationServlet = new SyndicationServlet(bimServer, getServletContext()); uploadServlet = new UploadServlet(bimServer, getServletContext()); downloadServlet = new DownloadServlet(bimServer, getServletContext()); soap11Servlet = new WebServiceServlet11(bimServer, getServletContext()); soap11Servlet.init(getServletConfig()); soap12Servlet = new WebServiceServlet12(bimServer, getServletContext()); soap12Servlet.init(getServletConfig()); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String requestUri = request.getRequestURI(); String servletContextPath = getServletContext().getContextPath(); if (requestUri.startsWith(servletContextPath)) { requestUri = requestUri.substring(servletContextPath.length()); } if (requestUri == null) { LOGGER.error("RequestURI is null"); } else { LOGGER.debug(requestUri); // LOGGER.info(requestUri); } setContentType(response, requestUri); if (request.getRequestURI().endsWith("getbimserveraddress")) { response.setContentType("application/json"); String siteAddress = bimServer.getServerSettingsCache().getServerSettings().getSiteAddress(); if (siteAddress == null || siteAddress.trim().isEmpty()) { // Only when in setup-mode siteAddress = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); } if (siteAddress.contains("http: siteAddress = siteAddress.replace("http://", request.getScheme() + "://"); } response.getWriter().print("{\"address\":\"" + siteAddress + "\"}"); return; } else if (requestUri.startsWith("/stream")) { LOGGER.warn("Stream request should not be going to this servlet!"); } else if (requestUri.startsWith("/openid")) { bimServer.getOpenIdManager().verifyResponse(request, response); } else if (requestUri.startsWith("/soap11/") || requestUri.equals("/soap11")) { soap11Servlet.service(request, response); } else if (requestUri.startsWith("/soap12/") || requestUri.equals("/soap12")) { soap12Servlet.service(request, response); } else if (requestUri.startsWith("/syndication/") || requestUri.equals("/syndication")) { syndicationServlet.service(request, response); } else if (requestUri.startsWith("/json/") || requestUri.equals("/json")) { jsonApiServlet.service(request, response); } else if (requestUri.startsWith("/upload/") || requestUri.equals("/upload")) { uploadServlet.service(request, response); } else if (requestUri.startsWith("/download/") || requestUri.equals("/download")) { downloadServlet.service(request, response); } else { if (requestUri.equals("") || requestUri.equals("/") || requestUri == null) { requestUri = "/index.html"; } if (bimServer.getDefaultWebModule() == null) { LOGGER.info("No default web module"); } String modulePath = requestUri; if (modulePath.indexOf("/", 1) != -1) { modulePath = modulePath.substring(0, modulePath.indexOf("/", 1)); } if (bimServer.getWebModules().containsKey(modulePath)) { String substring = requestUri.substring(modulePath.length()); if (bimServer.getWebModules().get(modulePath).service(substring, response)) { return; } } else { LOGGER.info("Sub path: " + modulePath + " NOT found"); } if (bimServer.getDefaultWebModule() != null) { if (bimServer.getDefaultWebModule().service(requestUri, response)) { return; } } LOGGER.info("Trying local resource: " + requestUri); InputStream resourceAsStream = getServletContext().getResourceAsStream(requestUri); if (resourceAsStream != null) { IOUtils.copy(resourceAsStream, response.getOutputStream()); } else { response.setStatus(404); try { response.getWriter().println("404 - Not Found"); } catch (IllegalStateException e) { } } } } catch (Throwable e) { if (e instanceof IOException) { // Ignore } else { LOGGER.error("", e); } } } private void setContentType(HttpServletResponse response, String requestUri) { if (requestUri.endsWith(".js")) { response.setContentType("application/javascript"); } else if (requestUri.endsWith(".css")) { response.setContentType("text/css"); } else if (requestUri.endsWith(".png")) { response.setContentType("image/png"); } else if (requestUri.endsWith(".gif")) { response.setContentType("image/gif"); } } }
package io.branch.referral; import io.branch.referral.ApkParser; import java.io.InputStream; import java.util.UUID; import java.util.jar.JarFile; import android.Manifest; import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings.Secure; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.WindowManager; public class SystemObserver { public static final String BLANK = "bnc_no_value"; private Context context_; public SystemObserver(Context context) { context_ = context; } public String getUniqueID() { if (context_ != null) { String androidID = Secure.getString(context_.getContentResolver(), Secure.ANDROID_ID); if (androidID == null) { androidID = UUID.randomUUID().toString();; } return androidID; } else return BLANK; } public String getURIScheme() { PackageManager pm = context_.getPackageManager(); try { ApplicationInfo ai = pm.getApplicationInfo(context_.getPackageName(), 0); String sourceApk = ai.publicSourceDir; Log.i("BranchUriSchemer", "source APK file " + sourceApk); try { JarFile jf = new JarFile(sourceApk); InputStream is = jf.getInputStream(jf.getEntry("AndroidManifest.xml")); byte[] xml = new byte[is.available()]; is.read(xml); String scheme = new ApkParser().decompressXML(xml); jf.close(); return scheme; } catch (Exception ex) { ex.printStackTrace(); } } catch (NameNotFoundException e) { e.printStackTrace(); } return BLANK; } public String getAppVersion() { try { PackageInfo packageInfo = context_.getPackageManager().getPackageInfo(context_.getPackageName(), 0); if (packageInfo.versionName != null) return packageInfo.versionName; else return BLANK; } catch (NameNotFoundException e) { e.printStackTrace(); } return BLANK; } public String getCarrier() { TelephonyManager telephonyManager = (TelephonyManager) context_.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { String ret = telephonyManager.getNetworkOperatorName(); if (ret != null) return ret; } return BLANK; } public boolean getBluetoothPresent() { try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { return bluetoothAdapter.isEnabled(); } } catch (SecurityException e) { e.printStackTrace(); } return false; } public String getBluetoothVersion() { if (android.os.Build.VERSION.SDK_INT >= 8) { if(android.os.Build.VERSION.SDK_INT >= 18 && context_.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { return "ble"; } else if(context_.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { return "classic"; } } return BLANK; } public boolean getNFCPresent() { try { return context_.getPackageManager().hasSystemFeature("android.hardware.nfc"); } catch (Exception e) { e.printStackTrace(); } return false; } public boolean getTelephonePresent() { try { return context_.getPackageManager().hasSystemFeature("android.hardware.telephony"); } catch (Exception e) { e.printStackTrace(); } return false; } public String getPhoneBrand() { return android.os.Build.MANUFACTURER; } public String getPhoneModel() { return android.os.Build.MODEL; } public String getOS() { return "Android"; } public int getOSVersion() { return android.os.Build.VERSION.SDK_INT; } @SuppressLint("NewApi") public int getUpdateState() { if (android.os.Build.VERSION.SDK_INT >= 9) { try { PackageInfo packageInfo = context_.getPackageManager().getPackageInfo(context_.getPackageName(), 0); if (packageInfo.lastUpdateTime != packageInfo.firstInstallTime) { return 1; } else { return 0; } } catch (NameNotFoundException e) { e.printStackTrace(); } } return 0; } public DisplayMetrics getScreenDisplay() { DisplayMetrics displayMetrics = new DisplayMetrics(); Display display = ((WindowManager) context_.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); display.getMetrics(displayMetrics); return displayMetrics; } public boolean getWifiConnected() { if (PackageManager.PERMISSION_GRANTED == context_.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)) { ConnectivityManager connManager = (ConnectivityManager) context_.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return wifiInfo.isConnected(); } return false; } }
// E v a l u a t o r s P a n e l // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.glyph.ui; import omr.glyph.Evaluation; import omr.glyph.Evaluator; import omr.glyph.Glyph; import omr.glyph.GlyphNetwork; import omr.glyph.GlyphRegression; import omr.glyph.Shape; import omr.sheet.Sheet; import omr.sheet.SystemInfo; import omr.ui.Panel; import omr.util.Logger; import com.jgoodies.forms.builder.*; import com.jgoodies.forms.layout.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * Class <code>EvaluatorsPanel</code> is dedicated to the display of * evaluation results performed by a pool of evaluators * * @author Herv&eacute Bitteur * @version $Id$ */ public class EvaluatorsPanel extends Panel { private static Logger logger = Logger.getLogger(EvaluatorsPanel.class); // Max number of buttons in the shape selector private static final int EVAL_NB = 3; private static final Color EVAL_GOOD_COLOR = new Color(100, 150, 0); private static final Color EVAL_SOSO_COLOR = new Color(255, 100, 150); // Related sheet & GlyphPane (if any) private final Sheet sheet; private final GlyphPane pane; // Lag view (if any) private SymbolGlyphView view; // Pool of evaluators private final GlyphNetwork network = GlyphNetwork.getInstance(); private final EvaluatorPanel networkPanel; private final GlyphRegression regression = GlyphRegression.getInstance(); private final EvaluatorPanel regressionPanel; // EvaluatorsPanel // /** * Create a panel with two evaluators (one neural network and one based * on regression) * * @param sheet the related sheet, or null * @param pane the glyph pane, or null if this panel is just an output */ public EvaluatorsPanel (Sheet sheet, GlyphPane pane) { this.sheet = sheet; this.pane = pane; if (pane != null) { setNoInsets(); } networkPanel = new EvaluatorPanel(network); regressionPanel = new EvaluatorPanel(regression); FormLayout layout = new FormLayout ("pref", "pref," + Panel.getPanelInterline() + "," + "pref"); PanelBuilder builder = new PanelBuilder(layout, this); builder.setDefaultDialogBorder(); CellConstraints cst = new CellConstraints(); int r = 1; builder.add(networkPanel, cst.xy (1, r)); r += 2; builder.add(regressionPanel, cst.xy (1, r)); } // setView // /** * Connect the glyph view. This could not be done from the constructor * * @param view the glyph lag view */ void setView (SymbolGlyphView view) { this.view = view; } // evaluate // /** * Evaluate the glyph at hand, and display the result from each * evaluator in its dedicated area * * @param glyph the glyph at hand */ public void evaluate (Glyph glyph) { if (glyph == null || glyph.getShape() == Shape.COMBINING_STEM) { // Blank the output networkPanel.selector.setEvals(null); regressionPanel.selector.setEvals(null); } else { networkPanel.selector.setEvals(network.getEvaluations(glyph)); regressionPanel.selector.setEvals(regression.getEvaluations(glyph)); } } // guessSheet // /** * Use the network evaluator to guess all non-assigned glyphs in the * sheet */ public void guessSheet () { network.guessSheet(sheet); } // EvaluatorPanel // /** * Class <code>EvaluatorPanel</code> is dedicated to one evaluator */ private class EvaluatorPanel extends Panel { // The evaluator this display is related to private final Evaluator evaluator; private final JButton testButton = new JButton(new TestAction()); // Pane for detailed info display about the glyph evaluation private final Selector selector = new Selector(); // Numeric result of whole sheet test private final JLabel testPercent = new JLabel("0%", SwingConstants.CENTER); private final JLabel testResult = new JLabel("", SwingConstants.CENTER); /** * Create a dedicated evaluator panel * * @param evaluator the related evaluator */ // EvaluatorPanel // public EvaluatorPanel (Evaluator evaluator) { this.evaluator = evaluator; setNoInsets(); defineLayout(); } // defineLayout // private void defineLayout() { final String buttonWidth = Panel.getButtonWidth(); final String fieldInterval = Panel.getFieldInterval(); final String fieldInterline = Panel.getFieldInterline(); FormLayout layout = new FormLayout (buttonWidth + "," + fieldInterval + "," + buttonWidth + "," + fieldInterval + "," + buttonWidth + "," + fieldInterval + "," + buttonWidth, "pref," + fieldInterline + "," + "pref," + "pref," + "pref"); // Uncomment following line to have fixed sized rows, whether // they are filled or not //layout.setRowGroups(new int[][]{{1, 3, 4, 5 }}); PanelBuilder builder = new PanelBuilder(layout, this); builder.setDefaultDialogBorder(); CellConstraints cst = new CellConstraints(); int r = 1; if (sheet != null) { builder.addSeparator(evaluator.getName(), cst.xyw(1, r, 1)); builder.add(testButton, cst.xy (3, r)); builder.add(testPercent, cst.xy (5, r)); builder.add(testResult, cst.xy (7, r)); } else { builder.addSeparator(evaluator.getName(), cst.xyw(1, r, 7)); } for (int i = 0 ; i < EVAL_NB; i++) { r = i + 3; builder.add(selector.buttons[i].grade, cst.xy (1, r)); if (pane != null) { builder.add(selector.buttons[i].button, cst.xyw(3, r, 5)); } else { builder.add(selector.buttons[i].field, cst.xyw(3, r, 5)); } } } // Selector // private class Selector { // A collection of EvalButton's EvalButton[] buttons; public Selector() { buttons = new EvalButton[EVAL_NB]; for (int i = 0; i < buttons.length; i++) { buttons[i] = new EvalButton(); } setEvals(null); } // setEvals // /** * Display the evaluations with some text highlighting. Only * relevant evaluations are displayed (distance less than an * evaluator-dependent threshold, and less than x times (also * evaluator-dependent) the best (first) eval whichever comes * first) * * @param evals the ordered list of evaluations from best to * worst */ public void setEvals (Evaluation[] evals) { // Special case to empty the selector if (evals == null) { for (EvalButton evalButton : buttons) { evalButton.setEval(null); } return; } double maxDist = evaluator.getMaxDistance(); double maxRatio = evaluator.getMaxDistanceRatio(); double best = -1; // i.e. Not set int iBound = Math.min(EVAL_NB, evals.length); int i; for (i = 0; i < iBound; i++) { Evaluation eval = evals[i]; if (eval.grade > maxDist) { break; } if (best < 0) { best = eval.grade; } if (eval.grade > best * maxRatio) { break; } buttons[i].setEval(eval); } // Zero the remaining buttons for (; i < EVAL_NB; i++) { buttons[i].setEval(null); } } } // EvalButton // private class EvalButton implements ActionListener { // A shape button or text field. Only one of them will be // allocated and used JTextField field; JButton button; // The related grade JLabel grade = new JLabel("", SwingConstants.RIGHT); public EvalButton() { grade.setToolTipText("Grade of the evaluation"); if (pane != null) { button = new JButton(); button.addActionListener(this); button.setToolTipText("Assignable shape"); } else { field = new JTextField(); field.setHorizontalAlignment(JTextField.CENTER); field.setEditable(false); field.setToolTipText("Evaluated shape"); } } public void setEval (Evaluation eval) { JComponent comp; if (pane != null) { comp = button; } else { comp = field; } if (eval != null) { if (pane != null) { button.setText(eval.shape.toString()); } else { field.setText(eval.shape.toString()); } comp.setVisible(true); if (eval.grade <= evaluator.getAcceptanceGrade()) { comp.setForeground(EVAL_GOOD_COLOR); } else { comp.setForeground(EVAL_SOSO_COLOR); } grade.setVisible(true); grade.setText(String.format("%.3f", eval.grade)); } else { grade.setVisible(false); comp.setVisible(false); } } // Triggered by button public void actionPerformed(ActionEvent e) { // Assign current glyph with selected shape if (pane != null) { pane.assignShape(Shape.valueOf(button.getText()), /* asGuessed => */ false, /* compound => */ false); } } } // TestAction // /** * Class <code>TestAction</code> uses the evaluator on all known * glyphs within the sheet, to check if they can be correctly * recognized. This does not modify the current glyph assignments. */ private class TestAction extends AbstractAction { public TestAction () { super("Global"); } public void actionPerformed (ActionEvent e) { int ok = 0; int total = 0; for (SystemInfo system : sheet.getSystems()) { for (Glyph glyph : system.getGlyphs()) { if (glyph.isKnown() && glyph.getShape() != Shape.COMBINING_STEM) { total++; Shape guess = evaluator.vote(glyph); if (glyph.getShape() == guess) { ok++; view.colorizeGlyph (glyph, Shape.okColor); } else { view.colorizeGlyph (glyph, Shape.missedColor); } } } } String pc = String.format(" %5.2f%%", (double) ok * 100 / (double) total); testPercent.setText(pc); testResult.setText(ok + "/" + total); // Almost all glyphs may have been modified, so... view.repaint(); } } } }
// G l y p h R e p o s i t o r y // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.glyph.ui; import omr.Main; import omr.glyph.Glyph; import omr.glyph.Shape; import omr.sheet.Sheet; import omr.sheet.SystemInfo; import omr.util.FileUtil; import omr.util.Logger; import omr.util.XmlMapper; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Collection; import java.io.IOException; import omr.glyph.ui.GlyphRepository.Monitor; /** * Class <code>GlyphRepository</code> handles the store of known glyphs, * across multiple sheets (and possibly multiple runs). * * <p> A glyph is known by its full name, whose format is * <B>sheetName/Shape.id.xml</B>, regardless of the area it is stored (this * may be the <I>core</I> area or the global <I>sheets</I> area) * * <p> The repository handles a private map of all deserialized glyphs so * far, since the deserialization is a rather expensive operation. * * <p> It handles two bases : the "whole base" (all glyphs) and the "core * base" (just the glyphs of the core) which are accessible respectively by * {@link #getWholeBase} and {@link #getCoreBase} methods. * * @author Herv&eacute; Bitteur * @version $Id$ */ public class GlyphRepository { private static final Logger logger = Logger.getLogger(GlyphRepository.class); // Specific glyph XML mapper private static XmlMapper xmlMapper; // The single instance of this class private static GlyphRepository INSTANCE; // Extension for training files private static final String FILE_EXTENSION = ".xml"; // Name of Structures sub-directory private static final String STRUCTURES_NAME = ".structures"; // Specific subdirectories for training files private static final File sheetsFolder = new File(Main.getTrainFolder(), "sheets"); private static final File coreFolder = new File(Main.getTrainFolder(), "core"); // Map of all glyphs deserialized so far, using full glyph name as key // Full glyph name format is : sheetName/Shape.id.xml private Map<String,Glyph> glyphsMap = new TreeMap<String,Glyph>(); // Whole collection of glyphs private Collection<String> wholeBase; // Core collection of glyphs private Collection<String> coreBase; // Private (singleton) private GlyphRepository() { } // getInstance // /** * Report the single instance of this class, after creating it if * needed * * @return the single instance */ public static GlyphRepository getInstance () { if (INSTANCE == null) { INSTANCE = new GlyphRepository(); } return INSTANCE; } // getXmlMapper // private XmlMapper getXmlMapper() { if (xmlMapper == null) { xmlMapper = new XmlMapper(Glyph.class); } return xmlMapper; } // getCoreBase // /** * Return the names of the core collection of glyphs * * @return the core collection of recorded glyphs */ synchronized Collection<String> getCoreBase (Monitor monitor) { if (coreBase == null) { coreBase = loadCoreBase(monitor); } return coreBase; } // getCoreFolder // /** * Report the folder where selected core glyphs are stored * * @return the directory of core material */ static File getCoreFolder() { return coreFolder; } // getGlyph // /** * Return a glyph knowing its full glyph name, which is the name of the * corresponding training material. If not already done, the glyph is * deserialized from the training file, searching first in the core * area, then in the global sheets area. * * @param gName the full glyph name (format is: sheetName/Shape.id.xml) * * @return the glyph instance if found, null otherwise */ Glyph getGlyph (String gName) { // First, try the map of glyphs Glyph glyph = glyphsMap.get(gName); // If failed, actually load the glyph from XML backup file if (glyph == null) { // We try to load from the core repository first, then from the // sheets repository File file; file = new File(getCoreFolder(), gName); if (!file.exists()) { file = new File(getSheetsFolder(), gName); if (!file.exists()) { logger.warning("Unable to find file for glyph " + gName); return null; } } if (logger.isFineEnabled()) { logger.fine("Reading " + file); } try { glyph = (Glyph) getXmlMapper().load(file); glyphsMap.put(gName, glyph); } catch (Exception ex) { // User already informed } } return glyph; } // getSheetDirectories // /** * Report the list of all sheet directories found in the training * material * * @return the list of sheet directories */ synchronized List<File> getSheetDirectories() { // One directory per sheet List<File> dirs = new ArrayList<File>(); File[] files = getSheetsFolder().listFiles(); for (File file : files) { if (file.isDirectory()) { dirs.add(file); } } return dirs; } // getSheetGlyphs // /** * Report the list of glyph files that are contained within a given * directory * * @param dir the containing directory * @return the list of glyph files */ synchronized List<File> getSheetGlyphs (File dir) { List<File> glyphFiles = new ArrayList<File>(); File[] files = dir.listFiles(); for (File file : files) { if (FileUtil.getExtension(file).equals(FILE_EXTENSION)) { logger.fine("Adding " + file); glyphFiles.add(file); } } return glyphFiles; } // getSheetsFolder // /** * Report the folder where all sheet glyphs are stored * * @return the directory of all sheets material */ static File getSheetsFolder() { return sheetsFolder; } // getWholeBase // /** * Return the names of the whole collection of glyphs * * @return the whole collection of recorded glyphs */ synchronized Collection<String> getWholeBase (Monitor monitor) { if (wholeBase == null) { wholeBase = loadWholeBase(monitor); } return wholeBase; } // recordSheetGlyphs // /** * Store all known glyphs of the provided sheet as separate XML files, * so that they can be later re-loaded to train an evaluator. We store * glyph for which Shape is not null, and different from NOISE and STEM * (CLUTTER is thus stored as well). * * <p>STRUCTURE shapes are stored in a parallel sub-directory so that * they don't get erased by shpes of their leaves. * * @param sheet the sheet whose glyphs are to be stored * @param emptyStructures flag to specify if the Structure directory * must be emptied beforehand */ void recordSheetGlyphs (Sheet sheet, boolean emptyStructures) { try { // Prepare target directory File sheetDir = new File(getSheetsFolder(), sheet.getRadix()); if (!sheetDir.exists()) { // Make sure related directory chain exists logger.info("Creating directory " + sheetDir); sheetDir.mkdirs(); } else { deleteXmlFiles(sheetDir); } // Prepare structures directory File structuresDir = new File(getSheetsFolder(), sheet.getRadix() + STRUCTURES_NAME); if (!structuresDir.exists()) { // Make sure related structure subdirectory exists logger.info("Creating subdirectory " + structuresDir); structuresDir.mkdirs(); } else if (emptyStructures) { deleteXmlFiles(structuresDir); } // Now record each relevant glyph int glyphNb = 0; int structuresNb = 0; for (SystemInfo system : sheet.getSystems()) { for (Glyph glyph : system.getGlyphs()) { Shape shape = glyph.getShape(); if (shape != null && shape != Shape.NOISE && shape != Shape.COMBINING_STEM) { if (logger.isFineEnabled()) { logger.fine("Storing " + glyph); } int y = glyph.getMembers().get(0).getStart(); glyph.setInterline (sheet.getScale().interline()); // Build the proper glyph file StringBuffer sb = new StringBuffer(); sb.append(shape); sb.append("."); sb.append(String.format("%04d", glyph.getId())); sb.append(FILE_EXTENSION); File glyphFile; if (shape != Shape.STRUCTURE) { glyphFile = new File(sheetDir, sb.toString()); } else { structuresNb++; glyphFile = new File(structuresDir, sb.toString()); } // Store the glyph getXmlMapper().store(glyph, glyphFile); glyphNb++; } } } logger.info(glyphNb + " glyphs stored from " + sheet.getRadix() + (structuresNb == 0 ? "" : " (including " + structuresNb + " structures)")); } catch (Exception ex) { ex.printStackTrace(); } } // removeGlyph // /** * Remove a glyph from the repository memory (this does not delete the * actual glyph file on disk). We also remove it from the various bases * which is safer * * @param gName the full glyph name */ synchronized void removeGlyph (String gName) { glyphsMap.remove(gName); if (wholeBase != null) { wholeBase.remove(gName); } if (coreBase != null) { coreBase.remove(gName); } } // setCoreBase // /** * Define the provided collection as the core training material * @param base the provided collection */ synchronized void setCoreBase (Collection<String> base) { coreBase = base; } // shapeOf // /** * Infer the shape of a glyph directly from its full name * * @param gName the full glyph name * @return the shape of the known glyph */ Shape shapeOf (String gName) { return shapeOf(new File(gName)); } // storeCoreBase // /** * Store the core training material */ synchronized void storeCoreBase () { if (coreBase == null) { logger.warning("Core base is null"); return; } // Create the core directory if needed File coreDir = getCoreFolder(); coreDir.mkdirs(); // Empty the directory FileUtil.deleteAll(coreDir.listFiles()); // Copy the glyph files into the core directory for (String gName : coreBase) { File source = new File(getSheetsFolder(), gName); File targetDir = new File(coreDir, source.getParentFile().getName()); targetDir.mkdirs(); File target = new File(targetDir, source.getName()); if (logger.isFineEnabled()) { logger.fine("Storing " + gName + " as core"); } try { FileUtil.copy(source, target); } catch (IOException ex) { logger.warning("Cannot copy " + source + " to " + target); } } logger.info(coreBase.size() + " glyphs copied as core training material"); } // deleteXmlFiles // private void deleteXmlFiles (File dir) { File[] files = dir.listFiles(); for (File file : files) { if (FileUtil.getExtension(file).equals(FILE_EXTENSION)) { file.delete(); } } } // glyphNameOf // /** * Build the full glyph name (which will be the unique glyph name) from * the file which contains the glyph description * * @param file the glyph backup file * @return the unique glyph name */ private static String glyphNameOf (File file) { return file.getParentFile().getName() + File.separator + file.getName(); } // loadBase // /** * Build the map and return the collection of glyphs names in a given * directory * * @param path the path of the directory to load * @param monitor the observing entity if any * @return the collection of loaded glyphs names */ private synchronized Collection<String> loadBase (File path, Monitor monitor) { // Files in the provided directory & its subdirectories List<File> files = new ArrayList<File>(1000); loadDirectory(path, files); if (monitor != null) { monitor.setTotalGlyphs(files.size()); } // Now, actually load the related glyphs if needed Collection<String> base = new ArrayList<String>(1000); for (File file : files) { String gName = glyphNameOf(file); base.add(gName); Glyph glyph = getGlyph(gName); if (monitor != null) { monitor.loadedGlyph(glyph); } } return base; } // loadDirectory // private void loadDirectory (File dir, List<File> all) { logger.fine("Recursing through " + dir); File[] files = dir.listFiles(); if (files == null) { logger.warning("Directory " + dir + " not found"); return; } for (File file : files) { if (file.isDirectory()) { // Recurse through it loadDirectory(file, all); } else { if (FileUtil.getExtension(file).equals(FILE_EXTENSION)) { logger.fine("Adding " + file); all.add(file); } } } } // loadCoreBase // /** * Build the collection of only the core glyphs * * @return the collection of core glyphs names */ private Collection<String> loadCoreBase (Monitor monitor) { return loadBase(getCoreFolder(), monitor); } // loadWholeBase // /** * Build the complete map of all glyphs recorded so far * * @return a collection of (known) glyphs names */ private Collection<String> loadWholeBase (Monitor monitor) { return loadBase(getSheetsFolder(), monitor); } // shapeOf // /** * Infer the shape of a glyph directly from its file name * * @param file the file that describes the glyph * @return the shape of the known glyph */ private Shape shapeOf (File file) { try { // ex: THIRTY_SECOND_REST.0105.xml String name = FileUtil.getNameSansExtension(file); int dot = name.indexOf("."); if (dot != -1) { name = name.substring(0, dot); } return Shape.valueOf(name); } catch (Exception ex) { // Not recognized return null; } } // Monitor // /** * Interface <code>Monitor</code> defines the entries to a UI entity * which monitors the loading of glyphs by the glyph repository */ static interface Monitor { /** * Called whenever a new glyph has been loaded * * @param glyph the glyph just loaded */ void loadedGlyph (Glyph glyph); /** * Called to pass the number of selected glyphs, which will be * later loaded * * @param selected the size of the selection */ void setSelectedGlyphs (int selected); /** * Called to pass the total number of available glyph descriptions * in the training material * * @param total the size of the training material */ void setTotalGlyphs (int total); } }
package edu.teco.dnd.graphiti; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.graphiti.features.IFeatureProvider; import org.eclipse.graphiti.features.context.IAddContext; import org.eclipse.graphiti.features.impl.AbstractAddShapeFeature; import org.eclipse.graphiti.mm.algorithms.Ellipse; import org.eclipse.graphiti.mm.algorithms.Polyline; import org.eclipse.graphiti.mm.algorithms.RoundedRectangle; import org.eclipse.graphiti.mm.algorithms.Text; import org.eclipse.graphiti.mm.algorithms.styles.Orientation; import org.eclipse.graphiti.mm.pictograms.ContainerShape; import org.eclipse.graphiti.mm.pictograms.Diagram; import org.eclipse.graphiti.mm.pictograms.FixPointAnchor; import org.eclipse.graphiti.mm.pictograms.PictogramElement; import org.eclipse.graphiti.mm.pictograms.Shape; import org.eclipse.graphiti.services.Graphiti; import org.eclipse.graphiti.services.IGaService; import org.eclipse.graphiti.services.IPeCreateService; import org.eclipse.graphiti.util.ColorConstant; import org.eclipse.graphiti.util.IColorConstant; import edu.teco.dnd.graphiti.model.FunctionBlockModel; import edu.teco.dnd.graphiti.model.InputModel; import edu.teco.dnd.graphiti.model.OptionModel; import edu.teco.dnd.graphiti.model.OutputModel; /** * Adds a graphical representation for a FunctionBlock. */ public class DNDAddBlockFeature extends AbstractAddShapeFeature { /** * Logger for this class. */ private static final Logger LOGGER = LogManager.getLogger(DNDAddBlockFeature.class); /** * Key to distinguish between text fields. */ public static final String TEXT_KEY = "text-id"; //$NON-NLS-1$ /** * Default width of a new block. */ public static final int DEFAULT_WIDTH = 100; /** * Default height of a new block. */ public static final int DEFAULT_HEIGHT = 50; /** * Corner radius for the rounded rectangle. */ public static final int CORNER_RADIUS = 5; /** * Y position of the separator line. */ public static final int SEPARATOR_Y = 20; /** * Vertical offset for the block name. */ public static final int BLOCKNAME_OFFSET = 35; /** * Vertical size of the block name. */ public static final int BLOCKNAME_SIZE = 15; /** * Vertical offset for the position. */ public static final int POSITION_OFFSET = 65; /** * Vertical size of the position. */ public static final int POSITION_SIZE = 15; /** * Vertical offset for the first input/output. */ public static final int CONNECTION_OFFSET = 105; /** * Size of an input/output. */ public static final int CONNECTION_SIZE = 15; /** * Extra space to add between inputs/outputs. */ public static final int CONNECTION_SPACE = 7; /** * Extra space for in/outputs to the side of the block. */ public static final int CONNECTION_EXTRA = 2; /** * Extra space for in/outputs to the side of the block. */ public static final int OPTION_EXTRA = 7; /** * Used to mark texts that show the name of an in- or output. */ public static final String CONNECTION_KEY = "connection"; //$NON-NLS-1$ /** * Used to mark texts that show the name of an in- or output. */ public static final String CONNECTION_VALUE = CONNECTION_KEY; /** * Color of the foreground. */ public static final IColorConstant FOREGROUND = IColorConstant.BLACK; /** * Color of the BackgroundSensor. */ public static final IColorConstant BACKGROUND_SENSOR = new ColorConstant("238BC2"); //$NON-NLS-1$ /** * Color of the BackgroundActor. */ public static final IColorConstant BACKGROUND_ACTOR = new ColorConstant("BC80FF"); //$NON-NLS-1$ /** * Color of the other background. */ public static final IColorConstant BACKGROUND_OTHER = new ColorConstant("AAAAAA"); //$NON-NLS-1$ /** * Color of the text. */ public static final IColorConstant TEXT = IColorConstant.BLACK; /** * Size of the font. */ public static final Integer FONT_SIZE = 8; /** * Color of the inputs. */ public static final IColorConstant INPUT = new ColorConstant("FFFF00"); //$NON-NLS-1$ /** * Color of the outputs. */ public static final IColorConstant OUTPUT = new ColorConstant("41DB00"); //$NON-NLS-1$ /** * Passes the feature provider to the super constructor. * * @param fp * the feature provider */ public DNDAddBlockFeature(final IFeatureProvider fp) { super(fp); } /** * Whether or not the feature can be used in the given context. * * @param context * the context * @return whether or not the feature can be used */ @Override public final boolean canAdd(final IAddContext context) { LOGGER.entry(context); boolean ret = context.getNewObject() instanceof FunctionBlockModel && context.getTargetContainer() instanceof Diagram; LOGGER.exit(ret); return ret; } /** * Returns a graphical representation for the given add context. * * @param context * the context * @return a graphical representation */ @Override public final PictogramElement add(final IAddContext context) { LOGGER.entry(context); FunctionBlockModel addedBlock = (FunctionBlockModel) context.getNewObject(); Diagram targetDiagram = (Diagram) context.getTargetContainer(); LOGGER.debug("Adding {} to {}", addedBlock, targetDiagram); //$NON-NLS-1$ IPeCreateService peCreateService = Graphiti.getPeCreateService(); ContainerShape containerShape = peCreateService.createContainerShape(targetDiagram, true); IGaService gaService = Graphiti.getGaService(); RoundedRectangle roundedRectangle; { LOGGER.debug("creating outer rectangle"); //$NON-NLS-1$ roundedRectangle = gaService.createRoundedRectangle(containerShape, CORNER_RADIUS, CORNER_RADIUS); if (addedBlock.isSensor()) { roundedRectangle.setBackground(manageColor(BACKGROUND_SENSOR)); } else if (addedBlock.isActor()) { roundedRectangle.setBackground(manageColor(BACKGROUND_ACTOR)); } else { roundedRectangle.setBackground(manageColor(BACKGROUND_OTHER)); } roundedRectangle.setForeground(manageColor(FOREGROUND)); roundedRectangle.setLineWidth(2); gaService.setLocationAndSize(roundedRectangle, context.getX(), context.getY(), DEFAULT_WIDTH, DEFAULT_HEIGHT); if (addedBlock.eResource() == null) { getDiagram().eResource().getContents().add(addedBlock); } TypePropertyUtil.setBlockShape(roundedRectangle); link(containerShape, addedBlock); } { LOGGER.debug("adding separator"); //$NON-NLS-1$ Shape shape = peCreateService.createShape(containerShape, false); Polyline polyline = gaService.createPolyline(shape, new int[] { 0, SEPARATOR_Y, DEFAULT_WIDTH, SEPARATOR_Y }); polyline.setForeground(manageColor(FOREGROUND)); polyline.setLineWidth(2); } { LOGGER.debug("adding name"); //$NON-NLS-1$ Shape shape = peCreateService.createShape(containerShape, false); Text text = gaService.createText(shape, addedBlock.getTypeName()); text.setForeground(manageColor(TEXT)); text.setHorizontalAlignment(Orientation.ALIGNMENT_CENTER); text.setFont(gaService .manageFont(getDiagram(), Messages.Graphiti_addBlock_FONTNAME, FONT_SIZE, false, true)); gaService.setLocationAndSize(text, 0, 0, DEFAULT_WIDTH, SEPARATOR_Y); link(shape, addedBlock); } { LOGGER.debug("adding blockName field"); //$NON-NLS-1$ Shape nameShape = peCreateService.createShape(containerShape, false); Text nameText = gaService.createText(nameShape, Messages.Graphiti_addBlock_NAME); nameText.setForeground(manageColor(TEXT)); nameText.setHorizontalAlignment(Orientation.ALIGNMENT_LEFT); gaService.setLocationAndSize(nameText, OPTION_EXTRA, BLOCKNAME_OFFSET - BLOCKNAME_SIZE / 2, DEFAULT_WIDTH / 2 - 2 * OPTION_EXTRA, BLOCKNAME_SIZE); Shape valueShape = peCreateService.createShape(containerShape, false); String blockName = addedBlock.getBlockName(); if (blockName == null) { blockName = Messages.Graphiti_EMPTYSTRING; } Text valueText = gaService.createText(valueShape, blockName); valueText.setForeground(manageColor(TEXT)); valueText.setHorizontalAlignment(Orientation.ALIGNMENT_RIGHT); gaService.setLocationAndSize(valueText, DEFAULT_WIDTH / 2 + OPTION_EXTRA, BLOCKNAME_OFFSET - BLOCKNAME_SIZE / 2, DEFAULT_WIDTH / 2 - 2 * OPTION_EXTRA, BLOCKNAME_SIZE); TypePropertyUtil.setBlockNameText(valueText); link(valueShape, addedBlock); } { LOGGER.debug("adding position"); //$NON-NLS-1$ Shape nameShape = peCreateService.createShape(containerShape, false); Text nameText = gaService.createText(nameShape, Messages.Graphiti_addBlock_POSITION); nameText.setForeground(manageColor(TEXT)); nameText.setHorizontalAlignment(Orientation.ALIGNMENT_LEFT); gaService.setLocationAndSize(nameText, OPTION_EXTRA, POSITION_OFFSET - POSITION_SIZE / 2, DEFAULT_WIDTH / 2 - 2 * OPTION_EXTRA, POSITION_SIZE); Shape valueShape = peCreateService.createShape(containerShape, false); String position = addedBlock.getPosition(); if (position == null) { position = Messages.Graphiti_EMPTYSTRING; //$NON-NLS-1$ } Text valueText = gaService.createText(valueShape, position); valueText.setForeground(manageColor(TEXT)); valueText.setHorizontalAlignment(Orientation.ALIGNMENT_RIGHT); gaService.setLocationAndSize(valueText, DEFAULT_WIDTH / 2 + OPTION_EXTRA, POSITION_OFFSET - POSITION_SIZE / 2, DEFAULT_WIDTH / 2 - 2 * OPTION_EXTRA, POSITION_SIZE); TypePropertyUtil.setPositionText(valueText); link(valueShape, addedBlock); } createConnectionsAndOptions(addedBlock, containerShape, peCreateService, gaService); LOGGER.debug("calling layout on {}", containerShape); //$NON-NLS-1$ layoutPictogramElement(containerShape); LOGGER.exit(containerShape); return containerShape; } /** * Creates graphical representations for Inputs, Outputs and Options. * * @param addedBlock * the block that was added * @param peCreateService * create service for PictogramElements * @param containerShape * the container shape for the block * @param gaService * the GraphicsAlgorithmService */ private void createConnectionsAndOptions(final FunctionBlockModel addedBlock, final ContainerShape containerShape, final IPeCreateService peCreateService, final IGaService gaService) { { LOGGER.debug("adding inputs"); //$NON-NLS-1$ int pos = CONNECTION_OFFSET; for (Object inputObject : addedBlock.getInputs()) { final InputModel input = (InputModel) inputObject; LOGGER.trace("adding {} at {}", input, pos); //$NON-NLS-1$ FixPointAnchor anchor = peCreateService.createFixPointAnchor(containerShape); anchor.setLocation(gaService.createPoint(CONNECTION_SIZE / 2 + CONNECTION_EXTRA, pos - CONNECTION_SIZE / 2)); Ellipse ellipse = gaService.createEllipse(anchor); ellipse.setForeground(manageColor(FOREGROUND)); ellipse.setBackground(manageColor(INPUT)); ellipse.setLineWidth(2); gaService.setLocationAndSize(ellipse, -CONNECTION_SIZE / 2 + CONNECTION_EXTRA, -CONNECTION_SIZE / 2, CONNECTION_SIZE, CONNECTION_SIZE); Shape labelShape = peCreateService.createShape(containerShape, false); Text label = gaService.createText(labelShape, input.getName()); label.setForeground(manageColor(TEXT)); label.setHorizontalAlignment(Orientation.ALIGNMENT_LEFT); gaService.setLocationAndSize(label, CONNECTION_SIZE + 2 * CONNECTION_EXTRA, pos - CONNECTION_SIZE, DEFAULT_WIDTH / 2 - CONNECTION_SIZE - CONNECTION_EXTRA * 3, CONNECTION_SIZE); Graphiti.getPeService().setPropertyValue(label, CONNECTION_KEY, CONNECTION_VALUE); pos += CONNECTION_SIZE + CONNECTION_SPACE; link(anchor, input); } } { LOGGER.debug("adding outputs"); //$NON-NLS-1$ int pos = CONNECTION_OFFSET; for (Object outputObject : addedBlock.getOutputs()) { final OutputModel output = (OutputModel) outputObject; LOGGER.trace("adding {} at {}", output, pos); //$NON-NLS-1$ FixPointAnchor anchor = peCreateService.createFixPointAnchor(containerShape); anchor.setLocation(gaService.createPoint(DEFAULT_WIDTH - CONNECTION_SIZE / 2 - CONNECTION_EXTRA, pos - CONNECTION_SIZE / 2)); Ellipse ellipse = gaService.createEllipse(anchor); ellipse.setForeground(manageColor(FOREGROUND)); ellipse.setBackground(manageColor(OUTPUT)); ellipse.setLineWidth(2); gaService.setLocationAndSize(ellipse, -CONNECTION_SIZE / 2 - CONNECTION_EXTRA, -CONNECTION_SIZE / 2, CONNECTION_SIZE, CONNECTION_SIZE); Shape labelShape = peCreateService.createShape(containerShape, false); Text label = gaService.createText(labelShape, output.getName()); label.setForeground(manageColor(TEXT)); label.setHorizontalAlignment(Orientation.ALIGNMENT_RIGHT); gaService.setLocationAndSize(label, DEFAULT_WIDTH / 2 + CONNECTION_SIZE + 2 * CONNECTION_EXTRA, pos - CONNECTION_SIZE, DEFAULT_WIDTH / 2 - CONNECTION_SIZE - CONNECTION_EXTRA * 5, CONNECTION_SIZE); Graphiti.getPeService().setPropertyValue(label, CONNECTION_KEY, CONNECTION_VALUE); LOGGER.trace("{}", Graphiti.getPeService().getProperty(label, CONNECTION_KEY)); //$NON-NLS-1$ pos += CONNECTION_SIZE + CONNECTION_SPACE; link(anchor, output); } } { LOGGER.debug("adding options"); //$NON-NLS-1$ int pos = DNDAddBlockFeature.CONNECTION_OFFSET + Math.max(addedBlock.getInputs().size(), addedBlock.getOutputs().size()) * (DNDAddBlockFeature.CONNECTION_SIZE + DNDAddBlockFeature.CONNECTION_SPACE); for (Object optionObject : addedBlock.getOptions()) { final OptionModel option = (OptionModel) optionObject; LOGGER.trace("adding {} at {}", option, pos); //$NON-NLS-1$ Shape nameShape = peCreateService.createShape(containerShape, false); Text nameText = gaService.createText(nameShape, option.getName() + ":"); //$NON-NLS-1$ nameText.setForeground(manageColor(TEXT)); nameText.setHorizontalAlignment(Orientation.ALIGNMENT_LEFT); gaService.setLocationAndSize(nameText, OPTION_EXTRA, pos - CONNECTION_SIZE / 2, DEFAULT_WIDTH / 2 - 2 * OPTION_EXTRA, CONNECTION_SIZE); Shape valueShape = peCreateService.createShape(containerShape, false); Text valueText = gaService.createText(valueShape, Messages.Graphiti_EMPTYSTRING + option.getValue()); //$NON-NLS-1$ valueText.setForeground(manageColor(TEXT)); valueText.setHorizontalAlignment(Orientation.ALIGNMENT_RIGHT); gaService.setLocationAndSize(valueText, DEFAULT_WIDTH / 2 + OPTION_EXTRA, pos - CONNECTION_SIZE / 2, DEFAULT_WIDTH / 2 - 2 * OPTION_EXTRA, CONNECTION_SIZE); pos += CONNECTION_SIZE + CONNECTION_SPACE; link(valueShape, option); } } } }
package org.jgroups.tests.perf; import org.jgroups.util.Util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.BufferedReader; import java.io.FileReader; import java.util.*; /** You start the test by running this class. * Use parameters -Xbatch -Xconcurrentio (Solaris specific) * @author Bela Ban (belaban@yahoo.com) */ public class Test implements Receiver { String props=null; Properties config; boolean sender=false; Transport transport=null; Object local_addr=null; /** HashMap<Object,MemberInfo> members. Keys=member addresses, value=MemberInfo */ HashMap senders=new HashMap(); /** Keeps track of members */ ArrayList members=new ArrayList(); /** Set when first message is received */ long start=0; /** Set when last message is received */ long stop=0; int num_members=0; Log log=LogFactory.getLog(getClass()); boolean all_received=false; /** HashMap<Object, HashMap>. A hashmap of senders, each value is the 'senders' hashmap */ HashMap results=new HashMap(); /** Dump info in gnuplot format */ boolean gnuplot_output=false; /** Log every n msgs received (if gnuplot_output == true) */ long log_interval=1000; /** Last time we dumped info */ long last_dump=0; long counter=1; long msg_size=1000; public void start(Properties c, boolean silent) throws Exception { String config_file="config.txt"; BufferedReader fileReader; String line; String key, val; StringTokenizer st; Properties tmp=new Properties(); config_file=c.getProperty("config"); fileReader=new BufferedReader(new FileReader(config_file)); while((line=fileReader.readLine()) != null) { if(line.startsWith(" continue; line=line.trim(); if(line.length() == 0) continue; st=new StringTokenizer(line, "=", false); key=st.nextToken().toLowerCase(); val=st.nextToken(); tmp.put(key, val); } fileReader.close(); // 'tmp' now contains all properties from the file, now we need to override the ones // passed to us by 'c' tmp.putAll(c); this.config=tmp; StringBuffer sb=new StringBuffer(); sb.append("\n\n sb.append("Date: ").append(new Date()).append('\n'); sb.append("Run by: ").append(System.getProperty("user.name")).append("\n\n"); sb.append("Properties: ").append(printProperties()).append("\n for(Iterator it=this.config.entrySet().iterator(); it.hasNext();) { Map.Entry entry=(Map.Entry)it.next(); sb.append(entry.getKey()).append(":\t").append(entry.getValue()).append('\n'); } sb.append('\n'); if(!silent) System.out.println("Configuration is: " + sb); log.info(sb.toString()); props=this.config.getProperty("props"); num_members=Integer.parseInt(this.config.getProperty("num_members")); sender=Boolean.valueOf(this.config.getProperty("sender")).booleanValue(); msg_size=Long.parseLong(this.config.getProperty("msg_size")); String tmp2=this.config.getProperty("gnuplot_output", "false"); if(Boolean.valueOf(tmp2).booleanValue()) this.gnuplot_output=true; tmp2=this.config.getProperty("log_interval"); if(tmp2 != null) log_interval=Long.parseLong(tmp2); if(gnuplot_output) { sb=new StringBuffer(); sb.append("\n sb.append(", free_mem [KB] "); sb.append(", total_mem [KB] "); sb.append(", total_msgs_sec [msgs/sec] "); sb.append(", total_throughput [KB/sec] "); sb.append(", rolling_msgs_sec (last ").append(log_interval).append(" msgs) "); sb.append(" [msgs/sec] "); sb.append(", rolling_throughput (last ").append(log_interval).append(" msgs) "); sb.append(" [KB/sec]\n"); if(log.isInfoEnabled()) log.info(sb.toString()); } String transport_name=this.config.getProperty("transport"); transport=(Transport)Thread.currentThread().getContextClassLoader().loadClass(transport_name).newInstance(); transport.create(this.config); transport.setReceiver(this); transport.start(); local_addr=transport.getLocalAddress(); } private String printProperties() { StringBuffer sb=new StringBuffer(); Properties p=System.getProperties(); for(Iterator it=p.entrySet().iterator(); it.hasNext();) { Map.Entry entry=(Map.Entry)it.next(); sb.append(entry.getKey()).append(": ").append(entry.getValue()).append('\n'); } return sb.toString(); } public void stop() { if(transport != null) { transport.stop(); transport.destroy(); } } public void receive(Object sender, byte[] payload) { Data d; try { d=(Data)Util.objectFromByteBuffer(payload); switch(d.getType()) { case Data.DISCOVERY_REQ: sendDiscoveryResponse(); break; case Data.DISCOVERY_RSP: synchronized(this.members) { if(!this.members.contains(sender)) { this.members.add(sender); System.out.println("-- " + sender + " joined"); if(d.sender) { synchronized(this.members) { if(!this.senders.containsKey(sender)) { this.senders.put(sender, new MemberInfo(d.num_msgs)); } } } this.members.notify(); } } break; case Data.DATA: if(all_received) return; if(start == 0) { start=System.currentTimeMillis(); last_dump=start; } MemberInfo info=(MemberInfo)this.senders.get(sender); if(info != null) { if(info.start == 0) info.start=System.currentTimeMillis(); info.num_msgs_received++; counter++; info.total_bytes_received+=d.payload.length; if(info.num_msgs_received % 1000 == 0) System.out.println("-- received " + info.num_msgs_received + " messages from " + sender); if(counter % log_interval == 0) { if(log.isInfoEnabled()) log.info(dumpStats(counter)); } if(info.num_msgs_received >= info.num_msgs_expected) { info.done=true; if(info.stop == 0) info.stop=System.currentTimeMillis(); if(allReceived()) { all_received=true; if(stop == 0) stop=System.currentTimeMillis(); sendResults(); if(!this.sender) dumpSenders(); synchronized(this) { this.notify(); } } } } else { System.err.println("-- sender " + sender + " not found in senders hashmap"); } break; case Data.DONE: if(all_received) return; MemberInfo mi=(MemberInfo)this.senders.get(sender); if(mi != null) { mi.done=true; if(mi.stop == 0) mi.stop=System.currentTimeMillis(); if(allReceived()) { all_received=true; if(stop == 0) stop=System.currentTimeMillis(); sendResults(); if(!this.sender) dumpSenders(); synchronized(this) { this.notify(); } } } else { System.err.println("-- sender " + sender + " not found in senders hashmap"); } break; case Data.RESULTS: synchronized(results) { if(!results.containsKey(sender)) { results.put(sender, d.results); results.notify(); } } break; default: System.err.println("received invalid data type: " + payload[0]); break; } } catch(Exception e) { e.printStackTrace(); } } void sendResults() throws Exception { Data d=new Data(Data.RESULTS); byte[] buf; d.results=(HashMap)this.senders.clone(); buf=Util.objectToByteBuffer(d); transport.send(null, buf); } boolean allReceived() { MemberInfo mi; for(Iterator it=this.senders.values().iterator(); it.hasNext();) { mi=(MemberInfo)it.next(); if(mi.done == false) return false; } return true; } void sendMessages() throws Exception { long total_msgs=0; int msg_size=Integer.parseInt(config.getProperty("msg_size")); int num_msgs=Integer.parseInt(config.getProperty("num_msgs")); int log_interval=Integer.parseInt(config.getProperty("log_interval")); // boolean gnuplot_output=Boolean.getBoolean(config.getProperty("gnuplot_output", "false")); byte[] buf=new byte[msg_size]; for(int k=0; k < msg_size; k++) buf[k]='.'; Data d=new Data(Data.DATA); d.payload=buf; byte[] payload=Util.objectToByteBuffer(d); for(int i=0; i < num_msgs; i++) { transport.send(null, payload); total_msgs++; if(total_msgs % 1000 == 0) { System.out.println("++ sent " + total_msgs); } if(total_msgs % log_interval == 0) { //if(gnuplot_output == false) // if(log.isInfoEnabled()) log.info(dumpStats(total_msgs)); } } } void fetchResults() throws Exception { System.out.println("-- sent all messages. Asking receivers if they received all messages\n"); int expected_responses=this.members.size(); // now send DONE message (periodically re-send to make up for message loss over unreliable transport) // when all results have been received, dump stats and exit Data d2=new Data(Data.DONE); byte[] tmp=Util.objectToByteBuffer(d2); System.out.println("-- fetching results (from " + expected_responses + " members)"); synchronized(this.results) { while((results.size()) < expected_responses) { transport.send(null, tmp); this.results.wait(1000); } } System.out.println("-- received all responses"); } void dumpResults() { Object member; Map.Entry entry; HashMap map; StringBuffer sb=new StringBuffer(); sb.append("\n-- results:\n\n"); for(Iterator it=results.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); member=entry.getKey(); map=(HashMap)entry.getValue(); sb.append("-- results from ").append(member).append(":\n"); dump(map, sb); sb.append('\n'); } System.out.println(sb.toString()); if(log.isInfoEnabled()) log.info(sb.toString()); } void dumpSenders() { StringBuffer sb=new StringBuffer(); dump(this.senders, sb); System.out.println(sb.toString()); } void dump(HashMap map, StringBuffer sb) { Map.Entry entry; Object sender; MemberInfo mi; MemberInfo combined=new MemberInfo(0); combined.start = Long.MAX_VALUE; combined.stop = Long.MIN_VALUE; for(Iterator it2=map.entrySet().iterator(); it2.hasNext();) { entry=(Map.Entry)it2.next(); sender=entry.getKey(); mi=(MemberInfo)entry.getValue(); combined.start=Math.min(combined.start, mi.start); combined.stop=Math.max(combined.stop, mi.stop); combined.num_msgs_expected+=mi.num_msgs_expected; combined.num_msgs_received+=mi.num_msgs_received; combined.total_bytes_received+=mi.total_bytes_received; sb.append("sender: ").append(sender).append(": ").append(mi).append('\n'); } sb.append("\ncombined: ").append(combined).append('\n'); } String dumpStats(long received_msgs) { StringBuffer sb=new StringBuffer(); if(gnuplot_output) sb.append(received_msgs).append(' '); else sb.append("\nmsgs_received=").append(received_msgs); if(gnuplot_output) sb.append(Runtime.getRuntime().freeMemory() / 1000.0).append(' '); else sb.append(", free_mem=").append(Runtime.getRuntime().freeMemory() / 1000.0); if(gnuplot_output) sb.append(Runtime.getRuntime().totalMemory() / 1000.0).append(' '); else sb.append(", total_mem=").append(Runtime.getRuntime().totalMemory() / 1000.0).append('\n'); dumpThroughput(sb, received_msgs); return sb.toString(); } void dumpThroughput(StringBuffer sb, long received_msgs) { double tmp; long current=System.currentTimeMillis(); //if(last_dump == 0 || (current - last_dump) <= 0) { // last_dump=System.currentTimeMillis(); //return; tmp=(1000 * received_msgs) / (current - start); if(gnuplot_output) sb.append(tmp).append(' '); else sb.append("total_msgs_sec=").append(tmp).append(" [msgs/sec]"); tmp=(received_msgs * msg_size) / (current - start); if(gnuplot_output) sb.append(tmp).append(' '); else sb.append("\ntotal_throughput=").append(tmp).append(" [KB/sec]"); tmp=(1000 * log_interval) / (current - last_dump); if(gnuplot_output) sb.append(tmp).append(' '); else { sb.append("\nrolling_msgs_sec (last ").append(log_interval).append(" msgs)="); sb.append(tmp).append(" [msgs/sec]"); } tmp=(log_interval * msg_size) / (current - last_dump); if(gnuplot_output) sb.append(tmp).append(' '); else { sb.append("\nrolling_throughput (last ").append(log_interval).append(" msgs)="); sb.append(tmp).append(" [KB/sec]\n"); } last_dump=current; } void runDiscoveryPhase() throws Exception { Data d=new Data(Data.DISCOVERY_REQ); transport.send(null, Util.objectToByteBuffer(d)); sendDiscoveryResponse(); synchronized(this.members) { System.out.println("-- waiting for " + num_members + " members to join"); while(this.members.size() < num_members) { this.members.wait(); System.out.println("-- members: " + this.members.size()); } } } void sendDiscoveryResponse() throws Exception { Data d2=new Data(Data.DISCOVERY_RSP); if(sender) { d2.sender=true; d2.num_msgs=Long.parseLong(config.getProperty("num_msgs")); } transport.send(null, Util.objectToByteBuffer(d2)); } public static void main(String[] args) { Properties config=new Properties(); boolean sender=false, silent=false; Test t=null; for(int i=0; i < args.length; i++) { if("-sender".equals(args[i])) { config.put("sender", "true"); sender=true; continue; } if("-receiver".equals(args[i])) { config.put("sender", "false"); sender=false; continue; } if("-config".equals(args[i])) { String config_file=args[++i]; config.put("config", config_file); continue; } if("-props".equals(args[i])) { String props=args[++i]; config.put("props", props); continue; } if("-silent".equals(args[i])) { silent=true; continue; } help(); return; } try { t=new Test(); t.start(config, silent); t.runDiscoveryPhase(); if(sender) { t.sendMessages(); t.fetchResults(); t.dumpResults(); } else { synchronized(t) { t.wait(); } Util.sleep(2000); } } catch(Exception e) { e.printStackTrace(); } finally { if(t != null) t.stop(); } } static void help() { System.out.println("Test [-help] ([-sender] | [-receiver]) [-config <config file>] [-props <stack config>] [-silent]"); } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import com.xerox.amazonws.sdb.Domain; import com.xerox.amazonws.sdb.Item; import com.xerox.amazonws.sdb.ItemAttribute; import com.xerox.amazonws.sdb.ListDomainsResult; import com.xerox.amazonws.sdb.QueryResult; import com.xerox.amazonws.sdb.SDBException; import com.xerox.amazonws.sdb.SimpleDB; /** * Sample application demonstrating various operations against SDS. * */ public class sdbShell { /** * Executes specified query against given domain while demonstrating pagination. * * @param domain query domain * @param queryString query string * @param maxResults maximum number of values to return per page of results */ private static void executeQuery(Domain domain, String queryString, int maxResults) { String nextToken = ""; do { try { QueryResult result = domain.listItems(queryString, nextToken, maxResults); List<Item> items = result.getItemList(); for (Item i : items) { System.out.println(i.getIdentifier()); } nextToken = result.getNextToken(); } catch (SDBException ex) { System.out.println("Query '" + queryString + "' Failure: "); ex.printStackTrace(); } } while (nextToken != null && nextToken.trim().length() > 0); System.out.println("Done."); } /** * Executes specified query against given domain. * * @param domain query domain * @param queryString query string */ private static void executeQuery(Domain domain, String queryString) { executeQuery(domain, queryString, 0); } /** * Main execution body. * * @param args command line arguments (none required or processed) */ public static void main(String [] args) { if (args.length < 2) { System.err.println("usage: sdbShell <access key> <secret key> [command file]"); System.exit(1); } try { String awsAccessId = args[0]; String awsSecretKey = args[1]; if (awsAccessId == null || awsAccessId.trim().length() == 0) { System.out.println("Access key not set"); return; } if (awsSecretKey == null || awsSecretKey.trim().length() == 0) { System.out.println("Secret key not set"); return; } SimpleDB sds = new SimpleDB(awsAccessId, awsSecretKey, true); InputStream iStr = System.in; if (args.length > 2) { iStr = new FileInputStream(args[2]); } BufferedReader rdr = new BufferedReader(new InputStreamReader(iStr)); boolean done = false; Domain dom = null; while (!done) { System.out.print("sdbShell> "); String line = rdr.readLine(); if (line == null) { // exit, if end of input System.exit(0); } StringTokenizer st = new StringTokenizer(line); if (st.countTokens() == 0) { continue; } String cmd = st.nextToken().toLowerCase(); if (cmd.equals("q") || cmd.equals("quit")) { done = true; } else if (cmd.equals("h") || cmd.equals("?") || cmd.equals("help")) { showHelp(); } else if (cmd.equals("d") || cmd.equals("domains")) { ListDomainsResult result = sds.listDomains(); List<Domain> domains = result.getDomainList(); for (Domain d : domains) { System.out.println(d.getName()); } } else if (cmd.equals("ad") || cmd.equals("adddomain")) { if (st.countTokens() != 1) { System.out.println("Error: need domain name."); continue; } Domain d = sds.createDomain(st.nextToken()); } else if (cmd.equals("dd") || cmd.equals("deletedomain")) { if (st.countTokens() != 1) { System.out.println("Error: need domain name."); continue; } sds.deleteDomain(st.nextToken()); } else if (cmd.equals("sd") || cmd.equals("setdomain")) { if (st.countTokens() != 1) { System.out.println("Error: need domain name."); continue; } dom = sds.getDomain(st.nextToken()); } else if (cmd.equals("aa") || cmd.equals("addattr")) { if (checkDomain(dom)) { if (st.countTokens() != 3) { System.out.println("Error: need item id, attribute name and value."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> list = new ArrayList<ItemAttribute>(); list.add(new ItemAttribute(st.nextToken(), st.nextToken(), false)); item.putAttributes(list); } } else if (cmd.equals("ra") || cmd.equals("replaceattr")) { if (checkDomain(dom)) { if (st.countTokens() != 3) { System.out.println("Error: need item id, attribute name and value."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> list = new ArrayList<ItemAttribute>(); list.add(new ItemAttribute(st.nextToken(), st.nextToken(), true)); item.putAttributes(list); } } else if (cmd.equals("da") || cmd.equals("deleteattr")) { if (checkDomain(dom)) { if (st.countTokens() != 2) { System.out.println("Error: need item id and attribute name."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> list = new ArrayList<ItemAttribute>(); list.add(new ItemAttribute(st.nextToken(), null, true)); item.deleteAttributes(list); } } else if (cmd.equals("di") || cmd.equals("deleteitem")) { if (checkDomain(dom)) { if (st.countTokens() != 1) { System.out.println("Error: need item id."); continue; } dom.deleteItem(st.nextToken()); } } else if (cmd.equals("i") || cmd.equals("item")) { if (checkDomain(dom)) { if (st.countTokens() != 1) { System.out.println("Error: need item id."); continue; } Item item = dom.getItem(st.nextToken()); List<ItemAttribute> attrs = item.getAttributes(null); System.out.println("Item : "+item.getIdentifier()); for (ItemAttribute attr : attrs) { System.out.println(" "+attr.getName()+" = "+attr.getValue()); } } } else if (cmd.equals("l") || cmd.equals("list")) { if (checkDomain(dom)) executeQuery(dom, null); } else { if (checkDomain(dom)) executeQuery(dom, line); } } } catch (Exception ex) { ex.printStackTrace(); if (ex.getCause() != null) { System.err.println("caused by : "); ex.getCause().printStackTrace(); } } } private static boolean checkDomain(Domain dom) { if (dom == null) { System.out.println("domain must be set!"); return false; } return true; } private static void showHelp() { System.out.println("SimpleDB Shell Commands:"); System.out.println("adddomain(ad) <domain name> : add new domain"); System.out.println("deletedomain(dd) <domain name> : delete domain (not functional in SDS yet)"); System.out.println("domains(d) : list domains"); System.out.println("setdomain(sd) <domain name> : set current domain"); System.out.println("addattr(aa) <item id> <attr name> <attr value> : add attribute to item in current domain"); System.out.println("replaceattr(aa) <item id> <attr name> <attr value> : replace attribute to item in current domain"); System.out.println("deleteattr(da) <item id> <attr name> : delete attribute of item in current domain"); System.out.println("deleteitem(di) <item id> : delete item in current domain"); System.out.println("list(l) or <filter string> : lists items matching filter in current domain"); System.out.println("item(i) <item id> : shows item attributes"); System.out.println("help(h,?) : show help"); System.out.println("quit(q) : exit the shell"); } }
import java.util.ArrayList; import java.util.List; public class Node implements jburg.BurgInput<NodeType> { NodeType nodeType; List<Node> children; String content; private int stateNumber = -1; Node(NodeType type) { this.nodeType = type; this.children = new ArrayList<Node>(); } Node(NodeType type, String content) { this(type); this.content = content; } void addChild(Node n) { this.children.add(n); } public NodeType getNodeType() { return this.nodeType; } public int getSubtreeCount() { return children.size(); } public Node getSubtree(int idx) { return children.get(idx); } public void setStateNumber(int stateNumber) { this.stateNumber = stateNumber; } public int getStateNumber() { return this.stateNumber; } /* * ** Nullary Operators ** */ public Integer intLiteral() { return Integer.valueOf(content); } public Short shortLiteral() { return Short.valueOf(content); } /* * ** Unary Operators ** */ public Integer negate(Integer x) { return -x; } public Integer identity(Integer x) { return x; } /* * ** Binary Operators ** */ public Integer add(Integer x, Integer y) { return x + y; } public Integer subtract(Integer x, Integer y) { return x - y; } public Integer multiply(Integer x, Integer y) { return x * y; } public Integer divide(Integer x, Integer y) { return x / y; } public String stringLiteral() { return content; } public String concat(String lhs, String rhs) { return lhs + rhs; } public Integer widenShortToInt(Short operand) { return operand.intValue(); } @Override public String toString() { if (content == null) { return String.format("%s%s", nodeType, children); } else { return String.format("%s(%s)%s", nodeType, content, children); } } }
// This file is part of OpenTSDB. // This program is free software: you can redistribute it and/or modify it // option) any later version. This program is distributed in the hope that it // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser package net.opentsdb.core; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hbase.async.Bytes; import org.hbase.async.HBaseRpc; import org.hbase.async.KeyValue; import org.hbase.async.PleaseThrottleException; import net.opentsdb.stats.StatsCollector; /** * "Queue" of rows to compact. * <p> * Whenever we write a data point to HBase, the row key we write to is added * to this queue, which is effectively a sorted set. There is a separate * thread that periodically goes through the queue and look for "old rows" to * compact. A row is considered "old" if the timestamp in the row key is * older than a certain threshold. * <p> * The compaction process consists in reading all the cells within a given row * and writing them back out as a single big cell. Once that writes succeeds, * we delete all the individual little cells. * <p> * This process is effective because in HBase the row key is repeated for * every single cell. And because there is no way to efficiently append bytes * at the end of a cell, we have to do this instead. */ final class CompactionQueue extends ConcurrentSkipListMap<byte[], Boolean> { private static final Logger LOG = LoggerFactory.getLogger(CompactionQueue.class); /** * How many items are currently in the queue. * Because {@link ConcurrentSkipListMap#size} has O(N) complexity. */ private final AtomicInteger size = new AtomicInteger(); private final AtomicLong trivial_compactions = new AtomicLong(); private final AtomicLong complex_compactions = new AtomicLong(); private final AtomicLong written_cells = new AtomicLong(); private final AtomicLong deleted_cells = new AtomicLong(); /** The {@code TSDB} instance we belong to. */ private final TSDB tsdb; /** On how many bytes do we encode metrics IDs. */ private final short metric_width; /** * Constructor. * @param tsdb The TSDB we belong to. */ public CompactionQueue(final TSDB tsdb) { super(new Cmp(tsdb)); this.tsdb = tsdb; metric_width = tsdb.metrics.width(); if (TSDB.enable_compactions) { startCompactionThread(); } } @Override public int size() { return size.get(); } public void add(final byte[] row) { if (super.put(row, Boolean.TRUE) == null) { size.incrementAndGet(); // We added a new entry, count it. } } /** * Forces a flush of the all old entries in the compaction queue. * @return A deferred that will be called back once everything has been * flushed (or something failed, in which case the deferred will carry the * exception). In case of success, the kind of object returned is * unspecified. */ public Deferred<ArrayList<Object>> flush() { final int size = size(); if (size > 0) { LOG.info("Flushing all old outstanding rows out of " + size + " rows"); } final long now = System.currentTimeMillis(); return flush(now / 1000 - Const.MAX_TIMESPAN - 1, Integer.MAX_VALUE); } /** * Collects the stats and metrics tracked by this instance. * @param collector The collector to use. */ void collectStats(final StatsCollector collector) { collector.record("compaction.count", trivial_compactions, "type=trivial"); collector.record("compaction.count", complex_compactions, "type=complex"); if (!TSDB.enable_compactions) { return; } // The remaining stats only make sense with compactions enabled. collector.record("compaction.queue.size", size); collector.record("compaction.errors", handle_read_error.errors, "rpc=read"); collector.record("compaction.errors", handle_write_error.errors, "rpc=put"); collector.record("compaction.errors", handle_delete_error.errors, "rpc=delete"); collector.record("compaction.writes", written_cells); collector.record("compaction.deletes", deleted_cells); } /** * Flushes all the rows in the compaction queue older than the cutoff time. * @param cut_off A UNIX timestamp in seconds (unsigned 32-bit integer). * @param maxflushes How many rows to flush off the queue at once. * This integer is expected to be strictly positive. * @return A deferred that will be called back once everything has been * flushed. */ private Deferred<ArrayList<Object>> flush(final long cut_off, int maxflushes) { assert maxflushes > 0: "maxflushes must be > 0, but I got " + maxflushes; // We can't possibly flush more entries than size(). maxflushes = Math.min(maxflushes, size()); if (maxflushes == 0) { // Because size() might be 0. return Deferred.fromResult(new ArrayList<Object>(0)); } final ArrayList<Deferred<Object>> ds = new ArrayList<Deferred<Object>>(Math.min(maxflushes, MAX_CONCURRENT_FLUSHES)); int nflushes = 0; for (final byte[] row : this.keySet()) { if (maxflushes == 0) { break; } final long base_time = Bytes.getUnsignedInt(row, metric_width); if (base_time > cut_off) { break; } else if (nflushes == MAX_CONCURRENT_FLUSHES) { // We kicked off the compaction of too many rows already, let's wait // until they're done before kicking off more. break; } // You'd think that it would be faster to grab an iterator on the map // and then call remove() on the iterator to "unlink" the element // directly from where the iterator is at, but no, the JDK implements // it by calling remove(key) so it has to lookup the key again anyway. if (super.remove(row) == null) { // We didn't remove anything. continue; // So someone else already took care of this entry. } nflushes++; maxflushes size.decrementAndGet(); ds.add(tsdb.get(row).addCallbacks(compactcb, handle_read_error)); } final Deferred<ArrayList<Object>> group = Deferred.group(ds); if (nflushes == MAX_CONCURRENT_FLUSHES && maxflushes > 0) { // We're not done yet. Once this group of flushes completes, we need // to kick off more. tsdb.flush(); // Speed up this batch by telling the client to flush. final int maxflushez = maxflushes; // Make it final for closure. final class FlushMoreCB implements Callback<Deferred<ArrayList<Object>>, ArrayList<Object>> { public Deferred<ArrayList<Object>> call(final ArrayList<Object> arg) { return flush(cut_off, maxflushez); } public String toString() { return "Continue flushing with cut_off=" + cut_off + ", maxflushes=" + maxflushez; } } group.addCallbackDeferring(new FlushMoreCB()); } return group; } private final CompactCB compactcb = new CompactCB(); /** * Callback to compact a row once it's been read. * <p> * This is used once the "get" completes, to actually compact the row and * write back the compacted version. */ private final class CompactCB implements Callback<Object, ArrayList<KeyValue>> { public Object call(final ArrayList<KeyValue> row) { return compact(row, null); } public String toString() { return "compact"; } } /** * Compacts a row into a single {@link KeyValue}. * @param row The row containing all the KVs to compact. * Must contain at least one element. * @return A compacted version of this row. */ KeyValue compact(final ArrayList<KeyValue> row) { final KeyValue[] compacted = { null }; compact(row, compacted); return compacted[0]; } /** * Compacts a row into a single {@link KeyValue}. * <p> * If the {@code row} is empty, this function does literally nothing. * If {@code compacted} is not {@code null}, then the compacted form of this * {@code row} will be stored in {@code compacted[0]}. Obviously, if the * {@code row} contains a single cell, then that cell is the compacted form. * Otherwise the compaction process takes places. * @param row The row containing all the KVs to compact. Must be non-null. * @param compacted If non-null, the first item in the array will be set to * a {@link KeyValue} containing the compacted form of this row. * If non-null, we will also not write the compacted form back to HBase * unless the timestamp in the row key is old enough. * @return A {@link Deferred} if the compaction processed required a write * to HBase, otherwise {@code null}. */ private Deferred<Object> compact(final ArrayList<KeyValue> row, final KeyValue[] compacted) { if (row.size() <= 1) { if (row.isEmpty()) { // Maybe the row got deleted in the mean time? LOG.debug("Attempted to compact a row that doesn't exist."); } else if (compacted != null) { // no need to re-compact rows containing a single value. compacted[0] = row.get(0); } return null; } // We know we have at least 2 cells. We need to go through all the cells // to determine what kind of compaction we're going to do. If each cell // contains a single individual data point, then we can do a trivial // compaction. Otherwise, we have a partially compacted row, and the // logic required to compact it is more complex. boolean write = true; // Do we need to write a compacted cell? final KeyValue compact; { boolean trivial = true; // Are we doing a trivial compaction? int qual_len = 0; // Pre-compute the size of the qualifier we'll need. int val_len = 1; // Reserve an extra byte for meta-data. short last_delta = -1; // Time delta, extracted from the qualifier. KeyValue longest = row.get(0); // KV with the longest qualifier. int longest_idx = 0; // Index of `longest'. final int nkvs = row.size(); for (int i = 0; i < nkvs; i++) { final KeyValue kv = row.get(i); final byte[] qual = kv.qualifier(); // If the qualifier length isn't 2, this row might have already // been compacted, potentially partially, so we need to merge the // partially compacted set of cells, with the rest. final int len = qual.length; if (len != 2) { trivial = false; // We only do this here because no qualifier can be < 2 bytes. if (len > longest.qualifier().length) { longest = kv; longest_idx = i; } } else { // In the trivial case, do some sanity checking here. // For non-trivial cases, the sanity checking logic is more // complicated and is thus pushed down to `complexCompact'. final short delta = (short) ((Bytes.getShort(qual) & 0xFFFF) Const.FLAG_BITS); // This data point has a time delta that's less than or equal to // the previous one. This typically means we have 2 data points // at the same timestamp but they have different flags. We're // going to abort here because someone needs to fsck the table. if (delta <= last_delta) { throw new IllegalDataException("Found out of order or duplicate" + " data: last_delta=" + last_delta + ", delta=" + delta + ", offending KV=" + kv + ", row=" + row + " -- run an fsck."); } last_delta = delta; // We don't need it below for complex compactions, so we update it // only here in the `else' branch. final byte[] v = kv.value(); val_len += floatingPointValueToFix(qual[1], v) ? 4 : v.length; } qual_len += len; } if (trivial) { trivial_compactions.incrementAndGet(); compact = trivialCompact(row, qual_len, val_len); } else { complex_compactions.incrementAndGet(); compact = complexCompact(row, qual_len / 2); // Now it's vital that we check whether the compact KV has the same // qualifier as one of the qualifiers that were already in the row. // Otherwise we might do a `put' in this cell, followed by a delete. // We don't want to delete what we just wrote. // This can happen if this row was already compacted but someone // wrote another individual data point at the same timestamp. // Optimization: since we kept track of which KV had the longest // qualifier, we can opportunistically check here if it happens to // have the same qualifier as the one we just created. final byte[] qual = compact.qualifier(); final byte[] longest_qual = longest.qualifier(); if (qual.length <= longest_qual.length) { KeyValue dup = null; int dup_idx = -1; if (Bytes.equals(longest_qual, qual)) { dup = longest; dup_idx = longest_idx; } else { // Worst case: to be safe we have to loop again and check all // the qualifiers and make sure we're not going to overwrite // anything. // TODO(tsuna): Try to write a unit test that triggers this code // path. I'm not even sure it's possible. Should we replace // this code with an `assert false: "should never be here"'? for (int i = 0; i < nkvs; i++) { final KeyValue kv = row.get(i); if (Bytes.equals(kv.qualifier(), qual)) { dup = kv; dup_idx = i; break; } } } if (dup != null) { // So we did find an existing KV with the same qualifier. // Let's check if, by chance, the value is the same too. if (Bytes.equals(dup.value(), compact.value())) { // Since the values are the same, we don't need to write // anything. There's already a properly compacted version of // this row in TSDB. write = false; } // Now let's make sure we don't delete this qualifier. This // re-allocates the entire array, but should be a rare case. row.remove(dup_idx); } // else: no dup, we're good. } // else: most common case: the compact qualifier is longer than // the previously longest qualifier, so we cannot possibly // overwrite an existing cell we would then delete. } } if (compacted != null) { // Caller is interested in the compacted form. compacted[0] = compact; final long base_time = Bytes.getUnsignedInt(compact.key(), metric_width); final long cut_off = System.currentTimeMillis() / 1000 - Const.MAX_TIMESPAN - 1; if (base_time > cut_off) { // If row is too recent... return null; // ... Don't write back compacted. } } if (!TSDB.enable_compactions) { return null; } final byte[] key = compact.key(); //LOG.debug("Compacting row " + Arrays.toString(key)); deleted_cells.addAndGet(row.size()); // We're going to delete this. if (write) { final byte[] qual = compact.qualifier(); final byte[] value = compact.value(); written_cells.incrementAndGet(); return tsdb.put(key, qual, value) .addCallbacks(new DeleteCompactedCB(row), handle_write_error); } else { // We had nothing to write, because one of the cells is already the // correctly compacted version, so we can go ahead and delete the // individual cells directly. new DeleteCompactedCB(row).call(null); return null; } } /** * Performs a trivial compaction of a row. * <p> * This method is to be used only when all the cells in the given row * are individual data points (nothing has been compacted yet). If any of * the cells have already been compacted, the caller is expected to call * {@link #complexCompact} instead. * @param row The row to compact. Assumed to have 2 elements or more. * @param qual_len Exact number of bytes to hold the compacted qualifiers. * @param val_len Exact number of bytes to hold the compacted values. * @return a {@link KeyValue} containing the result of the merge of all the * {@code KeyValue}s given in argument. */ private static KeyValue trivialCompact(final ArrayList<KeyValue> row, final int qual_len, final int val_len) { // Now let's simply concatenate all the qualifiers and values together. final byte[] qualifier = new byte[qual_len]; final byte[] value = new byte[val_len]; // Now populate the arrays by copying qualifiers/values over. int qual_idx = 0; int val_idx = 0; for (final KeyValue kv : row) { final byte[] q = kv.qualifier(); // We shouldn't get into this function if this isn't true. assert q.length == 2: "Qualifier length must be 2: " + kv; final byte[] v = fixFloatingPointValue(q[1], kv.value()); qualifier[qual_idx++] = q[0]; qualifier[qual_idx++] = fixQualifierFlags(q[1], v.length); System.arraycopy(v, 0, value, val_idx, v.length); val_idx += v.length; } // Right now we leave the last byte all zeros, this last byte will be // used in the future to introduce more formats/encodings. final KeyValue first = row.get(0); return new KeyValue(first.key(), first.family(), qualifier, value); } /** * Fix the flags inside the last byte of a qualifier. * <p> * OpenTSDB used to not rely on the size recorded in the flags being * correct, and so for a long time it was setting the wrong size for * floating point values (pretending they were encoded on 8 bytes when * in fact they were on 4). So overwrite these bits here to make sure * they're correct now, because once they're compacted it's going to * be quite hard to tell if the flags are right or wrong, and we need * them to be correct to easily decode the values. * @param flags The least significant byte of a qualifier. * @param val_len The number of bytes in the value of this qualifier. * @return The least significant byte of the qualifier with correct flags. */ private static byte fixQualifierFlags(byte flags, final int val_len) { // Explanation: // (1) Take the last byte of the qualifier. // (2) Zero out all the flag bits but one. // The one we keep is the type (floating point vs integer value). // (3) Set the length properly based on the value we have. return (byte) ((flags & ~(Const.FLAGS_MASK >>> 1)) | (val_len - 1)); // (1) (2) (3) } /** * Returns whether or not this is a floating value that needs to be fixed. * <p> * OpenTSDB used to encode all floating point values as `float' (4 bytes) * but actually store them on 8 bytes, with 4 leading 0 bytes, and flags * correctly stating the value was on 4 bytes. * @param flags The least significant byte of a qualifier. * @param value The value that may need to be corrected. */ private static boolean floatingPointValueToFix(final byte flags, final byte[] value) { return (flags & Const.FLAG_FLOAT) != 0 // We need a floating point value. && (flags & Const.LENGTH_MASK) == 0x3 // That pretends to be on 4 bytes. && value.length == 8; // But is actually using 8 bytes. } private static byte[] fixFloatingPointValue(final byte flags, final byte[] value) { if (floatingPointValueToFix(flags, value)) { // The first 4 bytes should really be zeros. if (value[0] == 0 && value[1] == 0 && value[2] == 0 && value[3] == 0) { // Just keep the last 4 bytes. return new byte[] { value[4], value[5], value[6], value[7] }; } else { // Very unlikely. throw new IllegalDataException("Corrupted floating point value: " + Arrays.toString(value) + " flags=0x" + Integer.toHexString(flags) + " -- first 4 bytes are expected to be zeros."); } } return value; } /** * Helper class for complex compaction cases. * <p> * This is simply a glorified pair of (qualifier, value) that's comparable. * Only the qualifier is used to make comparisons. * @see #complexCompact */ private static final class Cell implements Comparable<Cell> { /** Tombstone used as a helper during the complex compaction. */ static final Cell SKIP = new Cell(null, null); final byte[] qualifier; final byte[] value; Cell(final byte[] qualifier, final byte[] value) { this.qualifier = qualifier; this.value = value; } public int compareTo(final Cell other) { return Bytes.memcmp(qualifier, other.qualifier); } public boolean equals(final Object o) { return o != null && o instanceof Cell && compareTo((Cell) o) == 0; } public int hashCode() { return Arrays.hashCode(qualifier); } public String toString() { return "Cell(" + Arrays.toString(qualifier) + ", " + Arrays.toString(value) + ')'; } } private static KeyValue complexCompact(final ArrayList<KeyValue> row, final int estimated_nvalues) { // We know at least one of the cells contains multiple values, and we need // to merge all the cells together in a sorted fashion. We use a simple // strategy: split all the cells into individual objects, sort them, // merge the result while ignoring duplicates (same qualifier & value). final ArrayList<Cell> cells = breakDownValues(row, estimated_nvalues); Collections.sort(cells); // Now let's done one pass first to compute the length of the compacted // value and to find if we have any bad duplicates (same qualifier, // different value). int nvalues = 0; int val_len = 1; // Reserve an extra byte for meta-data. short last_delta = -1; // Time delta, extracted from the qualifier. int ncells = cells.size(); for (int i = 0; i < ncells; i++) { final Cell cell = cells.get(i); final short delta = (short) ((Bytes.getShort(cell.qualifier) & 0xFFFF) Const.FLAG_BITS); // Because we sorted `cells' by qualifier, and because the time delta // occupies the most significant bits, this should never trigger. assert delta >= last_delta: ("WTF? It's supposed to be sorted: " + cells + " at " + i + " delta=" + delta + ", last_delta=" + last_delta); // The only troublesome case is where we have two (or more) consecutive // cells with the same time delta, but different flags or values. if (delta == last_delta) { // Find the previous cell. Because we potentially replace the one // right before `i' with a tombstone, we might need to look further // back a bit more. Cell prev = Cell.SKIP; // i > 0 because we can't get here during the first iteration. // Also the first Cell cannot be Cell.SKIP, so `j' will never // underflow. And even if it does, we'll get an exception. for (int j = i - 1; prev == Cell.SKIP; j prev = cells.get(j); } if (cell.qualifier[1] != prev.qualifier[1] || !Bytes.equals(cell.value, prev.value)) { throw new IllegalDataException("Found out of order or duplicate" + " data: cell=" + cell + ", delta=" + delta + ", prev cell=" + prev + ", last_delta=" + last_delta + ", in row=" + row + " -- run an fsck."); } // else: we're good, this is a true duplicate (same qualifier & value). // Just replace it with a tombstone so we'll skip it. We don't delete // it from the array because that would cause a re-allocation. cells.set(i, Cell.SKIP); continue; } last_delta = delta; nvalues++; val_len += cell.value.length; } final byte[] qualifier = new byte[nvalues * 2]; final byte[] value = new byte[val_len]; // Now populate the arrays by copying qualifiers/values over. int qual_idx = 0; int val_idx = 0; for (final Cell cell : cells) { if (cell == Cell.SKIP) { continue; } byte[] b = cell.qualifier; System.arraycopy(b, 0, qualifier, qual_idx, b.length); qual_idx += b.length; b = cell.value; System.arraycopy(b, 0, value, val_idx, b.length); val_idx += b.length; } // Right now we leave the last byte all zeros, this last byte will be // used in the future to introduce more formats/encodings. final KeyValue first = row.get(0); final KeyValue kv = new KeyValue(first.key(), first.family(), qualifier, value); return kv; } private static ArrayList<Cell> breakDownValues(final ArrayList<KeyValue> row, final int estimated_nvalues) { final ArrayList<Cell> cells = new ArrayList<Cell>(estimated_nvalues); for (final KeyValue kv : row) { final byte[] qual = kv.qualifier(); final int len = qual.length; final byte[] val = kv.value(); if (len == 2) { // Single-value cell. // Maybe we need to fix the flags in the qualifier. final byte[] actual_val = fixFloatingPointValue(qual[1], val); final byte q = fixQualifierFlags(qual[1], actual_val.length); final byte[] actual_qual; if (q != qual[1]) { // We need to fix the qualifier. actual_qual = new byte[] { qual[0], q }; // So make a copy. } else { actual_qual = qual; // Otherwise use the one we already have. } final Cell cell = new Cell(actual_qual, actual_val); cells.add(cell); continue; } // else: we have a multi-value cell. We need to break it down into // individual Cell objects. // First check that the last byte is 0, otherwise it might mean that // this compacted cell has been written by a future version of OpenTSDB // and we don't know how to decode it, so we shouldn't touch it. if (val[val.length - 1] != 0) { throw new IllegalDataException("Don't know how to read this value:" + Arrays.toString(val) + " found in " + kv + " -- this compacted value might have been written by a future" + " version of OpenTSDB, or could be corrupt."); } // Now break it down into Cells. int val_idx = 0; for (int i = 0; i < len; i += 2) { final byte[] q = new byte[] { qual[i], qual[i + 1] }; final int vlen = (q[1] & Const.LENGTH_MASK) + 1; final byte[] v = new byte[vlen]; System.arraycopy(val, val_idx, v, 0, vlen); val_idx += vlen; final Cell cell = new Cell(q, v); cells.add(cell); } // Check we consumed all the bytes of the value. Remember the last byte // is metadata, so it's normal that we didn't consume it. if (val_idx != val.length - 1) { throw new IllegalDataException("Corrupted value: couldn't break down" + " into individual values (consumed " + val_idx + " bytes, but was" + " expecting to consume " + (val.length - 1) + "): " + kv + ", cells so far: " + cells); } } return cells; } /** * Callback to delete a row that's been successfully compacted. */ private final class DeleteCompactedCB implements Callback<Object, Object> { /** What we're going to delete. */ private final byte[] key; private final byte[] family; private final byte[][] qualifiers; public DeleteCompactedCB(final ArrayList<KeyValue> cells) { final KeyValue first = cells.get(0); key = first.key(); family = first.family(); qualifiers = new byte[cells.size()][]; for (int i = 0; i < qualifiers.length; i++) { qualifiers[i] = cells.get(i).qualifier(); } } public Object call(final Object arg) { return tsdb.delete(key, qualifiers).addErrback(handle_delete_error); } public String toString() { return "delete compacted cells"; } } private final HandleErrorCB handle_read_error = new HandleErrorCB("read"); private final HandleErrorCB handle_write_error = new HandleErrorCB("write"); private final HandleErrorCB handle_delete_error = new HandleErrorCB("delete"); /** * Callback to handle exceptions during the compaction process. */ private final class HandleErrorCB implements Callback<Object, Exception> { private volatile int errors; private final String what; /** * Constructor. * @param what String describing what kind of operation (e.g. "read"). */ public HandleErrorCB(final String what) { this.what = what; } public Object call(final Exception e) { if (e instanceof PleaseThrottleException) { // HBase isn't keeping up. final HBaseRpc rpc = ((PleaseThrottleException) e).getFailedRpc(); if (rpc instanceof HBaseRpc.HasKey) { // We failed to compact this row. Whether it's because of a failed // get, put or delete, we should re-schedule this row for a future // compaction. add(((HBaseRpc.HasKey) rpc).key()); return Boolean.TRUE; // We handled it, so don't return an exception. } else { // Should never get in this clause. LOG.error("WTF? Cannot retry this RPC, and this shouldn't happen: " + rpc); } } // `++' is not atomic but doesn't matter if we miss some increments. if (++errors % 100 == 1) { // Basic rate-limiting to not flood logs. LOG.error("Failed to " + what + " a row to re-compact", e); } return e; } public String toString() { return "handle " + what + " error"; } } static final long serialVersionUID = 1307386642; /** Starts a compaction thread. Only one such thread is needed. */ private void startCompactionThread() { final Thrd thread = new Thrd(); thread.setDaemon(true); thread.start(); } /** How frequently the compaction thread wakes up flush stuff. */ // TODO(tsuna): Make configurable? private static final int FLUSH_INTERVAL = 10; // seconds /** Minimum number of rows we'll attempt to compact at once. */ // TODO(tsuna): Make configurable? private static final int MIN_FLUSH_THRESHOLD = 100; // rows /** Maximum number of rows we'll compact concurrently. */ // TODO(tsuna): Make configurable? private static final int MAX_CONCURRENT_FLUSHES = 10000; // rows /** If this is X then we'll flush X times faster than we really need. */ // TODO(tsuna): Make configurable? private static final int FLUSH_SPEED = 2; // multiplicative factor /** * Background thread to trigger periodic compactions. */ final class Thrd extends Thread { public Thrd() { super("CompactionThread"); } public void run() { long last_flush = 0; while (true) { try { final long now = System.currentTimeMillis(); final int size = size(); // Let's suppose MAX_TIMESPAN = 1h. We have `size' rows to compact, // and we better compact them all before in less than 1h, otherwise // we're going to "fall behind" when a new hour start (as we'll be // creating a ton of new rows then). So slice MAX_TIMESPAN using // FLUSH_INTERVAL to compute what fraction of `size' we need to // flush at each iteration. Note that `size' will usually account // for many rows that can't be flushed yet (not old enough) so we're // overshooting a bit (flushing more aggressively than necessary). // This isn't a problem at all. The only thing that matters is that // the rate at which we flush stuff is proportional to how much work // is sitting in the queue. The multiplicative factor FLUSH_SPEED // is added to make flush even faster than we need. For example, if // FLUSH_SPEED is 2, then instead of taking 1h to flush what we have // for the previous hour, we'll take only 30m. This is desirable so // that we evict old entries from the queue a bit faster. final int maxflushes = Math.max(MIN_FLUSH_THRESHOLD, size * FLUSH_INTERVAL * FLUSH_SPEED / Const.MAX_TIMESPAN); // Flush if either (1) it's been too long since the last flush // or (2) we have too many rows to recompact already. // Note that in the case (2) we might not be able to flush anything // if the rows aren't old enough. if (last_flush - now > Const.MAX_TIMESPAN || size > maxflushes) { flush(now / 1000 - Const.MAX_TIMESPAN - 1, maxflushes); if (LOG.isDebugEnabled()) { final int newsize = size(); LOG.debug("flush() took " + (System.currentTimeMillis() - now) + "ms, new queue size=" + newsize + " (" + (newsize - size) + ')'); } } } catch (Exception e) { LOG.error("Uncaught exception in compaction thread", e); } catch (OutOfMemoryError e) { // Let's free up some memory by throwing away the compaction queue. final int sz = size.get(); CompactionQueue.super.clear(); size.set(0); LOG.error("Discarded the compaction queue, size=" + sz, e); } catch (Throwable e) { LOG.error("Uncaught *Throwable* in compaction thread", e); // Catching this kind of error is totally unexpected and is really // bad. If we do nothing and let this thread die, we'll run out of // memory as new entries are added to the queue. We could always // commit suicide, but it's kind of drastic and nothing else in the // code does this. If `enable_compactions' wasn't final, we could // always set it to false, but that's not an option. So in order to // try to get a fresh start, let this compaction thread terminate // and spin off a new one instead. try { Thread.sleep(1000); // Avoid busy looping creating new threads. } catch (InterruptedException i) { LOG.error("Compaction thread interrupted in error handling", i); return; // Don't flush, we're truly hopeless. } startCompactionThread(); return; } try { Thread.sleep(FLUSH_INTERVAL * 1000); } catch (InterruptedException e) { LOG.error("Compaction thread interrupted, doing one last flush", e); flush(); return; } } } } /** * Helper to sort the byte arrays in the compaction queue. * <p> * This comparator sorts things by timestamp first, this way we can find * all rows of the same age at once. */ private static final class Cmp implements Comparator<byte[]> { /** On how many bytes do we encode metrics IDs. */ private final short metric_width; public Cmp(final TSDB tsdb) { metric_width = tsdb.metrics.width(); } public int compare(final byte[] a, final byte[] b) { final int c = Bytes.memcmp(a, b, metric_width, Const.TIMESTAMP_BYTES); // If the timestamps are equal, sort according to the entire row key. return c != 0 ? c : Bytes.memcmp(a, b); } } }
package core.commands; import core.Constants; import core.entities.QueueManager; import core.entities.Server; import core.exceptions.BadArgumentsException; import core.exceptions.DoesNotExistException; import core.exceptions.InvalidUseException; import core.util.Utils; import net.dv8tion.jda.core.entities.Member; public class CmdSub extends Command{ public CmdSub(){ this.helpMsg = Constants.SUB_HELP; this.description = Constants.SUB_DESC; this.name = Constants.SUB_NAME; } @Override public void execCommand(Server server, Member member, String[] args) { String targName, subName; QueueManager qm = server.getQueueManager(); try{ if(args.length < 3){ Member target = server.getMember(args[0]); Member substitute = null; if(args.length == 1){ substitute = member; }else{ substitute = server.getMember(args[1]); } if(target != null){ if(substitute != null){ qm.sub(target.getUser(), substitute.getUser()); targName = target.getEffectiveName(); subName = substitute.getEffectiveName(); }else{ throw new BadArgumentsException("Substitute player does not exist"); } }else{ throw new BadArgumentsException("Target player does not exist"); } }else{ throw new BadArgumentsException(); } qm.updateTopic(); this.response = Utils.createMessage(String.format("%s has been subbed with %s", targName, subName), "", true); System.out.println(success()); }catch(DoesNotExistException | BadArgumentsException | InvalidUseException ex){ this.response = Utils.createMessage("Error!", ex.getMessage(), false); } } }
package cs437.som; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.regex.Pattern; /** * Reads a self-organizing map from a file. */ public class FileReader { private static final Pattern COLON_SPLIT = Pattern.compile(":"); private TrainableSelfOrganizingMap tsom = null; private FileReader(File input) throws IOException { BufferedReader isr = new BufferedReader( new InputStreamReader(new FileInputStream(input))); String[] kv = COLON_SPLIT.split(isr.readLine()); if (kv.length != 2) { throw new SOMError( "Input file is malformed: first line must be a map type statement."); } String className = "cs437.som.network." + kv[1].trim(); try { Class<?> mapType = Class.forName(className); Method readMethod = mapType.getMethod("read", BufferedReader.class); tsom = (TrainableSelfOrganizingMap) readMethod.invoke(mapType, isr); } catch (ClassNotFoundException e) { throw new SOMError("Map type " + className + " cannot be found."); } catch (NoSuchMethodException e) { throw new SOMError("Map type " + className + " cannot be loaded from a file."); } catch (InvocationTargetException e) { throw new SOMError(e.getCause().getMessage()); } catch (IllegalAccessException e) { throw new SOMError("Internal error while parsing: " + e.getMessage()); } } public static TrainableSelfOrganizingMap read(File file) throws IOException { FileReader fileReader = new FileReader(file); return fileReader.tsom; } public static TrainableSelfOrganizingMap read(String filename) throws IOException { File file = new File(filename); return read(file); } @Override public String toString() { return "FileReader"; } }
package controller; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Enumeration; import java.util.Optional; import java.util.function.Predicate; import java.util.zip.ZipEntry; import encounter.Encounter; import encounter.EncounterEntry; import entity.Creature; import entity.Monster; import entity.Player; import gui.MainGUI; import javafx.application.Platform; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.ProgressBar; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.util.Callback; import library.LibraryEntry; public class MainController { private static int libEntries = 0; private ObservableList<LibraryEntry> libEntryList; private Encounter encounter; @FXML private ListView<LibraryEntry> libraryList; @FXML private ListView<EncounterEntry> encounterList; @FXML private Text entryAmountText; @FXML private TextField filterTextField; @FXML private TextField encounterNameTextField; @FXML private CheckBox autoSaveCheckBox; @FXML private ProgressBar loadingProgressBar; @FXML private Label loadingProgressLabel; private SimpleDoubleProperty barProgress; private SimpleStringProperty progressText; private float progress = 0.0f; private float amountToLoad = 0.0f; @FXML public void initialize() { barProgress = new SimpleDoubleProperty(0.0); progressText = new SimpleStringProperty(); loadingProgressBar.progressProperty().bindBidirectional(barProgress); loadingProgressLabel.textProperty().bindBidirectional(progressText); new Thread(new Runnable() { @Override public void run() { loadData(); fillLibrary(); addLibraryTextFieldFilter(); loadingProgressBar.setVisible(false); loadingProgressLabel.setVisible(false); } }).start(); initEncounter(); } private void initEncounter() { MainGUI.encounter = new Encounter("Unnamed Encounter"); encounter = MainGUI.encounter; encounterNameTextField.setText(encounter.getEncounterName()); encounterNameTextField.textProperty().bindBidirectional(encounter.encounterNameProperty); encounterNameTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { encounter.setEncounterName(newValue); } }); } private void addLibraryTextFieldFilter() { FilteredList<LibraryEntry> fData = new FilteredList<>(libEntryList, p -> true); filterTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { fData.setPredicate(new Predicate<LibraryEntry>() { @Override public boolean test(LibraryEntry t) { if (newValue == null || newValue.isEmpty()) { return true; } if (t.getCreature().getName().toLowerCase().contains(newValue.toLowerCase())) { return true; } return false; } }); libraryList.setItems(fData); } }); progress++; double prgs = progress / (amountToLoad * 2 + 1); barProgress.set(prgs); Platform.runLater(new Runnable() { @Override public void run() { progressText.set("Loading progress: " + (int) (prgs * 100) + "%"); } }); } private void loadData() { if (MainGUI.imageZipFile == null) { try { Files.walk(Paths.get(System.getProperty("user.dir") + "\\images")).forEach(filePath -> { if (Files.isRegularFile(filePath) && filePath.toString().toLowerCase().contains("png")) { amountToLoad++; } }); Files.walk(Paths.get(System.getProperty("user.dir") + "\\images")).forEach(filePath -> { if (Files.isRegularFile(filePath) && filePath.toString().toLowerCase().contains("png")) { String filePathString = filePath.toString(); String[] filePathSplitBackslash = filePathString.split("\\\\"); String[] fileNameSplitDot = filePathSplitBackslash[filePathSplitBackslash.length - 1] .split("\\."); String creatureName = fileNameSplitDot[0]; Monster m = new Monster(creatureName, filePathSplitBackslash[filePathSplitBackslash.length - 1]); MainGUI.creatureList.add(m); progress++; double prgs = progress / (amountToLoad * 2 + 1); barProgress.set(prgs); Platform.runLater(new Runnable() { @Override public void run() { progressText.set("Loading progress: " + (int) (prgs * 100) + "%"); } }); libEntries++; } }); } catch (IOException e) { e.printStackTrace(); } } else { Enumeration<? extends ZipEntry> entries = MainGUI.imageZipFile.entries(); while (entries.hasMoreElements()) { amountToLoad++; entries.nextElement(); } entries = MainGUI.imageZipFile.entries(); while (entries.hasMoreElements()) { ZipEntry ne = (ZipEntry) entries.nextElement(); String name = ne.getName().split("\\.")[0]; Monster m = new Monster(name, ne.getName()); MainGUI.creatureList.add(m); progress++; double prgs = progress / (amountToLoad * 2 + 1); barProgress.set(prgs); Platform.runLater(new Runnable() { @Override public void run() { progressText.set("Loading progress: " + (int) (prgs * 100) + "%"); } }); libEntries++; } } entryAmountText.setText("#Entries: " + libEntries); } private void fillLibrary() { ArrayList<LibraryEntry> leList = new ArrayList<LibraryEntry>(); for (Creature c : MainGUI.creatureList) { progress++; double prgs = progress / (amountToLoad * 2 + 1); barProgress.set(prgs); Platform.runLater(new Runnable() { @Override public void run() { progressText.set("Loading progress: " + (int) (prgs * 100) + "%"); } }); leList.add(new LibraryEntry(c)); } libEntryList = FXCollections.observableArrayList(leList); libraryList.setItems(libEntryList); } @FXML protected void newEncounter(ActionEvent event) { encounter.reset(); encounterList.setItems(encounter.getObsList()); } @FXML protected void loadEncounter(ActionEvent event) { final FileChooser fc = new FileChooser(); fc.setInitialDirectory(new File(System.getProperty("user.dir"))); fc.getExtensionFilters().add(new ExtensionFilter("D&D Encounter Save", "*.ddesav")); File file = fc.showOpenDialog(MainGUI.mainStage); if (file != null) { encounter.readFromFile(file); } encounterList.setItems(encounter.getObsList()); } @FXML protected void saveEncounter(ActionEvent event) { final FileChooser fc = new FileChooser(); fc.setInitialDirectory(new File(System.getProperty("user.dir"))); fc.getExtensionFilters().add(new ExtensionFilter("D&D Encounter Save", "*.ddesav")); File file = fc.showSaveDialog(MainGUI.mainStage); if (file != null) { encounter.saveToFile(file); } } @FXML protected void addNPC(ActionEvent event) { Dialog<String> d = new Dialog<String>(); d.setTitle("Enter Player Name"); d.setResizable(false); Label name = new Label("Filter: "); TextField filterTF = new TextField(); ListView<String> lv = new ListView<String>(); lv.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() == 2) { d.resultProperty().set(lv.getSelectionModel().getSelectedItem()); } } }); ArrayList<String> names = new ArrayList<String>(); for (LibraryEntry le : libEntryList) { names.add(le.getCreature().getName()); } ObservableList<String> ol = FXCollections.observableArrayList(names); lv.setItems(ol); FilteredList<String> fData = new FilteredList<String>(ol, p -> true); filterTF.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { fData.setPredicate(new Predicate<String>() { @Override public boolean test(String t) { if (newValue == null || newValue.isEmpty()) { return true; } if (t.toLowerCase().contains(newValue.toLowerCase())) { return true; } return false; } }); lv.setItems(fData); } }); GridPane grid = new GridPane(); grid.add(name, 0, 0); grid.add(filterTF, 1, 0); grid.add(lv, 0, 1, 2, 1); d.getDialogPane().setContent(grid); ButtonType okButton = new ButtonType("Save", ButtonData.OK_DONE); ButtonType cancelButton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); d.getDialogPane().getButtonTypes().add(okButton); d.getDialogPane().getButtonTypes().add(cancelButton); d.setResultConverter(new Callback<ButtonType, String>() { @Override public String call(ButtonType param) { if (param == okButton) { return lv.getSelectionModel().getSelectedItem(); } if (param == cancelButton) { return null; } return null; } }); Optional<String> a = d.showAndWait(); if (a.isPresent()) { encounter.addCreature(a.get()); encounterList.setItems(encounter.getObsList()); } } @FXML protected void addPlayer(ActionEvent event) { Dialog<String> d = new Dialog<String>(); d.setTitle("Enter Player Name"); d.setResizable(false); Label name = new Label("Name: "); TextField tf = new TextField(); GridPane grid = new GridPane(); grid.add(name, 0, 0); grid.add(tf, 1, 0); d.getDialogPane().setContent(grid); ButtonType okButton = new ButtonType("Save", ButtonData.OK_DONE); ButtonType cancelButton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); d.getDialogPane().getButtonTypes().add(okButton); d.getDialogPane().getButtonTypes().add(cancelButton); d.setResultConverter(new Callback<ButtonType, String>() { @Override public String call(ButtonType param) { if (param == okButton) { return tf.getText(); } if (param == cancelButton) { return null; } return null; } }); Optional<String> a = d.showAndWait(); if (a.isPresent()) { encounter.addCreature(new Player(tf.getText(), "")); encounterList.setItems(encounter.getObsList()); } } @FXML protected void deleteSelected(ActionEvent event) { if (!encounterList.getSelectionModel().isEmpty()) { if (encounter.getCreatureList().size() > 0) { encounter.getCreatureList().remove(encounterList.getSelectionModel().getSelectedIndex()); encounterList.setItems(encounter.getObsList()); } } } @FXML protected void copySelected(ActionEvent event) { if (!encounterList.getSelectionModel().isEmpty()) { encounter.copy(encounterList.getSelectionModel().getSelectedIndex()); encounterList.setItems(encounter.getObsList()); } } @FXML protected void sortEncounter(ActionEvent event) { encounter.sort(); encounterList.setItems(encounter.getObsList()); } @FXML protected void nextTurn(ActionEvent event) { encounter.setNextIndex(); encounterList.setItems(encounter.getObsList()); encounterList.scrollTo(encounter.getCurrentIndex()); } @FXML protected void previousTurn(ActionEvent event) { encounter.setLastIndex(); encounterList.setItems(encounter.getObsList()); encounterList.scrollTo(encounter.getCurrentIndex()); } private File imageFile = null; @FXML protected void addNewLibraryEntry(ActionEvent event) { Dialog<Creature> d = new Dialog<Creature>(); d.setTitle("Enter Player Name"); d.setResizable(false); Label name = new Label("Name: "); TextField tfName = new TextField(); Label image = new Label("Name: "); TextField imageName = new TextField(); imageName.setEditable(false); Button chooseImage = new Button("Select Image"); chooseImage.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { final FileChooser fc = new FileChooser(); fc.setInitialDirectory(new File(System.getProperty("user.dir"))); fc.getExtensionFilters().add(new ExtensionFilter("Image File", "*.png", "*.jpeg", "*.bmp")); File file = fc.showOpenDialog(MainGUI.mainStage); if (file != null) { imageFile = file; imageName.setText(file.getName()); } } }); GridPane grid = new GridPane(); grid.add(name, 0, 0); grid.add(tfName, 1, 0); grid.add(image, 0, 1); grid.add(imageName, 1, 1); grid.add(chooseImage, 2, 1); d.getDialogPane().setContent(grid); ButtonType okButton = new ButtonType("Save", ButtonData.OK_DONE); ButtonType cancelButton = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); d.getDialogPane().getButtonTypes().add(okButton); d.getDialogPane().getButtonTypes().add(cancelButton); d.setResultConverter(new Callback<ButtonType, Creature>() { @Override public Creature call(ButtonType param) { if (param == okButton) { return new Creature(tfName.getText(), imageFile.getName()); } if (param == cancelButton) { return null; } return null; } }); Optional<Creature> a = d.showAndWait(); if (a.isPresent()) { MainGUI.creatureList.add(a.get()); } } @FXML public void autoSaveChanged() { MainGUI.autosave = autoSaveCheckBox.isSelected(); } }
/* Description: * TODO: * */ package models; import java.math.BigInteger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.Version; import org.apache.commons.codec.digest.DigestUtils; import play.Logger; import play.data.format.Formats; import play.data.validation.Constraints; import play.db.ebean.Model; //the table name "user" might be invalid for some db systems @Entity @Table(name = "users") public class User extends Model implements Comparable<User> { //PathBindable<User>, /** User class, contains all personal information */ private static final long serialVersionUID = 5178587449713353935L; @Id public Long id; @Column(length = 255, unique = true, nullable = false) @Constraints.MaxLength(255) @Formats.NonEmpty @Constraints.Email public String email; @Column(length = 255, unique = true, nullable = false) @Constraints.MaxLength(255) @Constraints.Required @Formats.NonEmpty public String username; public String password; // only for username/password login public String firstName; public String lastName; @Column(length = 2*1024) @Constraints.MaxLength(2*1024) public String description = ""; public Double latitude = 0.0; public Double longitude = 0.0; @Column(nullable = false) public Date creationDate; public Date lastLogin; @OneToMany(mappedBy = "owner") public List<Resource> resourceList = new ArrayList<Resource>(); @OneToMany(mappedBy = "owner") public List<Stream> streamList = new ArrayList<Stream>(); @OneToMany(mappedBy = "owner") public List<Actuator> actuatorList = new ArrayList<Actuator>(); @OneToMany(mappedBy = "owner") public List<Vfile> fileList = new ArrayList<Vfile>(); @ManyToMany public List<Stream> followedStreams = new ArrayList<Stream>(); /** Secret token for session authentication */ @Transient public String currentSessionToken; /** Secret token for authentication */ private String token; private boolean admin=false; @Version // for concurrency protection private int version; public static Model.Finder<Long, User> find = new Model.Finder<Long, User>(Long.class, User.class); // constructor userd by OpenID callback public User(String email, String username, String firstName, String lastName) { this(); this.email = email.toLowerCase(); this.username = username.toLowerCase(); this.firstName = firstName; this.lastName = lastName; } public User() { this.creationDate = new Date(); setPassword(new BigInteger(130,new SecureRandom()).toString(32)); this.admin = false; this.description = ""; this.latitude = 0.0; this.longitude= 0.0; this.firstName = ""; this.lastName = ""; } public String getEmail() { return email; } public void setEmail(String email) { this.email=email; } public String getToken() { return token; } public String getUsername() { return username; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String description() { return description; } public Double getLatitude() { return latitude; } public Double getLongitude() { return longitude; } public Long getId() { return new Long(id); } public boolean exists() { return exists(id); } public boolean isAdmin() { return admin; } public void setAdmin(boolean admin){ this.admin = admin; } public void updateUser(User user) { this.username = user.username.toLowerCase(); this.firstName = user.firstName; this.lastName = user.lastName; this.password = user.password; this.latitude = user.latitude; this.longitude = user.longitude; this.description = user.description; update(); } public void setPassword(String newPassword) { this.password = DigestUtils.md5Hex(newPassword); } public String resetPassword() { String newPassword = new BigInteger(130,new SecureRandom()).toString(32); this.password = hash(newPassword); return newPassword; } public Date updateLastLogin() { this.lastLogin = new Date(); update(); return this.lastLogin; } public String generateToken() { token = UUID.randomUUID().toString(); //save(); return token; } //don't remove strange chars from username public void verify() { username = username.replaceAll("[\\/:\"*?<>|']+", ""); } @Override public void save() { verify(); super.save(); } @Override public void update() { verify(); super.update(); } public int compareTo(User user) { return token.compareTo(user.token); } public boolean equals(User user) { if (user==null) {Logger.warn("User is null");} if (user.token!=null) {Logger.warn("Token is null");} if (token.equals(user.token)) {Logger.warn("Token doesnt match");} if (this.id != user.id) {Logger.warn("id doesnt match: "+this.id+" "+user.id);} //return user!=null && user.token!=null && token.equals(user.token) && this.id == user.id; return user!=null && this.id == user.id; } public void followStream(Stream stream) { if(stream != null && stream.id > 0L && !followedStreams.contains(stream)) { followedStreams.add(stream); } this.saveManyToManyAssociations("followedStreams"); } public void unfollowStream(Stream stream) { if(stream != null && stream.id > 0L) { followedStreams.remove(stream); } this.saveManyToManyAssociations("followedStreams"); } public boolean isfollowingStream(Stream stream) { return (stream != null) && followedStreams.contains(stream); } public List<Stream> followedStreams() { return followedStreams; } public void sortStreamList() { Logger.info("Sorting StreamList"); Collections.sort(streamList); } // perform the Password -> Hash transform public static String hash(String toHash) { return DigestUtils.md5Hex(toHash); } public static User create(User user) { user.generateToken(); user.save(); // is this necessary? -YES! user.saveManyToManyAssociations("followedStreams"); return user; } public static User getByToken(String token) { if (token == null) { return null; } try { return find.where().eq("token", token).findUnique(); } catch (Exception e) { return null; } } public static List<User> all() { return find.where().orderBy("username asc").findList(); } public static boolean exists(Long id) { return find.byId(id) != null; } public static User get(Long id) { return (id==null) ? null : find.byId(id); } public static User getByEmail(String email) { return find.where().eq("email", email).findUnique(); } public static User getByUserName(String username) { return find.where().eq("username", username).findUnique(); } public static void delete(Long id) { find.ref(id).delete(); } }
package roslab.model.electronics; /** * @author Peter Gebhard * */ public class PinService { String name; int number; char one_to_many = '#'; // Default to 1-to-1 connection type String io; String superServiceName; int superServiceNumber; int af; /** * @param name * @param number * @param io */ public PinService(String name, int number, String io) { this.name = name; this.number = number; this.io = io; } /** * @param name * @param number * @param one_to_many * @param io */ public PinService(String name, int number, char one_to_many, String io) { this.name = name; this.number = number; this.one_to_many = one_to_many; this.io = io; } /** * @param name * @param number * @param one_to_many * @param io * @param superServiceName * @param superServiceNumber */ public PinService(String name, int number, char one_to_many, String io, int af) { this.name = name; this.number = number; this.one_to_many = one_to_many; this.io = io; this.af = af; } /** * @param name * @param number * @param one_to_many * @param io * @param superServiceName * @param superServiceNumber */ public PinService(String name, int number, char one_to_many, String io, String superServiceName, int superServiceNumber) { this.name = name; this.number = number; this.one_to_many = one_to_many; this.io = io; this.superServiceName = superServiceName; this.superServiceNumber = superServiceNumber; } /** * @param name * @param number * @param one_to_many * @param io * @param superServiceName * @param superServiceNumber * @param af */ public PinService(String name, int number, char one_to_many, String io, String superServiceName, int superServiceNumber, int af) { this.name = name; this.number = number; this.one_to_many = one_to_many; this.io = io; this.superServiceName = superServiceName; this.superServiceNumber = superServiceNumber; this.af = af; } /** * @return the name */ public String getName() { return name; } /** * @return the number */ public int getNumber() { return number; } /** * @return the one_to_many */ public char getOne_to_many() { return one_to_many; } /** * @return the io */ public String getIo() { return io; } /** * @return the superServiceName */ public String getSuperServiceName() { return superServiceName; } /** * @return the superServiceNumber */ public int getSuperServiceNumber() { return superServiceNumber; } /** * @return the af */ public int getAf() { return af; } }
package emulatorinterface; import java.util.Enumeration; import java.util.Hashtable; import pipeline.outoforder.BootPipelineEvent; import memorysystem.MemorySystem; import generic.Time_t; import memorysystem.Bus; import memorysystem.Cache; import memorysystem.CoreMemorySystem; import memorysystem.Global; import misc.Error; import config.CacheConfig; import config.SimulationConfig; import config.SystemConfig; import config.XMLParser; import emulatorinterface.DynamicInstructionBuffer; import emulatorinterface.communication.*; import emulatorinterface.communication.shm.SharedMem; import emulatorinterface.translator.x86.objparser.ObjParser; import generic.Core; import generic.GlobalClock; import generic.InstructionList; import generic.InstructionTable; import generic.NewEventQueue; public class Newmain { public static int handled=0; public static int notHandled=0; //public static Object syncObject = new Object(); //public static Object syncObject2 = new Object(); public static void main(String[] arguments) throws Exception { // check command line arguments checkCommandLineArguments(arguments); // Read the command line arguments String executableFile = arguments[0]; // Parse the command line arguments XMLParser.parse(); // Create a hash-table for the static representation of the executable InstructionTable instructionTable; instructionTable = ObjParser .buildStaticInstructionTable(executableFile); // Create a new dynamic instruction buffer DynamicInstructionBuffer dynamicInstructionBuffer = new DynamicInstructionBuffer(); // configure the emulator configureEmulator(); // create PIN interface IPCBase ipcBase = new SharedMem(instructionTable); Process process = createPINinterface(ipcBase, arguments, dynamicInstructionBuffer); //create event queue NewEventQueue eventQ = new NewEventQueue(); //create cores Core[] cores = initCores(eventQ, ipcBase); //Create the memory system MemorySystem.initializeMemSys(cores); //different core components may work at different frequencies GlobalClock.systemTimingSetUp(cores, MemorySystem.getCacheList()); //commence pipeline eventQ.addEvent(new BootPipelineEvent(cores, ipcBase, eventQ, 0)); //Thread.sleep(10000); //System.out.println("finished sleeping.."); //while(core.getExecEngine().isExecutionComplete() == false) while(eventQ.isEmpty() == false) { eventQ.processEvents(); GlobalClock.incrementClock(); } //synchronized(Newmain.syncObject2) { //Newmain.syncObject2.notify(); } // returns the number of instructions. and waits on a semaphore for // finishing of reader threads long icount = ipcBase.doExpectedWaitForSelf(); /* //TODO currently simulating single core //number of cores to be read from configuration file Core core = new Core(dynamicInstructionBuffer, 0); //set up initial events in the queue eventQ.addEvent(new PerformDecodeEvent(0, core)); eventQ.addEvent(new PerformCommitsEvent(0, core)); */ // Call these functions at last ipcBase.doWaitForPIN(process); ipcBase.finish(); // Display coverage double coverage = (double)(handled*100)/(double)(handled+notHandled); System.out.print("\n\tDynamic coverage = " + coverage + " %\n"); } // TODO Must provide parameters to make from here private static void configureEmulator() { } private static Process createPINinterface(IPCBase ipcBase, String[] arguments, DynamicInstructionBuffer dynamicInstructionBuffer) { // Creating command for PIN tool. String cmd = SimulationConfig.PinTool + "/pin" + " -t " + SimulationConfig.PinInstrumentor + " -map " + SimulationConfig.MapEmuCores + " for(int i = 0; i < arguments.length; i++) { cmd += " "; cmd += arguments[i]; } Process process = null; try { process = ipcBase.startPIN(cmd); } catch (Exception e) { misc.Error .showErrorAndExit("\n\tUnable to run the required program using PIN !!"); } if (process == null) misc.Error .showErrorAndExit("\n\tCorrect path for pin or tool or executable not specified !!"); ipcBase.createReaders(dynamicInstructionBuffer); return process; } // checks if the command line arguments are in required format and number private static void checkCommandLineArguments(String arguments[]) { if (arguments.length < 1) { Error.showErrorAndExit("\n\tIllegal number of arguments !!"); } } //TODO read a config file //create specified number of cores //map threads to cores static Core[] initCores(NewEventQueue eventQ, IPCBase ipcBase) { System.out.println("initializing cores..."); Core[] cores = new Core[]{ new Core(0, eventQ, 1, new InstructionList[]{ipcBase.getReaderThreads()[0].getInputToPipeline()}, new int[]{0})}; return cores; } }
package simulators.basic; import core.Attribute; import core.Link; import core.Path; import core.events.*; import io.reporters.Reporter; import simulators.DataCollector; import simulators.Dataset; import simulators.DetectionData; import java.io.IOException; import java.util.Iterator; /** * Collects all data that can be stored in a basic dataset. */ public class BasicDataCollector implements DataCollector, ExportListener, DetectListener, StartListener, AdvertisementListener, EndListener, ThresholdReachedListener { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Fields * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ protected final BasicDataset dataset = new BasicDataset(); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Creates a new basic data collector and registers it with the event notifier to receive notifications * of all the required events. */ public BasicDataCollector() { EventNotifier.eventNotifier().addExportListener(this); EventNotifier.eventNotifier().addDetectListener(this); EventNotifier.eventNotifier().addStartListener(this); EventNotifier.eventNotifier().addAdvertisementListener(this); EventNotifier.eventNotifier().addEndListener(this); EventNotifier.eventNotifier().addThresholdReachedListener(this); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public Interface - Data Collector Interface * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Gives access to the data set storing the collected data. The dataset implementation returned depends on the * collector implementation. * * @return a dataset instance with the collected data. */ @Override public Dataset getDataset() { return dataset; } /** * Unregisters from the event notifier for all events. */ @Override public void unregister() { EventNotifier.eventNotifier().removeExportListener(this); EventNotifier.eventNotifier().removeDetectListener(this); EventNotifier.eventNotifier().removeStartListener(this); EventNotifier.eventNotifier().removeAdvertisementListener(this); EventNotifier.eventNotifier().removeEndListener(this); EventNotifier.eventNotifier().removeThresholdReachedListener(this); } /** * Clears all data that has been collected. */ @Override public void clear() { dataset.clear(); } /** * Reports the current collected data using the given reporter implementation. * * @param reporter reporter implementation to be used. * @param simulationNumber number of the simulation being reported. */ @Override public void report(Reporter reporter, int simulationNumber) throws IOException { reporter.report(simulationNumber, dataset); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Event Handling Methods - This methods are called during the simulation and should not be * called elsewhere. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Invoked when a detect event occurs. It checks if the detection was a false positive. * * @param event detect event that occurred. */ @Override public void onDetected(DetectEvent event) { Path cycle = event.getCycle(); // start with the alternative route's attribute Attribute initialAttribute = event.getAlternativeRoute().getAttribute(); // extend the attribute along the path Attribute attribute = initialAttribute; Iterator<Link> linkIterator = cycle.inLinksIterator(); while (linkIterator.hasNext()) { Link link = linkIterator.next(); attribute = link.getLabel().extend(link, attribute); } // it is a false positive if the alternative route's attribute when extended along the cycle // returns an attribute with equal or lower preference boolean falsePositive = (attribute.compareTo(initialAttribute) >= 0); dataset.addDetection(new DetectionData(event.getDetectingRouter(), event.getOutLink(), cycle, initialAttribute, falsePositive)); } /** * Invoked when a export event occurs. * * @param event export event that occurred. */ @Override public void onExported(ExportEvent event) { dataset.addMessage(); } /** * Invoked when a start event occurs. Stores the simulation seed. * * @param event start event that occurred. */ @Override public void onStarted(StartEvent event) { dataset.setSimulationSeed(event.getSeed()); } /** * Invoked when a advertisement event occurs. * * @param event advertisement event that occurred. */ @Override public void onAdvertised(AdvertisementEvent event) { dataset.setLastMessageTime(event.getAdvertisingRouter(), event.getTimeInstant()); } /** * Invoked when a end event occurs. * * @param event end event that occurred. */ @Override public void onEnded(EndEvent event) { dataset.setSimulationTime(event.getTimeInstant()); } /** * Invoked when a threshold reached event occurs. * * @param event threshold reached event that occurred. */ @Override public void onThresholdReached(ThresholdReachedEvent event) { dataset.setProtocolTerminated(false); } }
package com.tns; import java.io.Closeable; import java.io.DataInputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.LocalServerSocket; import android.net.LocalSocket; import android.util.Log; public class NativeScriptSyncService { private static String SYNC_ROOT_SOURCE_DIR = "/data/local/tmp/"; private static final String SYNC_SOURCE_DIR = "/sync/"; private static final String FULL_SYNC_SOURCE_DIR = "/fullsync/"; private static final String REMOVED_SYNC_SOURCE_DIR = "/removedsync/"; private static Logger logger; private final Context context; private final String syncPath; private final String fullSyncPath; private final String removedSyncPath; private final File fullSyncDir; private final File syncDir; private final File removedSyncDir; private LocalServerSocketThread localServerThread; private Thread localServerJavaThread; public NativeScriptSyncService(Logger logger, Context context) { this.logger = logger; this.context = context; syncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + SYNC_SOURCE_DIR; fullSyncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + FULL_SYNC_SOURCE_DIR; removedSyncPath = SYNC_ROOT_SOURCE_DIR + context.getPackageName() + REMOVED_SYNC_SOURCE_DIR; fullSyncDir = new File(fullSyncPath); syncDir = new File(syncPath); removedSyncDir = new File(removedSyncPath); } public void sync() { if (logger != null && logger.isEnabled()) { logger.write("Sync is enabled:"); logger.write("Sync path : " + syncPath); logger.write("Full sync path : " + fullSyncPath); logger.write("Removed files sync path: " + removedSyncPath); } if (fullSyncDir.exists()) { executeFullSync(context, fullSyncDir); deleteRecursive(fullSyncDir); return; } if (syncDir.exists()) { executePartialSync(context, syncDir); deleteRecursive(syncDir); } if (removedSyncDir.exists()) { executeRemovedSync(context, removedSyncDir); deleteRecursive(removedSyncDir); } } private class LocalServerSocketThread implements Runnable { private volatile boolean running; private final String name; private ListenerWorker commThread; private LocalServerSocket serverSocket; public LocalServerSocketThread(String name) { this.name = name; this.running = false; } public void stop() { this.running = false; try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } public void run() { running = true; try { serverSocket = new LocalServerSocket(this.name); while (running) { LocalSocket socket = serverSocket.accept(); commThread = new ListenerWorker(socket); new Thread(commThread).start(); } } catch (IOException e) { e.printStackTrace(); } } } private class ListenerWorker implements Runnable { private final DataInputStream input; private Closeable socket; private OutputStream output; public ListenerWorker(LocalSocket socket) throws IOException { this.socket = socket; input = new DataInputStream(socket.getInputStream()); output = socket.getOutputStream(); } public void run() { try { int length = input.readInt(); input.readFully(new byte[length]); //ignore the payload executePartialSync(context, syncDir); Platform.runScript(new File(NativeScriptSyncService.this.context.getFilesDir(), "internal/livesync.js")); try { output.write(1); } catch (IOException e) { e.printStackTrace(); } socket.close(); } catch (IOException e) { e.printStackTrace(); } } } public void startServer() { localServerThread = new LocalServerSocketThread(context.getPackageName() + "-livesync"); localServerJavaThread = new Thread(localServerThread); localServerJavaThread.start(); } private void deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { deleteRecursive(child); } } fileOrDirectory.delete(); } public static boolean isSyncEnabled(Context context) { int flags; boolean shouldExecuteSync = false; try { flags = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.flags; shouldExecuteSync = ((flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); } catch (NameNotFoundException e) { e.printStackTrace(); return false; } return shouldExecuteSync; } final FileFilter deletingFilesFilter = new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isDirectory()) { return true; } boolean success = pathname.delete(); if (!success) { logger.write("Syncing: file not deleted: " + pathname.getAbsolutePath().toString()); } return false; } }; private void deleteDir(File directory) { File[] subDirectories = directory.listFiles(deletingFilesFilter); if (subDirectories != null) { for (int i = 0; i < subDirectories.length; i++) { File subDir = subDirectories[i]; deleteDir(subDir); } } boolean success = directory.delete(); if (!success && directory.exists()) { logger.write("Syncing: directory not deleted: " + directory.getAbsolutePath().toString()); } } private void moveFiles(File sourceDir, String sourceRootAbsolutePath, String targetRootAbsolutePath) { File[] files = sourceDir.listFiles(); if (files != null) { if (logger.isEnabled()) { logger.write("Syncing total number of fiiles: " + files.length); } for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isFile()) { if (logger.isEnabled()) { logger.write("Syncing: " + file.getAbsolutePath().toString()); } String targetFilePath = file.getAbsolutePath().replace(sourceRootAbsolutePath, targetRootAbsolutePath); File targetFileDir = new File(targetFilePath); File targetParent = targetFileDir.getParentFile(); if (targetParent != null) { targetParent.mkdirs(); } boolean success = copyFile(file.getAbsolutePath(), targetFilePath); if (!success) { logger.write("Sync failed: " + file.getAbsolutePath().toString()); } } else { moveFiles(file, sourceRootAbsolutePath, targetRootAbsolutePath); } } } else { if (logger.isEnabled()) { logger.write("Can't move files. Source is empty."); } } } // this removes only the app directory from the device to preserve // any existing files in /files directory on the device private void executeFullSync(Context context, final File sourceDir) { String appPath = context.getFilesDir().getAbsolutePath() + "/app"; final File appDir = new File(appPath); if (appDir.exists()) { deleteDir(appDir); moveFiles(sourceDir, sourceDir.getAbsolutePath(), appDir.getAbsolutePath()); } } private void executePartialSync(Context context, File sourceDir) { String appPath = context.getFilesDir().getAbsolutePath() + "/app"; final File appDir = new File(appPath); if (!appDir.exists()) { Log.e("TNS", "Application dir does not exists. Partial Sync failed. appDir: " + appPath); return; } if (logger.isEnabled()) { logger.write("Syncing sourceDir " + sourceDir.getAbsolutePath() + " with " + appDir.getAbsolutePath()); } moveFiles(sourceDir, sourceDir.getAbsolutePath(), appDir.getAbsolutePath()); } private void deleteRemovedFiles(File sourceDir, String sourceRootAbsolutePath, String targetRootAbsolutePath) { File[] files = sourceDir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isFile()) { if (logger.isEnabled()) { logger.write("Syncing removed file: " + file.getAbsolutePath().toString()); } String targetFilePath = file.getAbsolutePath().replace(sourceRootAbsolutePath, targetRootAbsolutePath); File targetFile = new File(targetFilePath); targetFile.delete(); } else { deleteRemovedFiles(file, sourceRootAbsolutePath, targetRootAbsolutePath); } } } } private void executeRemovedSync(final Context context, final File sourceDir) { String appPath = context.getFilesDir().getAbsolutePath() + "/app"; deleteRemovedFiles(sourceDir, sourceDir.getAbsolutePath(), appPath); } private boolean copyFile(String sourceFile, String destinationFile) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destinationFile, false); byte[] buffer = new byte[4096]; int read = 0; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { logger.write("Error copying file " + sourceFile); e.printStackTrace(); return false; } catch (IOException e) { logger.write("Error copying file " + sourceFile); e.printStackTrace(); return false; } finally { try { if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { } } return true; } }
package dr.app.beauti; import dr.app.beauti.components.ComponentFactory; import dr.app.beauti.components.SequenceErrorModelComponentFactory; import dr.app.beauti.components.TipDateSamplingComponentFactory; import dr.app.beauti.datapanel.DataPanel; import dr.app.beauti.generator.BeastGenerator; import dr.app.beauti.mcmcpanel.MCMCPanel; import dr.app.beauti.modelsPanel.ModelsPanel; import dr.app.beauti.operatorspanel.OperatorsPanel; import dr.app.beauti.options.*; import dr.app.beauti.priorsPanel.PriorsPanel; import dr.app.beauti.taxonsetspanel.TaxaPanel; import dr.app.beauti.tipdatepanel.TipDatesPanel; import dr.app.beauti.traitspanel.TraitsPanel; import dr.app.beauti.treespanel.OldTreesPanel; import dr.app.beauti.treespanel.SpeciesTreesPanel; import dr.app.beauti.treespanel.TreesPanel; import dr.app.beauti.util.NexusApplicationImporter; import dr.app.util.Arguments; import dr.app.util.Utils; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.SimpleAlignment; import dr.evolution.io.Importer; import dr.evolution.io.NexusImporter; import dr.evolution.tree.Tree; import dr.evolution.util.Taxa; import dr.evolution.util.Taxon; import dr.evolution.util.TaxonList; import dr.evolution.util.Units; import dr.java16compat.FileNameExtensionFilter; import org.jdom.JDOMException; import org.virion.jam.framework.DocumentFrame; import org.virion.jam.framework.Exportable; import org.virion.jam.util.IconUtils; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.BorderUIResource; import java.awt.*; import java.awt.event.ActionEvent; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Map; /** * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: BeautiFrame.java,v 1.22 2006/09/09 16:07:06 rambaut Exp $ */ public class BeautiFrame extends DocumentFrame { private static final long serialVersionUID = 2114148696789612509L; private final BeautiOptions beautiOptions; private final BeastGenerator generator; private final JTabbedPane tabbedPane = new JTabbedPane(); public final JLabel statusLabel = new JLabel("No data loaded"); private DataPanel dataPanel; private TipDatesPanel tipDatesPanel; private TraitsPanel traitsPanel; private TaxaPanel taxaPanel; private ModelsPanel modelsPanel; private OldTreesPanel oldTreesPanel; private SpeciesTreesPanel speciesTreesPanel; private TreesPanel treesPanel; private PriorsPanel priorsPanel; private OperatorsPanel operatorsPanel; private MCMCPanel mcmcPanel; private BeautiPanel currentPanel; private JFileChooser chooser; // make JFileChooser chooser remember previous path final Icon gearIcon = IconUtils.getIcon(this.getClass(), "images/gear.png"); public BeautiFrame(String title) { super(); setTitle(title); // Prevent the application to close in requestClose() // after a user cancel or a failure in beast file generation setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); getOpenAction().setEnabled(false); getSaveAction().setEnabled(false); getFindAction().setEnabled(false); getZoomWindowAction().setEnabled(false); ComponentFactory[] components = { SequenceErrorModelComponentFactory.INSTANCE, TipDateSamplingComponentFactory.INSTANCE }; beautiOptions = new BeautiOptions(components); generator = new BeastGenerator(beautiOptions, components); } public void initializeComponents() { dataPanel = new DataPanel(this, getImportAction(), getDeleteAction()); tipDatesPanel = new TipDatesPanel(this); traitsPanel = new TraitsPanel(this, getImportTraitsAction()); taxaPanel = new TaxaPanel(this); modelsPanel = new ModelsPanel(this, getDeleteAction()); oldTreesPanel = new OldTreesPanel(this); treesPanel = new TreesPanel(this, getDeleteAction()); speciesTreesPanel = new SpeciesTreesPanel(this); priorsPanel = new PriorsPanel(this); operatorsPanel = new OperatorsPanel(this); mcmcPanel = new MCMCPanel(this); tabbedPane.addTab("Data Partitions", dataPanel); tabbedPane.addTab("Taxon Sets", taxaPanel); tabbedPane.addTab("Tip Dates", tipDatesPanel); tabbedPane.addTab("Traits", traitsPanel); tabbedPane.addTab("Models", modelsPanel); if (DataPanel.ALLOW_UNLINKED_TREES) { tabbedPane.addTab("Trees", treesPanel); } else { tabbedPane.addTab("Trees", oldTreesPanel); } tabbedPane.addTab("Priors", priorsPanel); tabbedPane.addTab("Operators", operatorsPanel); tabbedPane.addTab("MCMC", mcmcPanel); currentPanel = (BeautiPanel) tabbedPane.getSelectedComponent(); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { BeautiPanel selectedPanel = (BeautiPanel) tabbedPane.getSelectedComponent(); if (selectedPanel == dataPanel) { dataPanel.selectionChanged(); } else { getDeleteAction().setEnabled(false); } currentPanel.getOptions(beautiOptions); setAllOptions(); currentPanel = selectedPanel; } }); JPanel panel = new JPanel(new BorderLayout(6, 6)); panel.setBorder(new BorderUIResource.EmptyBorderUIResource(new java.awt.Insets(12, 12, 12, 12))); panel.add(tabbedPane, BorderLayout.CENTER); getExportAction().setEnabled(false); JButton generateButton = new JButton(getExportAction()); generateButton.putClientProperty("JButton.buttonType", "roundRect"); JPanel panel2 = new JPanel(new BorderLayout(6, 6)); panel2.add(statusLabel, BorderLayout.CENTER); panel2.add(generateButton, BorderLayout.EAST); panel.add(panel2, BorderLayout.SOUTH); getContentPane().setLayout(new java.awt.BorderLayout(0, 0)); getContentPane().add(panel, BorderLayout.CENTER); setAllOptions(); setSize(new java.awt.Dimension(1024, 768)); // make JFileChooser chooser remember previous path chooser = new JFileChooser(Utils.getCWD()); } /** * set all the options for all panels */ private void setAllOptions() { dataPanel.setOptions(beautiOptions); tipDatesPanel.setOptions(beautiOptions); traitsPanel.setOptions(beautiOptions); taxaPanel.setOptions(beautiOptions); modelsPanel.setOptions(beautiOptions); if (beautiOptions.isSpeciesAnalysis()) { speciesTreesPanel.setOptions(beautiOptions); } else if (DataPanel.ALLOW_UNLINKED_TREES) { treesPanel.setOptions(beautiOptions); } else { oldTreesPanel.setOptions(beautiOptions); } priorsPanel.setOptions(beautiOptions); operatorsPanel.setOptions(beautiOptions); mcmcPanel.setOptions(beautiOptions); } /** * get all the options for all panels */ private void getAllOptions() { dataPanel.getOptions(beautiOptions); tipDatesPanel.getOptions(beautiOptions); traitsPanel.getOptions(beautiOptions); taxaPanel.getOptions(beautiOptions); modelsPanel.getOptions(beautiOptions); if (beautiOptions.isSpeciesAnalysis()) { speciesTreesPanel.getOptions(beautiOptions); } else if (DataPanel.ALLOW_UNLINKED_TREES) { treesPanel.getOptions(beautiOptions); } else { oldTreesPanel.getOptions(beautiOptions); } priorsPanel.getOptions(beautiOptions); operatorsPanel.getOptions(beautiOptions); mcmcPanel.getOptions(beautiOptions); } public final void dataSelectionChanged(boolean isSelected) { getDeleteAction().setEnabled(isSelected); } public final void modelSelectionChanged(boolean isSelected) { getDeleteAction().setEnabled(isSelected); } public void doDelete() { if (tabbedPane.getSelectedComponent() == dataPanel) { dataPanel.removeSelection(); // } else if (tabbedPane.getSelectedComponent() == modelsPanel) { // modelsPanel.removeSelection(); // } else if (tabbedPane.getSelectedComponent() == treesPanel) { // treesPanel.removeSelection(); } else { throw new RuntimeException("Delete should only be accessable from the Data and Models panels"); } setStatusMessage(); } public boolean requestClose() { if (isDirty()) { int option = JOptionPane.showConfirmDialog(this, "You have made changes but have not generated\n" + "a BEAST XML file. Do you wish to generate\n" + "before closing this window?", "Unused changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.YES_OPTION) { return !doGenerate(); } else if (option == JOptionPane.CANCEL_OPTION || option == JOptionPane.DEFAULT_OPTION) { return false; } return true; } return true; } public void doApplyTemplate() { FileDialog dialog = new FileDialog(this, "Apply Template", FileDialog.LOAD); dialog.setVisible(true); if (dialog.getFile() != null) { File file = new File(dialog.getDirectory(), dialog.getFile()); try { readFromFile(file); } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "Unable to open template file: File not found", "Unable to open file", JOptionPane.ERROR_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Unable to read template file: " + ioe.getMessage(), "Unable to read file", JOptionPane.ERROR_MESSAGE); } } } protected boolean readFromFile(File file) throws IOException { return false; } public String getDefaultFileName() { return beautiOptions.fileNameStem + ".beauti"; } protected boolean writeToFile(File file) throws IOException { return false; } public final void doImport() { chooser.setMultiSelectionEnabled(true); FileNameExtensionFilter filter = new FileNameExtensionFilter( "NEXUS (*.nex) & BEAST (*.xml) Files", "nex", "nexus", "nx", "xml", "beast"); chooser.setFileFilter(filter); int returnVal = chooser.showDialog(this, "Import Aligment..."); if (returnVal == JFileChooser.APPROVE_OPTION) { File[] files = chooser.getSelectedFiles(); for (File file : files) { if (file == null || file.getName().equals("")) { JOptionPane.showMessageDialog(this, "Invalid file name", "Invalid file name", JOptionPane.ERROR_MESSAGE); } else { try { importFromFile(file); setDirty(); } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "Unable to open file: File not found", "Unable to open file", JOptionPane.ERROR_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(), "Unable to read file", JOptionPane.ERROR_MESSAGE); } } } } } protected void importFromFile(File file) throws IOException { Reader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); String line = bufferedReader.readLine(); while (line != null && line.length() == 0) { line = bufferedReader.readLine(); } if ((line != null && line.toUpperCase().contains("#NEXUS"))) { // is a NEXUS file importNexusFile(file); } else { // assume it is a BEAST XML file and see if that works... importBEASTFile(file); } setStatusMessage(); setAllOptions(); // @Todo templates are not implemented yet... // getOpenAction().setEnabled(true); // getSaveAction().setEnabled(true); getExportAction().setEnabled(true); } protected void importBEASTFile(File file) throws IOException { try { FileReader reader = new FileReader(file); BeastImporter importer = new BeastImporter(reader); java.util.List<TaxonList> taxonLists = new ArrayList<TaxonList>(); java.util.List<Alignment> alignments = new ArrayList<Alignment>(); importer.importBEAST(taxonLists, alignments); TaxonList taxa = taxonLists.get(0); for (Alignment alignment : alignments) { setData(taxa, alignment, null, null, null, file.getName()); } } catch (JDOMException e) { JOptionPane.showMessageDialog(this, "Unable to import file: " + e.getMessage(), "Unable to import file", JOptionPane.WARNING_MESSAGE); } catch (Importer.ImportException e) { JOptionPane.showMessageDialog(this, "Unable to import file: " + e.getMessage(), "Unable to import file", JOptionPane.WARNING_MESSAGE); } } protected void importNexusFile(File file) throws IOException { TaxonList taxa = null; SimpleAlignment alignment = null; java.util.List<Tree> trees = new ArrayList<Tree>(); PartitionSubstitutionModel model = null; java.util.List<NexusApplicationImporter.CharSet> charSets = new ArrayList<NexusApplicationImporter.CharSet>(); try { FileReader reader = new FileReader(file); NexusApplicationImporter importer = new NexusApplicationImporter(reader); boolean done = false; while (!done) { try { NexusImporter.NexusBlock block = importer.findNextBlock(); if (block == NexusImporter.TAXA_BLOCK) { if (taxa != null) { throw new NexusImporter.MissingBlockException("TAXA block already defined"); } taxa = importer.parseTaxaBlock(); } else if (block == NexusImporter.CALIBRATION_BLOCK) { if (taxa == null) { throw new NexusImporter.MissingBlockException("TAXA or DATA block must be defined before a CALIBRATION block"); } importer.parseCalibrationBlock(taxa); } else if (block == NexusImporter.CHARACTERS_BLOCK) { if (taxa == null) { throw new NexusImporter.MissingBlockException("TAXA block must be defined before a CHARACTERS block"); } if (alignment != null) { throw new NexusImporter.MissingBlockException("CHARACTERS or DATA block already defined"); } alignment = (SimpleAlignment) importer.parseCharactersBlock(taxa); } else if (block == NexusImporter.DATA_BLOCK) { if (alignment != null) { throw new NexusImporter.MissingBlockException("CHARACTERS or DATA block already defined"); } // A data block doesn't need a taxon block before it // but if one exists then it will use it. alignment = (SimpleAlignment) importer.parseDataBlock(taxa); if (taxa == null) { taxa = alignment; } } else if (block == NexusImporter.TREES_BLOCK) { // I guess there is no reason not to allow multiple trees blocks // if (trees.size() > 0) { // throw new NexusImporter.MissingBlockException("TREES block already defined"); Tree[] treeArray = importer.parseTreesBlock(taxa); trees.addAll(Arrays.asList(treeArray)); if (taxa == null && trees.size() > 0) { taxa = trees.get(0); } } else if (block == NexusApplicationImporter.PAUP_BLOCK) { model = importer.parsePAUPBlock(beautiOptions, charSets); } else if (block == NexusApplicationImporter.MRBAYES_BLOCK) { model = importer.parseMrBayesBlock(beautiOptions, charSets); } else if (block == NexusApplicationImporter.ASSUMPTIONS_BLOCK) { importer.parseAssumptionsBlock(charSets); } else { // Ignore the block.. } } catch (EOFException ex) { done = true; } } // Allow the user to load taxa only (perhaps from a tree file) so that they can sample from a prior... if (alignment == null && taxa == null) { throw new NexusImporter.MissingBlockException("TAXON, DATA or CHARACTERS block is missing"); } } catch (Importer.ImportException ime) { JOptionPane.showMessageDialog(this, "Error parsing imported file: " + ime, "Error reading file", JOptionPane.ERROR_MESSAGE); ime.printStackTrace(); return; } catch (IOException ioex) { JOptionPane.showMessageDialog(this, "File I/O Error: " + ioex, "File I/O Error", JOptionPane.ERROR_MESSAGE); ioex.printStackTrace(); return; } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Fatal exception: " + ex, "Error reading file", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); return; } setData(taxa, alignment, trees, model, charSets, file.getName()); } private void setData( TaxonList taxa, Alignment alignment, java.util.List<Tree> trees, PartitionSubstitutionModel model, java.util.List<NexusApplicationImporter.CharSet> charSets, String fileName) { String fileNameStem = dr.app.util.Utils.trimExtensions(fileName, new String[]{"NEX", "NEXUS", "TRE", "TREE", "XML"}); if (beautiOptions.taxonList == null) { // This is the first partition to be loaded... beautiOptions.taxonList = new Taxa(taxa); // check the taxon names for invalid characters boolean foundAmp = false; for (Taxon taxon : taxa) { String name = taxon.getId(); if (name.indexOf('&') >= 0) { foundAmp = true; } } if (foundAmp) { JOptionPane.showMessageDialog(this, "One or more taxon names include an illegal character ('&').\n" + "These characters will prevent BEAST from reading the resulting XML file.\n\n" + "Please edit the taxon name(s) before reloading the data file.", "Illegal Taxon Name(s)", JOptionPane.WARNING_MESSAGE); return; } // make sure they all have dates... for (int i = 0; i < taxa.getTaxonCount(); i++) { if (taxa.getTaxonAttribute(i, "date") == null) { java.util.Date origin = new java.util.Date(0); dr.evolution.util.Date date = dr.evolution.util.Date.createTimeSinceOrigin(0.0, Units.Type.YEARS, origin); taxa.getTaxon(i).setAttribute("date", date); } } beautiOptions.fileNameStem = fileNameStem; } else { // This is an additional partition so check it uses the same taxa if (!beautiOptions.allowDifferentTaxa) { // not allow Different Taxa java.util.List<String> oldTaxa = new ArrayList<String>(); for (int i = 0; i < beautiOptions.taxonList.getTaxonCount(); i++) { oldTaxa.add(beautiOptions.taxonList.getTaxon(i).getId()); } java.util.List<String> newTaxa = new ArrayList<String>(); for (int i = 0; i < taxa.getTaxonCount(); i++) { newTaxa.add(taxa.getTaxon(i).getId()); } if (!(oldTaxa.containsAll(newTaxa) && oldTaxa.size() == newTaxa.size())) { // AR - Yes and No are perfectly good answers to this question int adt = JOptionPane.showOptionDialog(this, "This file contains different taxa from the previously loaded\n" + "data partitions. This may be because the taxa are mislabelled\n" + "and need correcting before reloading.\n\n" + "Would you like to allow different taxa for each partition?\n", "Validation of Non-matching Taxon Name(s)", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[]{"Yes", "No"}, "No" ); // default button title if (adt == JOptionPane.YES_OPTION) { // set to Allow Different Taxa beautiOptions.allowDifferentTaxa = true; //changeTabs();// can be added, if required in future java.util.List<String> prevTaxa = new ArrayList<String>(); for (int i = 0; i < beautiOptions.taxonList.getTaxonCount(); i++) { prevTaxa.add(beautiOptions.taxonList.getTaxon(i).getId()); } for (int i = 0; i < taxa.getTaxonCount(); i++) { if (!prevTaxa.contains(taxa.getTaxon(i).getId())) { beautiOptions.taxonList.addTaxon(taxa.getTaxon(i)); } } } else { return; } } } else { // allow Different Taxa // AR - it will be much simpler just to consider beautiOptions.taxonList // to be the union set of all taxa. Each data partition has an alignment // which is a taxon list containing the taxa specific to that partition // for (Taxon taxon : taxa) { // not working // if (!beautiOptions.taxonList.contains(taxon)) { // beautiOptions.taxonList.addTaxon(taxon); // add the new diff taxa java.util.List<String> prevTaxa = new ArrayList<String>(); for (int i = 0; i < beautiOptions.taxonList.getTaxonCount(); i++) { prevTaxa.add(beautiOptions.taxonList.getTaxon(i).getId()); } for (int i = 0; i < taxa.getTaxonCount(); i++) { if (!prevTaxa.contains(taxa.getTaxon(i).getId())) { beautiOptions.taxonList.addTaxon(taxa.getTaxon(i)); } } } } addAlignment(alignment, charSets, model, fileName, fileNameStem); addTrees(trees); } private void addAlignment(Alignment alignment, java.util.List<NexusApplicationImporter.CharSet> charSets, PartitionSubstitutionModel model, String fileName, String fileNameStem) { if (alignment != null) { java.util.List<PartitionData> partitions = new ArrayList<PartitionData>(); if (charSets != null && charSets.size() > 0) { for (NexusApplicationImporter.CharSet charSet : charSets) { partitions.add(new PartitionData(charSet.getName(), fileName, alignment, charSet.getFromSite(), charSet.getToSite(), charSet.getEvery())); } } else { partitions.add(new PartitionData(fileNameStem, fileName, alignment)); } for (PartitionData partition : partitions) { beautiOptions.dataPartitions.add(partition); //TODO Cannot load Substitution Model and Tree Model from BEAST file yet if (model != null) { partition.setPartitionSubstitutionModel(model); // beautiOptions.addPartitionSubstitutionModel(model); // use same tree model and same tree prior in beginning for (PartitionTreeModel ptm : beautiOptions.getPartitionTreeModels()) { partition.setPartitionTreeModel(ptm); if (ptm.getPartitionTreePrior() == null || !(ptm.getPartitionTreePrior().getName().equalsIgnoreCase(beautiOptions.activedSameTreePrior.getName()))) { PartitionTreePrior ptp = new PartitionTreePrior(beautiOptions, ptm); ptm.setPartitionTreePrior(ptp); } } if (partition.getPartitionTreeModel() == null) { // PartitionTreeModel based on PartitionData PartitionTreeModel ptm = new PartitionTreeModel(beautiOptions, partition); partition.setPartitionTreeModel(ptm); // PartitionTreePrior always based on PartitionTreeModel PartitionTreePrior ptp = new PartitionTreePrior(beautiOptions, ptm); ptm.setPartitionTreePrior(ptp); // beautiOptions.addPartitionTreeModel(ptm); beautiOptions.shareSameTreePrior = true; beautiOptions.activedSameTreePrior = ptp; } // use same clock model in beginning, have to create after partition.setPartitionTreeModel(ptm); for (PartitionClockModel pcm : beautiOptions.getPartitionClockModels()) { partition.setPartitionClockModel(pcm); } if (partition.getPartitionClockModel() == null) { // PartitionClockModel based on PartitionData PartitionClockModel pcm = new PartitionClockModel(beautiOptions, partition); partition.setPartitionClockModel(pcm); // beautiOptions.addPartitionClockModel(pcm); } } else {// only this works for (PartitionSubstitutionModel psm : beautiOptions.getPartitionSubstitutionModels()) { if (psm.getDataType() == alignment.getDataType()) { // use same substitution model in beginning partition.setPartitionSubstitutionModel(psm); } } if (partition.getPartitionSubstitutionModel() == null) { // PartitionSubstitutionModel based on PartitionData PartitionSubstitutionModel psm = new PartitionSubstitutionModel(beautiOptions, partition); partition.setPartitionSubstitutionModel(psm); // beautiOptions.addPartitionSubstitutionModel(psm); } // use same tree model and same tree prior in beginning for (PartitionTreeModel ptm : beautiOptions.getPartitionTreeModels()) { partition.setPartitionTreeModel(ptm); if (ptm.getPartitionTreePrior() == null || !(ptm.getPartitionTreePrior().getName().equalsIgnoreCase(beautiOptions.activedSameTreePrior.getName()))) { PartitionTreePrior ptp = new PartitionTreePrior(beautiOptions, ptm); ptm.setPartitionTreePrior(ptp); } } if (partition.getPartitionTreeModel() == null) { // PartitionTreeModel based on PartitionData PartitionTreeModel ptm = new PartitionTreeModel(beautiOptions, partition); partition.setPartitionTreeModel(ptm); // PartitionTreePrior always based on PartitionTreeModel PartitionTreePrior ptp = new PartitionTreePrior(beautiOptions, ptm); ptm.setPartitionTreePrior(ptp); // beautiOptions.addPartitionTreeModel(ptm); beautiOptions.shareSameTreePrior = true; beautiOptions.activedSameTreePrior = ptp; } // use same clock model in beginning, have to create after partition.setPartitionTreeModel(ptm); for (PartitionClockModel pcm : beautiOptions.getPartitionClockModels()) { partition.setPartitionClockModel(pcm); } if (partition.getPartitionClockModel() == null) { // PartitionClockModel based on PartitionData PartitionClockModel pcm = new PartitionClockModel(beautiOptions, partition); partition.setPartitionClockModel(pcm); // beautiOptions.addPartitionClockModel(pcm); } } } beautiOptions.updatePartitionClockTreeLinks(); } } private void addTrees(java.util.List<Tree> trees) { if (trees != null && trees.size() > 0) { for (Tree tree : trees) { String id = tree.getId(); if (id == null || id.trim().length() == 0) { tree.setId("tree_" + (beautiOptions.userTrees.size() + 1)); } else { String newId = id; int count = 1; for (Tree tree1 : beautiOptions.userTrees) { if (tree1.getId().equals(newId)) { newId = id + "_" + count; count++; } } tree.setId(newId); } beautiOptions.userTrees.add(tree); } } } public final void doImportTraits() { if (beautiOptions.taxonList != null) { // validation of check empty taxonList FileDialog dialog = new FileDialog(this, "Import Traits File...", FileDialog.LOAD); dialog.setVisible(true); if (dialog.getFile() != null) { final File file = new File(dialog.getDirectory(), dialog.getFile()); importTraitsFromFile(file); } } else { JOptionPane.showMessageDialog(this, "No taxa loaded yet, please import Alignment file!", "No taxa loaded", JOptionPane.ERROR_MESSAGE); } } protected void importTraitsFromFile(final File file) { try { importMultiTraits(file); } catch (FileNotFoundException fnfe) { JOptionPane.showMessageDialog(this, "Unable to open file: File not found", "Unable to open file", JOptionPane.ERROR_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(), "Unable to read file", JOptionPane.ERROR_MESSAGE); } if (beautiOptions.isSpeciesAnalysis()) { // species setupSpeciesAnalysis(); } setAllOptions(); } public void setupSpeciesAnalysis() { dataPanel.selectAll(); dataPanel.unlinkModels(); //TODO tree for (PartitionSubstitutionModel model : beautiOptions.getPartitionSubstitutionModels()) { // model.initAllParametersAndOperators(); } int i = tabbedPane.indexOfTab("Trees"); tabbedPane.removeTabAt(i); tabbedPane.insertTab("Trees", null, speciesTreesPanel, "", i); speciesTreesPanel.getOptions(beautiOptions); beautiOptions.initSpeciesParametersAndOperators(); beautiOptions.fileNameStem = "LogStem"; setStatusMessage(); } public void removeSepciesAnalysisSetup() { int i = tabbedPane.indexOfTab("Trees"); tabbedPane.removeTabAt(i); if (DataPanel.ALLOW_UNLINKED_TREES) { tabbedPane.insertTab("Trees", null, treesPanel, "", i); } else { tabbedPane.insertTab("Trees", null, oldTreesPanel, "", i); } setStatusMessage(); } public void removeSpecifiedTreePrior(boolean isChecked) { // TipDatesPanel usingTipDates //TODO: wait for new implementation in BEAST if (DataPanel.ALLOW_UNLINKED_TREES) { treesPanel.setCheckedTipDate(isChecked); } else { if (isChecked) { oldTreesPanel.treePriorCombo.removeItem(TreePrior.YULE); oldTreesPanel.treePriorCombo.removeItem(TreePrior.BIRTH_DEATH); } else { oldTreesPanel.treePriorCombo = new JComboBox(EnumSet.range(TreePrior.CONSTANT, TreePrior.BIRTH_DEATH).toArray()); } } } private void importMultiTraits(final File file) throws IOException { // if( beautiOptions.taxonList == null ) { // JOptionPane.showMessageDialog(this, "No taxa loaded yet - noting done!", // "No taxa loaded", JOptionPane.ERROR_MESSAGE); // return; // } // move to doImportTraits() try { Map<String, List<String[]>> traits = Utils.importTraitsFromFile(file, "\t"); for (Map.Entry<String, List<String[]>> e : traits.entrySet()) { final List<String[]> value = e.getValue(); final Class c = Utils.detectTYpe(e.getValue().get(0)[1]); final String label = e.getKey(); Boolean warningGiven = false; for (String[] v : e.getValue()) { final Class c1 = Utils.detectTYpe(v[1]); if (c != c1 && !warningGiven) { JOptionPane.showMessageDialog(this, "Not all values of same type in column" + label, "Incompatible values", JOptionPane.WARNING_MESSAGE); warningGiven = true; // TODO Error - not all values of same type } } beautiOptions.selecetedTraits.add(label); TraitGuesser.TraitType t = (c == Boolean.class || c == String.class) ? TraitGuesser.TraitType.DISCRETE : (c == Integer.class) ? TraitGuesser.TraitType.INTEGER : TraitGuesser.TraitType.CONTINUOUS; beautiOptions.traitTypes.put(label, t); for (final String[] v : e.getValue()) { final int index = beautiOptions.taxonList.getTaxonIndex(v[0]); if (index >= 0) { // if the taxon isn't in the list then ignore it. // TODO provide a warning of unmatched taxa final Taxon taxon = beautiOptions.taxonList.getTaxon(index); taxon.setAttribute(label, Utils.constructFromString(c, v[1])); } } } } catch (Arguments.ArgumentException e) { JOptionPane.showMessageDialog(this, "Error in loading traits file: " + e.getMessage(), "Error Loading file", JOptionPane.ERROR_MESSAGE); } } private void setStatusMessage() { String message = ""; if (beautiOptions.dataPartitions.size() > 0) { message += "Data: " + beautiOptions.taxonList.getTaxonCount() + " taxa, " + beautiOptions.dataPartitions.size() + (beautiOptions.dataPartitions.size() > 1 ? " partitions" : " partition"); if (beautiOptions.isSpeciesAnalysis()) { int num = beautiOptions.getSpeciesList().size(); message += ", " + num + " species"; // species is both singular and plural } if (beautiOptions.userTrees.size() > 0) { message += ", " + beautiOptions.userTrees.size() + (beautiOptions.userTrees.size() > 1 ? " trees" : " tree"); } if (beautiOptions.allowDifferentTaxa) { message += " in total"; } if (beautiOptions.isSpeciesAnalysis()) { message += "; Welcome to *BEAST"; } } else if (beautiOptions.userTrees.size() > 0) { message += "Trees only : " + beautiOptions.userTrees.size() + (beautiOptions.userTrees.size() > 1 ? " trees, " : " tree, ") + beautiOptions.taxonList.getTaxonCount() + " taxa"; } else if (beautiOptions.taxonList != null && beautiOptions.taxonList.getTaxonCount() > 0) { message += "Taxa only: " + beautiOptions.taxonList.getTaxonCount() + " taxa"; } statusLabel.setText(message); } public final boolean doGenerate() { try { generator.checkOptions(); } catch (IllegalArgumentException iae) { JOptionPane.showMessageDialog(this, iae.getMessage(), "Unable to generate file", JOptionPane.ERROR_MESSAGE); return false; } // todo offer stem as default FileNameExtensionFilter filter = new FileNameExtensionFilter("Generate BEAST File...", "xml", "beast"); chooser.setFileFilter(filter); final int returnVal = chooser.showSaveDialog(this); if( returnVal == JFileChooser.APPROVE_OPTION ) { File file = chooser.getSelectedFile(); try { generate(file); } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Unable to generate file: " + ioe.getMessage(), "Unable to generate file", JOptionPane.ERROR_MESSAGE); return false; } } // FileDialog dialog = new FileDialog(this, // "Generate BEAST File...", // FileDialog.SAVE); // dialog.setVisible(true); // if (dialog.getFile() != null) { // File file = new File(dialog.getDirectory(), dialog.getFile()); // try { // generate(file); // } catch (IOException ioe) { // JOptionPane.showMessageDialog(this, "Unable to generate file: " + ioe.getMessage(), // "Unable to generate file", // JOptionPane.ERROR_MESSAGE); // return false; clearDirty(); return true; } protected void generate(File file) throws IOException { getAllOptions(); FileWriter fw = new FileWriter(file); generator.generateXML(fw); fw.close(); } public JComponent getExportableComponent() { JComponent exportable = null; Component comp = tabbedPane.getSelectedComponent(); if (comp instanceof Exportable) { exportable = ((Exportable) comp).getExportableComponent(); } else if (comp instanceof JComponent) { exportable = (JComponent) comp; } return exportable; } public boolean doSave() { return doSaveAs(); } public boolean doSaveAs() { FileDialog dialog = new FileDialog(this, "Save Template As...", FileDialog.SAVE); dialog.setVisible(true); if (dialog.getFile() == null) { // the dialog was cancelled... return false; } File file = new File(dialog.getDirectory(), dialog.getFile()); try { if (writeToFile(file)) { clearDirty(); } } catch (IOException ioe) { JOptionPane.showMessageDialog(this, "Unable to save file: " + ioe, "Unable to save file", JOptionPane.ERROR_MESSAGE); } return true; } public Action getOpenAction() { return openTemplateAction; } private final AbstractAction openTemplateAction = new AbstractAction("Apply Template...") { private static final long serialVersionUID = 2450459627280385426L; public void actionPerformed(ActionEvent ae) { doApplyTemplate(); } }; public Action getSaveAction() { return saveAsAction; } public Action getSaveAsAction() { return saveAsAction; } private final AbstractAction saveAsAction = new AbstractAction("Save Template As...") { private static final long serialVersionUID = 2424923366448459342L; public void actionPerformed(ActionEvent ae) { doSaveAs(); } }; public Action getImportAction() { return importAlignmentAction; } protected AbstractAction importAlignmentAction = new AbstractAction("Import Alignment...") { private static final long serialVersionUID = 3217702096314745005L; public void actionPerformed(java.awt.event.ActionEvent ae) { doImport(); } }; public Action getImportTraitsAction() { return importTraitsAction; } protected AbstractAction importTraitsAction = new AbstractAction("Import Traits...") { private static final long serialVersionUID = 3217702096314745005L; public void actionPerformed(java.awt.event.ActionEvent ae) { doImportTraits(); } }; public Action getExportAction() { return generateAction; } protected AbstractAction generateAction = new AbstractAction("Generate BEAST File...", gearIcon) { private static final long serialVersionUID = -5329102618630268783L; public void actionPerformed(java.awt.event.ActionEvent ae) { doGenerate(); } }; }
package team1100.season2010.robot; import team1100.season2010.robot.DashboardPacker; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.camera.AxisCameraException; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.NIVisionException; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.AnalogChannel; import edu.wpi.first.wpilibj.Watchdog; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot1100 extends IterativeRobot { //Counts how many periodic cycles have passed. int m_count; AnalogChannel pot_1 = new AnalogChannel(7); Joystick joystick_1; Joystick joystick_2; //RobotDrive drive; final int POT_RANGE = 10; final int DIGPORT = 4; int prev_pot; final double JOYSTICK_DEADBAND = .1; final int MAX_POT_VALUE = 268; final int MIN_POT_VALUE = 256; double prev_speed; double setpt_speed; final double SPEED_ADJUST = .1; Jaguar front_right_motor; Jaguar front_left_motor; Jaguar back_right_motor; Jaguar back_left_motor; Jaguar chain_rotation_motor; //Jaguar testMotor = new Jaguar(3); //PIDController pid; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { //Sets periodic call rate to 10 milisecond intervals, i.e. 100Hz. this.setPeriod(0.01); System.out.print("ROBOT STARTUP"); //drive = new RobotDrive(1,5); //drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, false); //drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, false); //pid = new PIDController(.1,.001,0, pot_1, testMotor); //pid.setInputRange(0, 1024); } /** * This function is called when the robot enters autonomous mode. */ public void autonomousInit() { m_count = 0; System.out.println("Autonomous Init"); } /** * This function is called periodically (100Hz) during autonomous */ public void autonomousPeriodic() { m_count++; //System.out.println("AutoCount: " + m_count); //Runs periodically at 100Hz { } //Runs periodically at 50Hz. if (m_count % 2 == 0) { } //Runs periodically at 25Hz. if (m_count % 4 == 0) { } //Runs periodically at 20Hz. if (m_count % 5 == 0) { DashboardPacker.updateDashboard(); System.out.println("Packet Sent (Auto)"); } //Runs periodically at 10Hz. if (m_count % 10 == 0) { } //Runs periodically at 5Hz. if (m_count % 20 == 0) { } } /** * This function is called when the robot enters teleop mode. */ public void teleopInit() { m_count = 0; System.out.println("TeleOp Initialized."); joystick_1 = new Joystick(1); joystick_2 = new Joystick(2); front_right_motor = new Jaguar(DIGPORT,5); front_left_motor = new Jaguar(DIGPORT,1); //back_right_motor = new Jaguar(DIGPORT,3); //back_left_motor = new Jaguar(DIGPORT,4); ///chain_rotation_motor = new Jaguar(DIGPORT,5); prev_pot = pot_1.getAverageValue(); } /** * This function is called periodically (100Hz) during operator control */ public void teleopPeriodic() { m_count++; //System.out.println("TeleOp: "+ m_count); //drive.tankDrive(joystick_1, joystick_2); //Runs periodically at 100Hz { } //Runs periodically at 50Hz. if (m_count % 2 == 0) { } //Runs periodically at 25Hz. if (m_count % 4 == 0) { } //Runs periodically at 20Hz. if (m_count % 5 == 0) { Watchdog.getInstance().feed(); DashboardPacker.updateDashboard(); //System.out.println("Packet Sent (TO)"); //System.out.println("1X: " + joystick_1.getX() + " 1Y: " + joystick_1.getY()); //System.out.println("2X: " + joystick_2.getX() + " 2Y: " + joystick_2.getY()); //System.out.println ("Joystick 1" + " X = " + joystick_1.getX() + "Y = " + joystick_1.getY() + "Z = " + joystick_1.getZ()); //System.out.println ("Joystick 2" + "X = " + joystick_2.getX() + "Y = " + joystick_2.getY() + "Z = " + joystick_2.getZ() ); //System.out.println("1Z: " + joystick_1.getZ()); //System.out.println("2z: " + joystick_2.getZ()); //testMotor.set(joystick_2.getY()); /* System.out.println("POT:" + pot_1.getValue()); if(joystick_1.getMagnitude()>=.5) { System.out.println("\tAngle: " + joystick_1.getDirectionDegrees()); if(pot_1.getValue() <= 1024.0 / 360.0 * (joystick_1.getDirectionDegrees() + 180) - POT_RANGE) testMotor.set(-1); else if(pot_1.getValue() >= 1024.0 / 360.0 * (joystick_1.getDirectionDegrees() + 180) + POT_RANGE) testMotor.set(1); else testMotor.set(0); } else testMotor.set(0);*/ //System.out.println("X val: " + joystick_1.getX()/2); //System.out.println("\tPot v: " + pot_1.getValue()); //System.out.println("\t\tPot.getPid()" + pot_1.pidGet()); } //Runs periodically at 10Hz. if (m_count % 10 == 0) { } //Runs periodically at 5Hz. if (m_count % 20 == 0) { //joystick_2 = throttle joystick for driving wheels if(joystick_2.getY()>=JOYSTICK_DEADBAND || joystick_2.getY()<=-1 * JOYSTICK_DEADBAND) { setpt_speed = joystick_2.getY(); if(setpt_speed>prev_speed) { front_right_motor.set(prev_speed+SPEED_ADJUST); front_left_motor.set(prev_speed+SPEED_ADJUST); //back_right_motor.set(prev_speed+SPEED_ADJUST); //back_left_motor.set(prev_speed+SPEED_ADJUST); } else { front_right_motor.set(prev_speed-SPEED_ADJUST); front_left_motor.set(prev_speed-SPEED_ADJUST); //back_right_motor.set(prev_speed-SPEED_ADJUST); //back_left_motor.set(prev_speed-SPEED_ADJUST); } prev_speed=(front_right_motor.get()+front_left_motor.get())/2; //+back_right_motor.get()+back_left_motor.get())/4; } else { if(SPEED_ADJUST<=Math.abs(prev_speed)) { front_right_motor.set(0); front_left_motor.set(0); //back_right_motor.set(0); //back_left_motor.set(0); } else if(0<prev_speed) { front_right_motor.set(prev_speed+SPEED_ADJUST); front_left_motor.set(prev_speed+SPEED_ADJUST); //back_right_motor.set(prev_speed+SPEED_ADJUST); //back_left_motor.set(prev_speed+SPEED_ADJUST); } else { front_right_motor.set(prev_speed-SPEED_ADJUST); front_left_motor.set(prev_speed-SPEED_ADJUST); //back_right_motor.set(prev_speed-SPEED_ADJUST); //back_left_motor.set(prev_speed-SPEED_ADJUST); } prev_speed=(front_right_motor.get()+front_left_motor.get())/2; //+back_right_motor.get()+back_left_motor.get())/4; } prev_pot = pot_1.getAverageValue(); } } public void motorSpeedAdjustment(double setpt_speed, double prev_speed) { if(setpt_speed>prev_speed) for(double i=prev_speed; i<setpt_speed; i += SPEED_ADJUST) { front_right_motor.set(i); front_left_motor.set(i); back_right_motor.set(i); back_left_motor.set(i); } else for(double i= prev_speed; i>setpt_speed; i -= SPEED_ADJUST) { front_right_motor.set(i); front_left_motor.set(i); back_right_motor.set(i); back_left_motor.set(i); } } /** * This function is called when the robot enters disabled mode. */ public void disabledInit() { m_count = 0; // System.out.println("Disabled Init 1100 version"); } /** * This function is called periodically (100Hz) during disabled mode. */ public void disabledPeriodic() { m_count++; // System.out.println("Mcount =" + m_count); //Runs periodically at 100Hz { } //Runs periodically at 50Hz. if (m_count % 2 == 0) { } //Runs periodically at 25Hz. if (m_count % 4 == 0) { } //Runs periodically at 20Hz. if (m_count % 5 == 0) { DashboardPacker.updateDashboard(); System.out.println("Packet Sent (D)"); } //Runs periodically at 10Hz. if (m_count % 10 == 0) { } //Runs periodically at 5Hz. if (m_count % 20 == 0) { } //Runs periodically at 1/5 Hz. if (m_count % 500 == 0) { // System.out.println("Hello, world! in Disable mode..."); } } }
package com.brettonw.db; import org.junit.Test; public class Keys_Test { @Test public void test () { // because coverage reports Keys as untested... new Keys (); } }
package guitests; import javafx.scene.input.KeyCode; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testfx.api.FxToolkit; import ui.TestController; import ui.UI; import util.GitHubURL; import util.PlatformEx; import util.events.IssueCreatedEvent; import util.events.IssueSelectedEvent; import util.events.LabelCreatedEvent; import util.events.MilestoneCreatedEvent; import util.events.testevents.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeoutException; public class ChromeDriverTest extends UITest { private final List<String> urlsNavigated = new ArrayList<>(); private final List<String> scriptsExecuted = new ArrayList<>(); private final List<String> keysSentToBrowser = new ArrayList<>(); private boolean hasJumpedToComment = false; private final NavigateToPageEventHandler navToPageHandler = e -> urlsNavigated.add(e.url); private final ExecuteScriptEventHandler execScriptHandler = e -> scriptsExecuted.add(e.script); private final JumpToNewCommentBoxEventHandler jumpCommentHandler = e -> hasJumpedToComment = true; @Before public void prepare() { urlsNavigated.clear(); scriptsExecuted.clear(); keysSentToBrowser.clear(); hasJumpedToComment = false; UI.events.registerEvent(navToPageHandler); UI.events.registerEvent(execScriptHandler); UI.events.registerEvent(jumpCommentHandler); PlatformEx.runAndWait(()->TestController.getUI().getPanelControl().getPanel(0).requestFocus()); } @After public void tearDown() { UI.events.unregisterEvent(navToPageHandler); UI.events.unregisterEvent(execScriptHandler); UI.events.unregisterEvent(jumpCommentHandler); } @Override public void setup() throws TimeoutException { FxToolkit.setupApplication( TestUI.class, "--test=true", "--bypasslogin=true", "--testchromedriver=true"); } /** * Performs the specified action and waits for a specific response to occur. * * @param expected expected response to the action. * @param action the action to take to trigger the desired response. * @param responses aggregator of responses to the action. */ private <T> void actAndAwaitResponse(T expected, Runnable action, Collection<T> responses) { responses.clear(); action.run(); awaitCondition(() -> responses.contains(expected)); } private void actAndAwaitNavToPage(String expectedUrl, Runnable action) { actAndAwaitResponse(expectedUrl, action, urlsNavigated); } @Test public void navigateToPage_selectIssue() { actAndAwaitNavToPage( GitHubURL.getPathForIssue("dummy/dummy", 1), () -> UI.events.triggerEvent(new IssueSelectedEvent("dummy/dummy", 1, 0, false)) ); } @Test public void navigateToPage_createIssue() { actAndAwaitNavToPage( GitHubURL.getPathForNewIssue("dummy/dummy"), () -> UI.events.triggerEvent(new IssueCreatedEvent()) ); } @Test public void navigateToPage_createLabel() { actAndAwaitNavToPage( GitHubURL.getPathForNewLabel("dummy/dummy"), () -> UI.events.triggerEvent(new LabelCreatedEvent()) ); actAndAwaitNavToPage( GitHubURL.getPathForNewLabel("dummy/dummy"), () -> push(KeyCode.G).push(KeyCode.L) ); } @Test public void navigateToPage_createMilestone() { actAndAwaitNavToPage( GitHubURL.getPathForNewMilestone("dummy/dummy"), () -> UI.events.triggerEvent(new MilestoneCreatedEvent()) ); } @Test public void navigateToPage_showDocs() { actAndAwaitNavToPage( GitHubURL.DOCS_PAGE, () -> push(KeyCode.F1) ); actAndAwaitNavToPage( GitHubURL.DOCS_PAGE, () -> { push(KeyCode.G); push(KeyCode.H); } ); actAndAwaitNavToPage( GitHubURL.DOCS_PAGE, () -> { clickOn("View"); clickOn("Documentation"); } ); } @Test public void navigateToPage_issues() { // go to issues page actAndAwaitNavToPage( GitHubURL.getPathForAllIssues("dummy/dummy"), () -> push(KeyCode.G).push(KeyCode.I) ); } @Test public void navigateToPage_milestones() { actAndAwaitNavToPage( GitHubURL.getPathForMilestones("dummy/dummy"), () -> push(KeyCode.G).push(KeyCode.M) ); } @Test public void navigateToPage_pullRequests() { actAndAwaitNavToPage( GitHubURL.getPathForPullRequests("dummy/dummy"), () -> push(KeyCode.G).push(KeyCode.P) ); } @Test public void navigateToPage_developers() { actAndAwaitNavToPage( GitHubURL.getPathForContributors("dummy/dummy"), () -> push(KeyCode.G).push(KeyCode.D) ); } @Test public void navigateToPage_keyboardShortcuts() { actAndAwaitNavToPage( GitHubURL.KEYBOARD_SHORTCUTS_PAGE, () -> push(KeyCode.G).push(KeyCode.K) ); } private void actAndAwaitExecScript(String expectedScript, Runnable action) { actAndAwaitResponse(expectedScript, action, scriptsExecuted); } @Test public void executeScripts_scrollToTop() { actAndAwaitExecScript( "window.scrollTo(0, 0)", () -> push(KeyCode.I) ); } @Test public void executeScripts_scrollToBottom() { actAndAwaitExecScript( "window.scrollTo(0, document.body.scrollHeight)", () -> push(KeyCode.N) ); } @Test public void executeScripts_scrollUp() { actAndAwaitExecScript( "window.scrollBy(0, -100)", () -> push(KeyCode.J) ); } @Test public void executeScripts_scrollDown() { actAndAwaitExecScript( "window.scrollBy(0, 100)", () -> push(KeyCode.K) ); } @Test public void jumpToNewCommentBox() { // jump to comments push(KeyCode.R, 1); awaitCondition(() -> hasJumpedToComment); } }
package prm4j.util; import java.util.Collection; import java.util.Iterator; import java.util.Map; import prm4j.api.Alphabet; import prm4j.api.MatchHandler; import prm4j.api.Parameter; import prm4j.api.Symbol0; import prm4j.api.Symbol1; import prm4j.api.Symbol2; import prm4j.api.fsm.FSM; import prm4j.api.fsm.FSMState; import prm4j.indexing.realtime.AwareMatchHandler; import prm4j.indexing.realtime.AwareMatchHandler.AwareMatchHandler1; import prm4j.indexing.realtime.AwareMatchHandler.AwareMatchHandler2; public abstract class FSMDefinitions { @SuppressWarnings("rawtypes") public static class FSM_unsafeMapIterator { public final Alphabet alphabet = new Alphabet(); public final Parameter<Map> m = alphabet.createParameter("m", Map.class); public final Parameter<Collection> c = alphabet.createParameter("c", Collection.class); public final Parameter<Iterator> i = alphabet.createParameter("i", Iterator.class); public final Symbol2<Map, Collection> createColl = alphabet.createSymbol2("createColl", m, c); public final Symbol2<Collection, Iterator> createIter = alphabet.createSymbol2("createIter", c, i); public final Symbol1<Map> updateMap = alphabet.createSymbol1("updateMap", m); public final Symbol1<Iterator> useIter = alphabet.createSymbol1("useIter", i); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState s3 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(MatchHandler.NO_OP); public FSM_unsafeMapIterator() { initial.addTransition(createColl, s1); s1.addTransition(updateMap, s1); s1.addTransition(createIter, s2); s2.addTransition(useIter, s2); s2.addTransition(updateMap, s3); s3.addTransition(updateMap, s3); s3.addTransition(useIter, error); } } /** * Twos <b>A</b>s trigger the error state, a <b>B</b> will end in a dead state. */ public static abstract class AbstractFSM_2symbols3states { public final Alphabet alphabet = new Alphabet(); public final Symbol0 a = alphabet.createSymbol0("a"); public final Symbol0 b = alphabet.createSymbol0("b"); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(MatchHandler.NO_OP); public AbstractFSM_2symbols3states() { setupTransitions(); } public abstract void setupTransitions(); } /** * Watches for <code>e1e3</code> traces. Taken from * "Efficient Formalism-Independent Monitoring of Parametric Properties". */ public static abstract class FSM_e1e3 { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final Symbol1<String> e2 = alphabet.createSymbol1("e2", p2); public final Symbol2<String, String> e3 = alphabet.createSymbol2("e3", p1, p2); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(MatchHandler.NO_OP); public FSM_e1e3() { initial.addTransition(e1, s1); initial.addTransition(e2, initial); // self-loop s1.addTransition(e3, error); } } public static class FSM_a_a_a { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final AwareMatchHandler1<String> matchHandler = AwareMatchHandler.create(p1); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_a_a_a() { initial.addTransition(e1, s1); s1.addTransition(e1, s2); s2.addTransition(e1, error); } } public static class FSM_a_ab_a_b { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Symbol1<String> e1 = alphabet.createSymbol1("e1", p1); public final Symbol2<String, String> e2 = alphabet.createSymbol2("e2", p1, p2); public final Symbol1<String> e3 = alphabet.createSymbol1("e3", p2); public final AwareMatchHandler2<String, String> matchHandler = AwareMatchHandler.create(p1, p2); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState s3 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_a_ab_a_b() { initial.addTransition(e1, s1); s1.addTransition(e2, s2); s2.addTransition(e1, s3); s3.addTransition(e3, error); } } public static class FSM_ab_bc_c { public final Alphabet alphabet = new Alphabet(); public final Parameter<String> p1 = alphabet.createParameter("p1", String.class); public final Parameter<String> p2 = alphabet.createParameter("p2", String.class); public final Parameter<String> p3 = alphabet.createParameter("p3", String.class); public final Symbol2<String, String> e1 = alphabet.createSymbol2("e2", p1, p2); public final Symbol2<String, String> e2 = alphabet.createSymbol2("e2", p2, p3); public final Symbol1<String> e3 = alphabet.createSymbol1("e3", p3); public final AwareMatchHandler2<String, String> matchHandler = AwareMatchHandler.create(p1, p3); public final FSM fsm = new FSM(alphabet); public final FSMState initial = fsm.createInitialState(); public final FSMState s1 = fsm.createState(); public final FSMState s2 = fsm.createState(); public final FSMState error = fsm.createAcceptingState(matchHandler); public FSM_ab_bc_c() { initial.addTransition(e1, s1); s1.addTransition(e2, s2); s2.addTransition(e3, error); } } }
package product; import operators.base.RefreshOperator; import operators.configurations.BuildConfigurationSetPageOperator; import operators.products.ProductPageOperator; import operators.projects.ProjectPageOperator; import operators.products.ImportPageOperator; import org.junit.Assert; import org.junit.Test; import ui.UITest; public class ImportProductTest extends UITest { @Test public void jdg() { importConfig("jdg-infinispan", "8.3", "JDG Infinispan", "http://git.app.eng.bos.redhat.com/infinispan/infinispan.git", "JDG_7.0.0.ER9-2", "mvn clean deploy -DskipTests=true -Pdistribution"); } @Test public void jdgConsole() { importConfig("jdg-management-console", "8.3", "JDG Management Console", "http://git.engineering.redhat.com/git/users/pkralik/jdg-management-console.git", "JDG_7.0.0.GA_pnc_wa", "export NVM_NODEJS_ORG_MIRROR=http://rcm-guest.app.eng.bos.redhat.com/rcm-guest/staging/jboss-dg/node\n\n" + "mvn clean deploy " + "-DnpmDownloadRoot=http://rcm-guest.app.eng.bos.redhat.com/rcm-guest/staging/jboss-dg/node/npm/ " + "-DnodeDownloadRoot=http://rcm-guest.app.eng.bos.redhat.com/rcm-guest/staging/jboss-dg/node/ " + "-DnpmRegistryURL=http://jboss-prod-docker.app.eng.bos.redhat.com:49165"); } @Test public void sso() { importConfig("keycloak", "2.0", "RH SSO", "http://git.engineering.redhat.com/git/users/pkralik/keycloak-prod.git", "2.0.0.Final-redhat-1-pnc", "mvn clean deploy -Pdistribution " + "-pl '!adapters/oidc/jetty/jetty9.1' -pl '!adapters/oidc/jetty/jetty9.2' -pl '!adapters/oidc/spring-boot' -pl '!adapters/oidc/spring-security' -pl '!adapters/oidc/tomcat/tomcat6' -pl '!adapters/oidc/tomcat/tomcat7' -pl '!adapters/oidc/tomcat/tomcat8' -pl '!adapters/oidc/wildfly/wf8-subsystem' -pl '!adapters/saml/jetty/jetty8.1' -pl '!adapters/saml/jetty/jetty9.1' -pl '!adapters/saml/jetty/jetty9.2' -pl '!adapters/saml/tomcat/tomcat6' -pl '!adapters/saml/tomcat/tomcat7' -pl '!adapters/saml/tomcat/tomcat8' -pl '!distribution/adapters/as7-eap6-adapter/as7-adapter-zip' -pl '!distribution/adapters/tomcat6-adapter-zip' -pl '!distribution/adapters/tomcat7-adapter-zip' -pl '!distribution/adapters/tomcat8-adapter-zip' -pl '!distribution/adapters/jetty81-adapter-zip' -pl '!distribution/adapters/jetty91-adapter-zip' -pl '!distribution/adapters/jetty92-adapter-zip' -pl '!distribution/adapters/wf8-adapter/wf8-adapter-zip' -pl '!distribution/adapters/wf8-adapter/wf8-modules' -pl '!distribution/api-docs-dist' -pl '!distribution/feature-packs/adapter-feature-pack' -pl '!distribution/demo-dist' -pl '!distribution/examples-dist' -pl '!distribution/proxy-dist' -pl '!distribution/saml-adapters/as7-eap6-adapter/as7-adapter-zip' -pl '!distribution/saml-adapters/tomcat6-adapter-zip' -pl '!distribution/saml-adapters/tomcat7-adapter-zip' -pl '!distribution/saml-adapters/tomcat8-adapter-zip' -pl '!distribution/saml-adapters/jetty81-adapter-zip' -pl '!distribution/saml-adapters/jetty92-adapter-zip' -pl '!distribution/src-dist' -pl '!model/mongo' -pl '!proxy/proxy-server' -pl '!proxy/launcher/' -pl '!testsuite/proxy' -pl '!testsuite/tomcat6' -pl '!testsuite//tomcat7' -pl '!testsuite/tomcat8' -pl '!testsuite/jetty/jetty81' -pl '!testsuite/jetty/jetty91' -pl '!testsuite/jetty/jetty92' -pl '!testsuite/stress'"); } @Test public void eap() { importConfig("eap7", "7.0", "JBoss EAP 7", "http://git.engineering.redhat.com/git/users/pkralik/wildfly.git", "7.0.1.GA-redhat-2-pnc", "mvn clean deploy -Prelease"); } private void importConfig(String... param) { new ProductPageOperator(param[0]).createProduct(param[2] + " product"); new RefreshOperator().refresh(); new ProjectPageOperator(param[0]).createProject(param[2] + " project"); new RefreshOperator().refresh(); ImportPageOperator product = new ImportPageOperator(param[0]); product.importProduct(param[1], param[3], param[4], param[5]); product.buildConfigurationSet(); String buildName = product.getConfigSetName(); BuildConfigurationSetPageOperator buildGroupConfig = new BuildConfigurationSetPageOperator(buildName); buildGroupConfig.menuBuildGroups(); Assert.assertTrue(buildGroupConfig.waitUntilLink(buildName).isDisplayed()); } }
package solid.stream; import java.util.Iterator; public class Empty<T> extends Stream<T> { public static <T> Empty<T> empty() { //noinspection unchecked return EMPTY; } private static final Empty EMPTY = new Empty(); private static Iterator iterator = new ReadOnlyIterator() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new UnsupportedOperationException(); } }; @Override public Iterator<T> iterator() { //noinspection unchecked return iterator; } }
package edu.dynamic.dynamiz.UI; import java.awt.*; import java.awt.event.*; import javax.swing.*; import edu.dynamic.dynamiz.UI.DisplayerInterface; /** * * @author XYLau * */ public class UI extends JPanel implements ActionListener { protected JTextField inputScreen; protected JTextArea displayScreen; private final static String newline = "\n"; public static Displayer disp = new Displayer(); public UI() { super(new GridBagLayout()); displayScreen = new JTextArea(40, 100); displayScreen.setEditable(false); JScrollPane scrollPane = new JScrollPane(displayScreen); inputScreen = new JTextField(20); inputScreen.addActionListener(this); // Add Components to this panel. GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; add(scrollPane, c); c.fill = GridBagConstraints.HORIZONTAL; add(inputScreen, c); } /** * Event Handler for each event, where event refers to the entry of a single * command into the Screen interface */ public void actionPerformed(ActionEvent evt) { String text = inputScreen.getText(); /* * To be added once controller is completed (ZX) Feedback feedback = * controller.executeCommand(text); */ display(disp.displayPrompt()); // for testing purposes (XY) displayln(text); // TODO: Replace with line by line string feedback once Displayer is completed (WY) // Additional Feature: Retained Last-Entered Command inputScreen.selectAll(); // Make sure the new text is visible, even if there // was a selection in the text area. displayScreen.setCaretPosition(displayScreen.getDocument().getLength()); } /** * Displays a string onto the Screen with newline * @param text */ public void displayln(String text) { displayScreen.append(text + newline); } /** * Displays a string onto the Screen without a newline * * @param text */ public void display(String text) { displayScreen.append(text); } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event dispatch thread. */ private static void Screen() { // Create and set up the window. JFrame frame = new JFrame("Dynamiz"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add contents to the window. frame.add(new UI()); displayScreen(frame); } /** * Displays the screen * * @param frame */ private static void displayScreen(JFrame frame) { frame.pack(); frame.setVisible(true); } public static void main(String[] args) { // Schedule a job for the event dispatch thread: // creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { Screen(); } }); } }
/*Alessandro Corbetta * corbisoft@gmail.com * Conv Encoder simulator 1/02/11 * */ package encMechanicsConv; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class LaunchB2 { private Joint myFacadeClass; private Gui myGui; private double transProb; public static void main(String[] args) { String path = JOptionPane.showInputDialog("Please insert a correctly formatted trellis file:","CodifEsempioLibro540.txt"); String bscTransProbab = JOptionPane.showInputDialog("Please insert the transition probability of the BSC", "0.1"); new LaunchB2(path,bscTransProbab); } private LaunchB2(String path, String bscTransProbab){ this.myFacadeClass = new Joint(path,Double.parseDouble(bscTransProbab)); this.transProb = Double.parseDouble(bscTransProbab); this.myGui = new Gui(this.myFacadeClass.linkToTrellisPanel(),this.myFacadeClass.linkToTrellisShow()); } class Gui extends JFrame{ private JPanel trellisFr; private Container wordPn; private JPanel trellisShow; private Container globCont; private Container centerCont; private JPanel rightCont; public Gui(JPanel trellisFr, JPanel trellisShow){ super("[Convol Enc - Trans - Dec] Alessandro Corbetta"); //this.setLayout(new FlowLayout()); this.trellisFr = trellisFr; this.trellisShow = trellisShow; this.globCont = this.getContentPane(); this.globCont.setLayout(new FlowLayout()); this.centerCont = new Container(); this.centerCont.setLayout(new FlowLayout()); this.centerCont.add(this.trellisFr); this.wordPn = new InputForm(); this.centerCont.add(wordPn); this.rightCont = new JPanel(); this.rightCont.add(trellisShow); this.centerCont.add(this.rightCont); this.globCont.add(this.centerCont); this.pack(); this.setVisible(true); } private class InputForm extends Container{ private JLabel inputLabel; private JTextField inputField; private JButton encodeAndSend; private JLabel encodedLabel; private JTextField encodedField; private JLabel TransProp; private JLabel arrivedLabel; private JTextField arrivedField; private JLabel decodedLabel; private JTextField decodedField; private JLabel decProp; private JButton buttonAbout; private InputForm(){ super(); this.setLayout(new GridLayout(0,1)); this.inputLabel = new JLabel("Insert information sequence [ 0,1 array]: "); this.add(this.inputLabel); this.inputField = new JTextField(20); this.add(this.inputField); this.encodeAndSend = new JButton("Encode and Send!"); this.encodeAndSend.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { myFacadeClass.resetEnc(); trellisShow = myFacadeClass.linkToTrellisShow(); //JOptionPane.showMessageDialog(null, Integer.toString(trellisShow.getComponentCount())); rightCont.remove(0); rightCont.add(trellisShow); trellisShow.repaint(); InterexchangeSeq seq = myFacadeClass.CodeTransfDecode4Win(inputField.getText()); encodedField.setText(seq.getCodeS()); arrivedField.setText(seq.getTrasS()); decodedField.setText(seq.getDecS()); TransProp.setText("Transmission errors: " + Integer.toString(seq.getCodingErr()) + " over " + Integer.toString(myFacadeClass.getTotCodedBit()) + " simbols"); decProp.setText("Decoding errors: " + Integer.toString(seq.getBitErr()) + " over " + Integer.toString(myFacadeClass.getTotalInfobit())+ " bit"); // TODO Auto-generated method stub } }); this.add(this.encodeAndSend); this.encodedLabel = new JLabel("Encoded String:"); this.add(this.encodedLabel); this.encodedField = new JTextField(40); this.add(this.encodedField); JLabel BSCprop = new JLabel("Transmission through BSC with transition probability p=" + Double.toString(transProb),JLabel.RIGHT); BSCprop.setFont(new Font("sansserif", Font.ITALIC, 12)); this.add(BSCprop); this.arrivedLabel = new JLabel("Received String:"); this.add(this.arrivedLabel); this.arrivedField = new JTextField(40); this.add(this.arrivedField); TransProp = new JLabel("Transmission errors: N/A",JLabel.RIGHT); TransProp.setFont(new Font("sansserif", Font.ITALIC, 12)); this.add(TransProp); this.decodedLabel = new JLabel("Decoded String:"); this.add(this.decodedLabel); this.decodedField = new JTextField(20); this.add(this.decodedField); decProp = new JLabel("Decoding errors: N/A",JLabel.RIGHT); decProp.setFont(new Font("sansserif", Font.ITALIC, 12)); this.add(decProp); this.buttonAbout = new JButton("About..."); this.buttonAbout.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub JOptionPane.showMessageDialog(null, "A small program to simulate convolutional encoding...\n" + "Homework for the exam: Coding Theory and Structure of Convolutional Codes\n" + "at Politecnico di Torino (2011)\n" + "1,5K+ codelines and 6 days of hard work\n" + "\n" + "by Alessandro Corbetta\n" + " alessandro.corbetta@hotmail.com\n" + " 1/02/2011\n" + "\n" + "\n" + "P.S. try other trellis files!!\n " + "(the program is not protected against bad filling of the trellis file - follow the template!)\n\n" + "" + "peace", "About..", JOptionPane.INFORMATION_MESSAGE ); } }); this.add(buttonAbout); } } } }
import managed_dll.*; import managed_dll.properties.*; import managed_dll.first.*; import managed_dll.first.second.*; import managed_dll.exceptions.*; import mono.embeddinator.*; import static org.junit.Assert.*; import org.junit.*; public class Tests { private static boolean doublesAreEqual(double value1, double value2) { return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2); } @Test public void testProperties() { assertFalse(Platform.getIsWindows()); Platform.setExitCode(255); assertEquals(Platform.getExitCode(), 255); assertEquals(Query.getUniversalAnswer(), 42); Query query = new Query(); assertTrue(query.getIsGood()); assertFalse(query.getIsBad()); assertEquals(query.getAnswer(), 42); query.setAnswer(911); assertEquals(query.getAnswer(), 911); assertFalse(query.getIsSecret()); query.setSecret(1); assertTrue(query.getIsSecret()); } @Test public void testNamespaces() { ClassWithoutNamespace nonamespace = new ClassWithoutNamespace(); assertEquals(nonamespace.toString(), "ClassWithoutNamespace"); ClassWithSingleNamespace singlenamespace = new ClassWithSingleNamespace(); assertEquals(singlenamespace.toString(), "First.ClassWithSingleNamespace"); ClassWithNestedNamespace nestednamespaces = new ClassWithNestedNamespace(); assertEquals(nestednamespaces.toString(), "First.Second.ClassWithNestedNamespace"); managed_dll.first.second.third.ClassWithNestedNamespace nestednamespaces2 = new managed_dll.first.second.third.ClassWithNestedNamespace(); assertEquals(nestednamespaces2.toString(), "First.Second.Third.ClassWithNestedNamespace"); } @Test public void testExceptions() { Throwable e = null; try { Throwers throwers = new Throwers(); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); e = null; try { ThrowInStaticCtor static_thrower = new ThrowInStaticCtor(); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); try { Super sup1 = new Super(false); } catch(Exception ex) { fail(); } e = null; try { Super sup2 = new Super(true); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); } @Test static long UCHAR_MAX = (long)(Math.pow(2, Byte.SIZE) - 1); static long USHRT_MAX = (long)(Math.pow(2, Short.SIZE) - 1); static long UINT_MAX = (long)(Math.pow(2, Integer.SIZE) - 1); static long ULONG_MAX = (long)(Math.pow(2, Long.SIZE) - 1); public void testTypes() { assertEquals(Byte.MIN_VALUE, Type_SByte.getMin()); assertEquals(Byte.MAX_VALUE, Type_SByte.getMax()); assertEquals(Short.MIN_VALUE, Type_Int16.getMin()); assertEquals(Short.MAX_VALUE, Type_Int16.getMax()); assertEquals(Integer.MIN_VALUE, Type_Int32.getMin()); assertEquals(Integer.MAX_VALUE, Type_Int32.getMax()); assertEquals(Long.MIN_VALUE, Type_Int64.getMin()); assertEquals(Long.MAX_VALUE, Type_Int64.getMax()); assertEquals(0, Type_Byte.getMin().longValue()); assertEquals(UCHAR_MAX, Type_Byte.getMax().longValue()); assertEquals(0, Type_UInt16.getMin().longValue()); assertEquals(USHRT_MAX, Type_UInt16.getMax().longValue()); assertEquals(0, Type_UInt32.getMin().longValue()); assertEquals(UINT_MAX, Type_UInt32.getMax().longValue()); assertEquals(0, Type_UInt64.getMin().longValue()); // TODO: Use BigDecimal for unsigned 64-bit integer types. //assertEquals(ULONG_MAX, Type_UInt64.getMax().longValue()); doublesAreEqual(-Float.MAX_VALUE, Type_Single.getMin()); doublesAreEqual(Float.MAX_VALUE, Type_Single.getMax()); doublesAreEqual(-Double.MAX_VALUE, Type_Double.getMin()); doublesAreEqual(Double.MAX_VALUE, Type_Double.getMax()); assertEquals(Character.MIN_VALUE, Type_Char.getMin()); assertEquals(Character.MAX_VALUE, Type_Char.getMax()); assertEquals(0, Type_Char.getZero()); } }
import managed_dll.*; import managed_dll.properties.*; import managed_dll.first.*; import managed_dll.first.second.*; import managed_dll.exceptions.*; import managed_dll.constructors.*; import managed_dll.enums.*; import mono.embeddinator.*; import static org.junit.Assert.*; import org.junit.*; public class Tests { private static boolean doublesAreEqual(double value1, double value2) { return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2); } @Test public void testProperties() { assertFalse(Platform.getIsWindows()); Platform.setExitCode(255); assertEquals(Platform.getExitCode(), 255); assertEquals(Query.getUniversalAnswer(), 42); Query query = new Query(); assertTrue(query.getIsGood()); assertFalse(query.getIsBad()); assertEquals(query.getAnswer(), 42); query.setAnswer(911); assertEquals(query.getAnswer(), 911); assertFalse(query.getIsSecret()); query.setSecret(1); assertTrue(query.getIsSecret()); } @Test public void testNamespaces() { ClassWithoutNamespace nonamespace = new ClassWithoutNamespace(); assertEquals(nonamespace.toString(), "ClassWithoutNamespace"); ClassWithSingleNamespace singlenamespace = new ClassWithSingleNamespace(); assertEquals(singlenamespace.toString(), "First.ClassWithSingleNamespace"); ClassWithNestedNamespace nestednamespaces = new ClassWithNestedNamespace(); assertEquals(nestednamespaces.toString(), "First.Second.ClassWithNestedNamespace"); managed_dll.first.second.third.ClassWithNestedNamespace nestednamespaces2 = new managed_dll.first.second.third.ClassWithNestedNamespace(); assertEquals(nestednamespaces2.toString(), "First.Second.Third.ClassWithNestedNamespace"); } @Test public void testExceptions() { Throwable e = null; try { Throwers throwers = new Throwers(); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); e = null; try { ThrowInStaticCtor static_thrower = new ThrowInStaticCtor(); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); try { Super sup1 = new Super(false); } catch(Exception ex) { fail(); } e = null; try { Super sup2 = new Super(true); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); } @Test public void testConstructors() { Unique unique = new Unique(); assertEquals(1, unique.getId()); Unique unique_init_id = new Unique(911); assertEquals(911, unique_init_id.getId()); SuperUnique super_unique_default_init = new SuperUnique(); assertEquals(411, super_unique_default_init.getId()); Implicit implicit = new Implicit(); assertEquals("OK", implicit.getTestResult()); AllTypeCode all1 = new AllTypeCode(true, (char)USHRT_MAX, "Mono"); assertTrue(all1.getTestResult()); AllTypeCode all2 = new AllTypeCode(Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Long.MAX_VALUE); assertTrue(all2.getTestResult()); // TODO: Use BigDecimal for unsigned 64-bit integer types. //AllTypeCode all3 = new AllTypeCode(new UnsignedByte(UCHAR_MAX), new UnsignedShort(USHRT_MAX), // new UnsignedInt(UINT_MAX), new UnsignedLong(ULONG_MAX)); //assertTrue(all3.getTestResult()); AllTypeCode all4 = new AllTypeCode(Float.MAX_VALUE, Double.MAX_VALUE); assertTrue(all4.getTestResult()); } @Test public void testEnums() { Ref<IntEnum> i = new Ref<IntEnum>(IntEnum.Min); Ref<ShortEnum> s = new Ref<ShortEnum>(ShortEnum.Min); ByteFlags f = Enumer.test(ByteEnum.Max, i, s); assertEquals(0x22, f.getValue()); assertEquals(IntEnum.Max, i.get()); assertEquals(ShortEnum.Max, s.get()); f = Enumer.test(ByteEnum.Zero, i, s); assertEquals(IntEnum.Min, i.get()); assertEquals(ShortEnum.Min, s.get()); } static long UCHAR_MAX = (long)(Math.pow(2, Byte.SIZE) - 1); static long USHRT_MAX = (long)(Math.pow(2, Short.SIZE) - 1); static long UINT_MAX = (long)(Math.pow(2, Integer.SIZE) - 1); static long ULONG_MAX = (long)(Math.pow(2, Long.SIZE) - 1); @Test public void testTypes() { assertEquals(Byte.MIN_VALUE, Type_SByte.getMin()); assertEquals(Byte.MAX_VALUE, Type_SByte.getMax()); assertEquals(Short.MIN_VALUE, Type_Int16.getMin()); assertEquals(Short.MAX_VALUE, Type_Int16.getMax()); assertEquals(Integer.MIN_VALUE, Type_Int32.getMin()); assertEquals(Integer.MAX_VALUE, Type_Int32.getMax()); assertEquals(Long.MIN_VALUE, Type_Int64.getMin()); assertEquals(Long.MAX_VALUE, Type_Int64.getMax()); assertEquals(0, Type_Byte.getMin().longValue()); assertEquals(UCHAR_MAX, Type_Byte.getMax().longValue()); assertEquals(0, Type_UInt16.getMin().longValue()); assertEquals(USHRT_MAX, Type_UInt16.getMax().longValue()); assertEquals(0, Type_UInt32.getMin().longValue()); assertEquals(UINT_MAX, Type_UInt32.getMax().longValue()); assertEquals(0, Type_UInt64.getMin().longValue()); // TODO: Use BigDecimal for unsigned 64-bit integer types. //assertEquals(ULONG_MAX, Type_UInt64.getMax().longValue()); doublesAreEqual(-Float.MAX_VALUE, Type_Single.getMin()); doublesAreEqual(Float.MAX_VALUE, Type_Single.getMax()); doublesAreEqual(-Double.MAX_VALUE, Type_Double.getMin()); doublesAreEqual(Double.MAX_VALUE, Type_Double.getMax()); assertEquals(Character.MIN_VALUE, Type_Char.getMin()); assertEquals(Character.MAX_VALUE, Type_Char.getMax()); assertEquals(0, Type_Char.getZero()); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyc.stages; import java.util.*; import static wyil.util.ErrorMessages.*; import wybs.lang.SyntacticElement; import wybs.lang.SyntaxError; import wybs.util.ResolveError; import wyc.builder.*; import wyc.lang.*; import wyc.lang.Stmt.*; import wyil.util.*; import wyil.lang.*; /** * <p> * Responsible for expanding all types and constraints for a given module(s), as * well as generating appropriate WYIL code. For example, consider these two * declarations: * </p> * * <pre> * define Point2D as {int x, int y} * define Point3D as {int x, int y, int z} * define Point as Point2D | Point3D * </pre> * <p> * This stage will expand the type <code>Point</code> to give its full * structural definition. That is, * <code>{int x,int y}|{int x,int y,int z}</code>. * </p> * <p> * Type expansion must also account for any constraints on the types in * question. For example: * </p> * * <pre> * define nat as int where $ >= 0 * define natlist as [nat] * </pre> * <p> * The type <code>natlist</code> expands to <code>[int]</code>, whilst its * constraint is expanded to <code>all {x in $ | x >= 0}</code>. * </p> * <p> * <b>NOTE:</b> As the above description hints, this class currently has two * distinct responsibilities. Therefore, at some point in the future, it will be * split into two separate stages. * </p> * * @author David J. Pearce * */ public final class CodeGeneration { private final Whiley2WyilBuilder builder; private final GlobalResolver resolver; private GlobalGenerator globalGenerator; private LocalGenerator localGenerator; private Stack<Scope> scopes = new Stack<Scope>(); private WhileyFile.FunctionOrMethod currentFunDecl; // The shadow set is used to (efficiently) aid the correct generation of // runtime checks for post conditions. The key issue is that a post // condition may refer to parameters of the method. However, if those // parameters are modified during the method, then we must store their // original value on entry for use in the post-condition runtime check. // These stored values are called "shadows". private final HashMap<String, Integer> shadows = new HashMap<String, Integer>(); public CodeGeneration(Whiley2WyilBuilder builder, GlobalGenerator generator, GlobalResolver resolver) { this.builder = builder; this.resolver = resolver; this.globalGenerator = generator; } public WyilFile generate(WhileyFile wf) { ArrayList<WyilFile.Declaration> declarations = new ArrayList<WyilFile.Declaration>(); for (WhileyFile.Declaration d : wf.declarations) { try { if (d instanceof WhileyFile.TypeDef) { declarations.add(generate((WhileyFile.TypeDef) d)); } else if (d instanceof WhileyFile.Constant) { declarations.add(generate((WhileyFile.Constant) d)); } else if (d instanceof WhileyFile.FunctionOrMethod) { declarations.add(generate((WhileyFile.FunctionOrMethod) d)); } } catch (SyntaxError se) { throw se; } catch (Throwable ex) { WhileyFile.internalFailure(ex.getMessage(), localGenerator.context(), d, ex); } } return new WyilFile(wf.module, wf.filename, declarations); } private WyilFile.ConstantDeclaration generate(WhileyFile.Constant cd) { // TODO: this the point where were should an evaluator return new WyilFile.ConstantDeclaration(cd.modifiers, cd.name, cd.resolvedValue); } private WyilFile.TypeDeclaration generate(WhileyFile.TypeDef td) throws Exception { Block constraint = null; if(td.constraint != null) { localGenerator = new LocalGenerator(globalGenerator,td); NameID nid = new NameID(td.file().module,td.name); constraint = globalGenerator.generate(nid); } return new WyilFile.TypeDeclaration(td.modifiers, td.name(), td.resolvedType.raw(), constraint); } private WyilFile.MethodDeclaration generate(WhileyFile.FunctionOrMethod fd) throws Exception { Type.FunctionOrMethod ftype = fd.resolvedType().raw(); localGenerator = new LocalGenerator(globalGenerator,fd); LocalGenerator.Environment environment = new LocalGenerator.Environment(); // method return type int paramIndex = 0; int nparams = fd.parameters.size(); // Generate pre-condition Block precondition = null; for (WhileyFile.Parameter p : fd.parameters) { // First, generate and inline any constraints associated with the // type. // Now, map the parameter to its index Block constraint = globalGenerator.generate(p.type, p); if (constraint != null) { if (precondition == null) { precondition = new Block(nparams); } constraint = shiftBlockExceptionZero(nparams, paramIndex, constraint); precondition.append(constraint); } environment.allocate(ftype.params().get(paramIndex++),p.name()); } // Resolve pre- and post-condition if(fd.precondition != null) { if(precondition == null) { precondition = new Block(nparams); } localGenerator.generateAssertion("precondition not satisfied", fd.precondition, false, environment, precondition); } // Generate post-condition Block postcondition = globalGenerator.generate(fd.ret,fd); if (fd.postcondition != null) { LocalGenerator.Environment postEnv = new LocalGenerator.Environment(); postEnv.allocate(fd.resolvedType().ret().raw(),"$"); paramIndex = 0; for (WhileyFile.Parameter p : fd.parameters) { postEnv.allocate(ftype.params().get(paramIndex),p.name()); paramIndex++; } postcondition = new Block(postEnv.size()); localGenerator.generateAssertion("postcondition not satisfied", fd.postcondition, false, postEnv, postcondition); } // Generate body currentFunDecl = fd; Block body = new Block(fd.parameters.size()); for (Stmt s : fd.statements) { generate(s, environment, body); } currentFunDecl = null; // The following is sneaky. It guarantees that every method ends in a // return. For methods that actually need a value, this is either // removed as dead-code or remains and will cause an error. body.append(Code.Return(),attributes(fd)); List<WyilFile.Case> ncases = new ArrayList<WyilFile.Case>(); ArrayList<String> locals = new ArrayList<String>(); // TODO: resolve this? // for(int i=0;i!=environment.size();++i) { // locals.add(null); // for(Map.Entry<String,Integer> e : environment.entrySet()) { // locals.set(e.getValue(),e.getKey()); ncases.add(new WyilFile.Case(body,precondition,postcondition,locals)); if(fd instanceof WhileyFile.Function) { WhileyFile.Function f = (WhileyFile.Function) fd; return new WyilFile.MethodDeclaration(fd.modifiers, fd.name(), f.resolvedType.raw(), ncases); } else { WhileyFile.Method md = (WhileyFile.Method) fd; return new WyilFile.MethodDeclaration(fd.modifiers, fd.name(), md.resolvedType.raw(), ncases); } } private void generate(Stmt stmt, LocalGenerator.Environment environment, Block codes) { try { if (stmt instanceof Assign) { generate((Assign) stmt, environment, codes); } else if (stmt instanceof Assert) { generate((Assert) stmt, environment, codes); } else if (stmt instanceof Assume) { generate((Assume) stmt, environment, codes); } else if (stmt instanceof Return) { generate((Return) stmt, environment, codes); } else if (stmt instanceof Debug) { generate((Debug) stmt, environment, codes); } else if (stmt instanceof IfElse) { generate((IfElse) stmt, environment, codes); } else if (stmt instanceof Switch) { generate((Switch) stmt, environment, codes); } else if (stmt instanceof TryCatch) { generate((TryCatch) stmt, environment, codes); } else if (stmt instanceof Break) { generate((Break) stmt, environment, codes); } else if (stmt instanceof Throw) { generate((Throw) stmt, environment, codes); } else if (stmt instanceof While) { generate((While) stmt, environment, codes); } else if (stmt instanceof DoWhile) { generate((DoWhile) stmt, environment, codes); } else if (stmt instanceof ForAll) { generate((ForAll) stmt, environment, codes); } else if (stmt instanceof Expr.MethodCall) { localGenerator.generate((Expr.MethodCall) stmt,environment,codes); } else if (stmt instanceof Expr.FunctionCall) { localGenerator.generate((Expr.FunctionCall) stmt,environment,codes); } else if (stmt instanceof Expr.IndirectMethodCall) { localGenerator.generate((Expr.IndirectMethodCall) stmt,environment,codes); } else if (stmt instanceof Expr.IndirectFunctionCall) { localGenerator.generate((Expr.IndirectFunctionCall) stmt,environment,codes); } else if (stmt instanceof Expr.New) { localGenerator.generate((Expr.New) stmt, environment, codes); } else if (stmt instanceof Skip) { generate((Skip) stmt, environment, codes); } else { // should be dead-code WhileyFile.internalFailure("unknown statement: " + stmt.getClass().getName(), localGenerator.context(), stmt); } } catch (ResolveError rex) { WhileyFile.syntaxError(rex.getMessage(), localGenerator.context(), stmt, rex); } catch (SyntaxError sex) { throw sex; } catch (Exception ex) { WhileyFile.internalFailure(ex.getMessage(), localGenerator.context(), stmt, ex); } } private void generate(Assign s, LocalGenerator.Environment environment, Block codes) { if(s.lhs instanceof Expr.AssignedVariable) { Expr.AssignedVariable v = (Expr.AssignedVariable) s.lhs; int operand = localGenerator.generate(s.rhs, environment, codes); int target = environment.get(v.var); codes.append(Code.Assign(v.result().raw(), target, operand),attributes(s)); }else if(s.lhs instanceof Expr.RationalLVal) { Expr.RationalLVal tg = (Expr.RationalLVal) s.lhs; Expr.AssignedVariable lv = (Expr.AssignedVariable) tg.numerator; Expr.AssignedVariable rv = (Expr.AssignedVariable) tg.denominator; if (environment.get(lv.var) == null) { environment.allocate(Type.T_INT,lv.var); } if (environment.get(rv.var) == null) { environment.allocate(Type.T_INT,rv.var); } int operand = localGenerator.generate(s.rhs, environment, codes); codes.append(Code.UnArithOp(s.rhs.result() .raw(), environment.get(lv.var), operand, Code.UnArithKind.NUMERATOR), attributes(s)); codes.append(Code.UnArithOp(s.rhs.result().raw(), environment.get(rv.var), operand, Code.UnArithKind.DENOMINATOR), attributes(s)); } else if(s.lhs instanceof Expr.Tuple) { Expr.Tuple tg = (Expr.Tuple) s.lhs; ArrayList<Expr> fields = new ArrayList<Expr>(tg.fields); for (int i = 0; i != fields.size(); ++i) { Expr e = fields.get(i); if (!(e instanceof Expr.AssignedVariable)) { WhileyFile.syntaxError(errorMessage(INVALID_TUPLE_LVAL), localGenerator.context(), e); } Expr.AssignedVariable v = (Expr.AssignedVariable) e; if (environment.get(v.var) == null) { environment.allocate(v.afterType.raw(), v.var); } } int operand = localGenerator.generate(s.rhs, environment, codes); for (int i = 0; i != fields.size(); ++i) { Expr.AssignedVariable v = (Expr.AssignedVariable) fields.get(i); codes.append(Code.TupleLoad((Type.EffectiveTuple) s.rhs .result().raw(), environment.get(v.var), operand, i), attributes(s)); } } else if (s.lhs instanceof Expr.IndexOf || s.lhs instanceof Expr.RecordAccess) { ArrayList<String> fields = new ArrayList<String>(); ArrayList<Integer> operands = new ArrayList<Integer>(); Expr.AssignedVariable lhs = extractLVal(s.lhs, fields, operands, environment, codes); if (environment.get(lhs.var) == null) { WhileyFile.syntaxError("unknown variable", localGenerator.context(), lhs); } int target = environment.get(lhs.var); int rhsRegister = localGenerator .generate(s.rhs, environment, codes); codes.append(Code.Update(lhs.type.raw(), target, rhsRegister, operands, lhs.afterType.raw(), fields), attributes(s)); } else { WhileyFile.syntaxError("invalid assignment", localGenerator.context(), s); } } private Expr.AssignedVariable extractLVal(Expr e, ArrayList<String> fields, ArrayList<Integer> operands, LocalGenerator.Environment environment, Block codes) { if (e instanceof Expr.AssignedVariable) { Expr.AssignedVariable v = (Expr.AssignedVariable) e; return v; } else if (e instanceof Expr.Dereference) { Expr.Dereference pa = (Expr.Dereference) e; return extractLVal(pa.src, fields, operands, environment, codes); } else if (e instanceof Expr.IndexOf) { Expr.IndexOf la = (Expr.IndexOf) e; int operand = localGenerator.generate(la.index, environment, codes); Expr.AssignedVariable l = extractLVal(la.src, fields, operands, environment, codes); operands.add(operand); return l; } else if (e instanceof Expr.RecordAccess) { Expr.RecordAccess ra = (Expr.RecordAccess) e; Expr.AssignedVariable r = extractLVal(ra.src, fields, operands, environment, codes); fields.add(ra.name); return r; } else { WhileyFile.syntaxError(errorMessage(INVALID_LVAL_EXPRESSION), localGenerator.context(), e); return null; // dead code } } private void generate(Assert s, LocalGenerator.Environment environment, Block codes) { localGenerator.generateAssertion("assertion failed", s.expr, false, environment, codes); } private void generate(Assume s, LocalGenerator.Environment environment, Block codes) { localGenerator.generateAssertion("assumption failed", s.expr, true, environment, codes); } private void generate(Return s, LocalGenerator.Environment environment, Block codes) { if (s.expr != null) { int operand = localGenerator.generate(s.expr, environment, codes); // Here, we don't put the type propagated for the return expression. // Instead, we use the declared return type of this function. This // has the effect of forcing an implicit coercion between the // actual value being returned and its required type. Type ret = currentFunDecl.resolvedType().raw().ret(); codes.append(Code.Return(ret, operand), attributes(s)); } else { codes.append(Code.Return(), attributes(s)); } } private void generate(Skip s, LocalGenerator.Environment environment, Block codes) { codes.append(Code.Nop, attributes(s)); } private void generate(Debug s, LocalGenerator.Environment environment, Block codes) { int operand = localGenerator.generate(s.expr, environment, codes); codes.append(Code.Debug(operand), attributes(s)); } private void generate(IfElse s, LocalGenerator.Environment environment, Block codes) { String falseLab = Block.freshLabel(); String exitLab = s.falseBranch.isEmpty() ? falseLab : Block .freshLabel(); localGenerator.generateCondition(falseLab, invert(s.condition), environment, codes); for (Stmt st : s.trueBranch) { generate(st, environment, codes); } if (!s.falseBranch.isEmpty()) { codes.append(Code.Goto(exitLab)); codes.append(Code.Label(falseLab)); for (Stmt st : s.falseBranch) { generate(st, environment, codes); } } codes.append(Code.Label(exitLab)); } private void generate(Throw s, LocalGenerator.Environment environment, Block codes) { int operand = localGenerator.generate(s.expr, environment, codes); codes.append(Code.Throw(s.expr.result().raw(), operand), s.attributes()); } private void generate(Break s, LocalGenerator.Environment environment, Block codes) { BreakScope scope = findEnclosingScope(BreakScope.class); if (scope == null) { WhileyFile.syntaxError(errorMessage(BREAK_OUTSIDE_LOOP), localGenerator.context(), s); } codes.append(Code.Goto(scope.label)); } private void generate(Switch s, LocalGenerator.Environment environment, Block codes) throws Exception { String exitLab = Block.freshLabel(); int operand = localGenerator.generate(s.expr, environment, codes); String defaultTarget = exitLab; HashSet<Constant> values = new HashSet(); ArrayList<Pair<Constant, String>> cases = new ArrayList(); int start = codes.size(); for (Stmt.Case c : s.cases) { if (c.expr.isEmpty()) { // A case with an empty match represents the default label. We // must check that we have not already seen a case with an empty // match (otherwise, we'd have two default labels ;) if (defaultTarget != exitLab) { WhileyFile.syntaxError( errorMessage(DUPLICATE_DEFAULT_LABEL), localGenerator.context(), c); } else { defaultTarget = Block.freshLabel(); codes.append(Code.Label(defaultTarget), attributes(c)); for (Stmt st : c.stmts) { generate(st, environment, codes); } codes.append(Code.Goto(exitLab), attributes(c)); } } else if (defaultTarget == exitLab) { String target = Block.freshLabel(); codes.append(Code.Label(target), attributes(c)); // Case statements in Whiley may have multiple matching constant // values. Therefore, we iterate each matching value and // construct a mapping from that to a label indicating the start // of the case body. for (Constant constant : c.constants) { // Check whether this case constant has already been used as // a case constant elsewhere. If so, then report an error. if (values.contains(constant)) { WhileyFile.syntaxError( errorMessage(DUPLICATE_CASE_LABEL), localGenerator.context(), c); } cases.add(new Pair(constant, target)); values.add(constant); } for (Stmt st : c.stmts) { generate(st, environment, codes); } codes.append(Code.Goto(exitLab), attributes(c)); } else { // This represents the case where we have another non-default // case after the default case. Such code cannot be executed, // and is therefore reported as an error. WhileyFile.syntaxError(errorMessage(UNREACHABLE_CODE), localGenerator.context(), c); } } codes.insert(start, Code.Switch(s.expr.result().raw(), operand, defaultTarget, cases), attributes(s)); codes.append(Code.Label(exitLab), attributes(s)); } private void generate(TryCatch s, LocalGenerator.Environment environment, Block codes) throws Exception { int exceptionRegister = allocate(environment); String exitLab = Block.freshLabel(); Block cblk = new Block(environment.size()); for (Stmt st : s.body) { cblk.append(generate(st, environment)); } cblk.append(Code.Goto(exitLab),attributes(s)); String endLab = null; ArrayList<Pair<Type,String>> catches = new ArrayList<Pair<Type,String>>(); for(Stmt.Catch c : s.catches) { Code.Label lab; if(endLab == null) { endLab = Block.freshLabel(); lab = Code.TryEnd(endLab); } else { lab = Code.Label(Block.freshLabel()); } Type pt = c.type.raw(); // TODO: deal with exception type constraints catches.add(new Pair<Type,String>(pt,lab.label)); cblk.append(lab, attributes(c)); environment.put(c.variable, exceptionRegister); for (Stmt st : c.stmts) { cblk.append(generate(st, environment)); } cblk.append(Code.Goto(exitLab),attributes(c)); } Block blk = new Block(environment.size()); blk.append(Code.TryCatch(exceptionRegister,endLab,catches),attributes(s)); blk.append(cblk); blk.append(Code.Label(exitLab), attributes(s)); return blk; } private void generate(While s, LocalGenerator.Environment environment, Block codes) { String label = Block.freshLabel(); if (s.invariant != null) { localGenerator.generateAssertion( "loop invariant not satisfied on entry", s.invariant, false, environment, codes); } codes.append(Code.Loop(label, Collections.EMPTY_SET), attributes(s)); localGenerator.generateCondition(label, invert(s.condition), environment, codes); scopes.push(new BreakScope(label)); for (Stmt st : s.body) { generate(st, environment, codes); } scopes.pop(); // break if (s.invariant != null) { localGenerator.generateAssertion("loop invariant not restored", s.invariant, false, environment, codes); } codes.append(Code.LoopEnd(label)); } private void generate(DoWhile s, LocalGenerator.Environment environment, Block codes) { String label = Block.freshLabel(); if (s.invariant != null) { localGenerator.generateAssertion( "loop invariant not satisfied on entry", s.invariant, false, environment, codes); } codes.append(Code.Loop(label, Collections.EMPTY_SET), attributes(s)); scopes.push(new BreakScope(label)); for (Stmt st : s.body) { generate(st, environment, codes); } scopes.pop(); // break if (s.invariant != null) { localGenerator.generateAssertion( "loop invariant not restored", s.invariant, false, environment, codes); } localGenerator.generateCondition(label, invert(s.condition), environment, codes); codes.append(Code.LoopEnd(label)); } private void generate(ForAll s, LocalGenerator.Environment environment, Block codes) { String label = Block.freshLabel(); if (s.invariant != null) { String invariantLabel = Block.freshLabel(); localGenerator.generateAssertion( "loop invariant not satisfied on entry", s.invariant, false, environment, codes); } int sourceRegister = localGenerator.generate(s.source, environment, codes); // FIXME: loss of nominal information Type.EffectiveCollection rawSrcType = s.srcType.raw(); if (s.variables.size() > 1) { // this is the destructuring case // FIXME: support destructuring of lists and sets if (!(rawSrcType instanceof Type.EffectiveMap)) { WhileyFile.syntaxError(errorMessage(INVALID_MAP_EXPRESSION), localGenerator.context(), s.source); } Type.EffectiveMap dict = (Type.EffectiveMap) rawSrcType; Type.Tuple element = (Type.Tuple) Type.Tuple(dict.key(), dict.value()); int indexRegister = environment.allocate(element); codes.append(Code .ForAll((Type.EffectiveMap) rawSrcType, sourceRegister, indexRegister, Collections.EMPTY_SET, label), attributes(s)); for (int i = 0; i < s.variables.size(); ++i) { String var = s.variables.get(i); int varReg = environment.allocate(element.element(i), var); codes.append(Code.TupleLoad(element, varReg, indexRegister, i), attributes(s)); } } else { // easy case. int indexRegister = environment.allocate(rawSrcType.element(), s.variables.get(0)); codes.append(Code.ForAll(s.srcType.raw(), sourceRegister, indexRegister, Collections.EMPTY_SET, label), attributes(s)); } // FIXME: add a continue scope scopes.push(new BreakScope(label)); for (Stmt st : s.body) { generate(st, environment, codes); } scopes.pop(); // break if (s.invariant != null) { localGenerator.generateAssertion("loop invariant not restored", s.invariant, false, environment, codes); } codes.append(Code.LoopEnd(label), attributes(s)); } private static Expr invert(Expr e) { if (e instanceof Expr.BinOp) { Expr.BinOp bop = (Expr.BinOp) e; Expr.BinOp nbop = null; switch (bop.op) { case AND: nbop = new Expr.BinOp(Expr.BOp.OR, invert(bop.lhs), invert(bop.rhs), attributes(e)); break; case OR: nbop = new Expr.BinOp(Expr.BOp.AND, invert(bop.lhs), invert(bop.rhs), attributes(e)); break; case EQ: nbop = new Expr.BinOp(Expr.BOp.NEQ, bop.lhs, bop.rhs, attributes(e)); break; case NEQ: nbop = new Expr.BinOp(Expr.BOp.EQ, bop.lhs, bop.rhs, attributes(e)); break; case LT: nbop = new Expr.BinOp(Expr.BOp.GTEQ, bop.lhs, bop.rhs, attributes(e)); break; case LTEQ: nbop = new Expr.BinOp(Expr.BOp.GT, bop.lhs, bop.rhs, attributes(e)); break; case GT: nbop = new Expr.BinOp(Expr.BOp.LTEQ, bop.lhs, bop.rhs, attributes(e)); break; case GTEQ: nbop = new Expr.BinOp(Expr.BOp.LT, bop.lhs, bop.rhs, attributes(e)); break; } if(nbop != null) { nbop.srcType = bop.srcType; return nbop; } } else if (e instanceof Expr.UnOp) { Expr.UnOp uop = (Expr.UnOp) e; switch (uop.op) { case NOT: return uop.mhs; } } Expr.UnOp r = new Expr.UnOp(Expr.UOp.NOT, e); r.type = Nominal.T_BOOL; return r; } /** * The shiftBlock method takes a block and shifts every slot a given amount * to the right. The number of inputs remains the same. This method is used * * @param amount * @param blk * @return */ private static Block shiftBlockExceptionZero(int amount, int zeroDest, Block blk) { HashMap<Integer,Integer> binding = new HashMap<Integer,Integer>(); for(int i=1;i!=blk.numSlots();++i) { binding.put(i,i+amount); } binding.put(0, zeroDest); Block nblock = new Block(blk.numInputs()); for(Block.Entry e : blk) { Code code = e.code.remap(binding); nblock.append(code,e.attributes()); } return nblock.relabel(); } /** * The attributes method extracts those attributes of relevance to wyil, and * discards those which are only used for the wyc front end. * * @param elem * @return */ private static Collection<Attribute> attributes(SyntacticElement elem) { ArrayList<Attribute> attrs = new ArrayList<Attribute>(); attrs.add(elem.attribute(Attribute.Source.class)); return attrs; } private <T extends Scope> T findEnclosingScope(Class<T> c) { for(int i=scopes.size()-1;i>=0;--i) { Scope s = scopes.get(i); if(c.isInstance(s)) { return (T) s; } } return null; } private abstract class Scope {} private class BreakScope extends Scope { public String label; public BreakScope(String l) { label = l; } } private class ContinueScope extends Scope { public String label; public ContinueScope(String l) { label = l; } } }
class E004_ArrayMethodDeclarations { String oneParameter(int one)[] { return null; } String[] oneParameter2(int one)[] { return null; } String twoParameters(int one, String two)[] { return null; } String[] twoParameters2(int one, String two)[] { return null; } String varArgs(String... two)[] { return null; } String[] varArgs2(String... two)[] { return null; } String varArgsArray(String[]... two)[] { return null; } String[] varArgsArray2(String[]... two)[] { return null; } String simpleGenericParameter(int one, String two, java.util.List<String> three)[] { return null; } String[] simpleGenericParameter2(int one, String two, java.util.List<String> three)[] { return null; } public String publicMethod(int one, String two, java.util.List<String> three, boolean isPublic)[] { return null; } public String[] publicMethod2(int one, String two, java.util.List<String> three, boolean isPublic)[] { return null; } String typeArgumentExtends(java.util.List<? extends Number> list)[] { return null; } String[] typeArgumentExtends2(java.util.List<? extends Number> list)[] { return null; } String typeArgumentSuper(Class<? super Number> clazz)[] { return null; } String[] typeArgumentSuper2(Class<? super Number> clazz)[] { return null; } <R> R returnTypeParameter()[] { return null; } <R> R[] returnTypeParameter2()[] { return null; } <T, R> R returnAndParameterTypeParameter(T arg)[] { return null; } <T, R> R[] returnAndParameterTypeParameter2(T arg)[] { return null; } String throwsMethod()[] throws Exception { return null; } String[] throwsMethod2()[] throws Exception { return null; } <T, R, E extends Exception> R throwsReturnsAndParameter(T arg)[] throws E, NullPointerException { return null; } <T, R, E extends Exception> R[] throwsReturnsAndParameter2(T arg)[] throws E, NullPointerException { return null; } }
package org.apache.xerces.dom; import java.io.*; import java.util.Enumeration; import java.util.Vector; import org.w3c.dom.*; /** * Elements represent most of the "markup" and structure of the * document. They contain both the data for the element itself * (element name and attributes), and any contained nodes, including * document text (as children). * <P> * Elements may have Attributes associated with them; the API for this is * defined in Node, but the function is implemented here. In general, XML * applications should retrive Attributes as Nodes, since they may contain * entity references and hence be a fairly complex sub-tree. HTML users will * be dealing with simple string values, and convenience methods are provided * to work in terms of Strings. * <P> * @version * @since PR-DOM-Level-1-19980818. */ public class ElementImpl extends NodeImpl implements Element { // Constants /** Serialization version. */ static final long serialVersionUID = -7202454486126245907L; // Data /** Attributes. */ protected NamedNodeMapImpl attributes; /** DOM2: Namespace URI. */ protected String namespaceURI; /** DOM2: Prefix */ protected String prefix; /** DOM2: localName. */ protected String localName; /** DOM2: support. * Is this element created with ownerDocument.createElementNS()? */ protected boolean enableNamespace = false; // Constructors /** Factory constructor. */ public ElementImpl(DocumentImpl ownerDoc, String name) { super(ownerDoc, name, null); //setupDefaultAttributes(ownerDoc); this.localName = name; syncData = true; } /** * DOM2: Constructor for Namespace implementation. */ protected ElementImpl(DocumentImpl ownerDocument, String namespaceURI, String qualifiedName) { this.ownerDocument = ownerDocument; this.namespaceURI = namespaceURI; this.name = qualifiedName; int index = qualifiedName.indexOf(':'); if (index < 0) { this.prefix = null; this.localName = qualifiedName; } else { this.prefix = qualifiedName.substring(0, index); this.localName = qualifiedName.substring(index+1); } this.enableNamespace = true; syncData = true; } // <init>(DocumentImpl,String,short,boolean,String) // Node methods /** * A short integer indicating what type of node this is. The named * constants for this value are defined in the org.w3c.dom.Node interface. */ public short getNodeType() { return Node.ELEMENT_NODE; } /** Returns the node value. */ public String getNodeValue() { return null; } /** * Elements never have a nodeValue. * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR), unconditionally. */ public void setNodeValue(String value) throws DOMException { throw new DOMExceptionImpl(DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } /** * Retrieve all the Attributes as a set. Note that this API is inherited * from Node rather than specified on Element; in fact only Elements will * ever have Attributes, but they want to allow folks to "blindly" operate * on the tree as a set of Nodes. */ public NamedNodeMap getAttributes() { if (syncData) { synchronizeData(); } return attributes; } // getAttributes():NamedNodeMap /** * Return a duplicate copy of this Element. Note that its children * will not be copied unless the "deep" flag is true, but Attributes * are <i>always</i> replicated. * * @see org.w3c.dom.Node#cloneNode(boolean) */ public Node cloneNode(boolean deep) { if (syncData) { synchronizeData(); } ElementImpl newnode = (ElementImpl) super.cloneNode(deep); // Replicate NamedNodeMap rather than sharing it. newnode.attributes = attributes.cloneMap(); return newnode; } // cloneNode(boolean):Node // Element methods /** * Look up a single Attribute by name. Returns the Attribute's * string value, or an empty string (NOT null!) to indicate that the * name did not map to a currently defined attribute. * <p> * Note: Attributes may contain complex node trees. This method * returns the "flattened" string obtained from Attribute.getValue(). * If you need the structure information, see getAttributeNode(). */ public String getAttribute(String name) { if (syncData) { synchronizeData(); } Attr attr = (Attr)(attributes.getNamedItem(name)); return (attr == null) ? "" : attr.getValue(); } // getAttribute(String):String /** * Look up a single Attribute by name. Returns the Attribute Node, * so its complete child tree is available. This could be important in * XML, where the string rendering may not be sufficient information. * <p> * If no matching attribute is available, returns null. */ public Attr getAttributeNode(String name) { if (syncData) { synchronizeData(); } return (Attr)attributes.getNamedItem(name); } // getAttributeNode(String):Attr /** * Returns a NodeList of all descendent nodes (children, * grandchildren, and so on) which are Elements and which have the * specified tag name. * <p> * Note: NodeList is a "live" view of the DOM. Its contents will * change as the DOM changes, and alterations made to the NodeList * will be reflected in the DOM. * * @param tagname The type of element to gather. To obtain a list of * all elements no matter what their names, use the wild-card tag * name "*". * * @see DeepNodeListImpl */ public NodeList getElementsByTagName(String tagname) { return new DeepNodeListImpl(this,tagname); } //DOM2: Namespace methods. /** * Introduced in DOM Level 2. <p> * * The namespace URI of this node, or null if it is unspecified.<p> * * This is not a computed value that is the result of a namespace lookup based on * an examination of the namespace declarations in scope. It is merely the * namespace URI given at creation time.<p> * * For nodes created with a DOM Level 1 method, such as createElement * from the Document interface, this is null. * @since WD-DOM-Level-2-19990923 */ public String getNamespaceURI() { if (syncData) { synchronizeData(); } return namespaceURI; } /** * Introduced in DOM Level 2. <p> * * The namespace prefix of this node, or null if it is unspecified. <p> * * For nodes created with a DOM Level 1 method, such as createElement * from the Document interface, this is null. <p> * * @since WD-DOM-Level-2-19990923 */ public String getPrefix() { if (syncData) { synchronizeData(); } return prefix; } /** * Introduced in DOM Level 2. <p> * * Note that setting this attribute changes the nodeName attribute, which holds the * qualified name, as well as the tagName and name attributes of the Element * and Attr interfaces, when applicable.<p> * * @throws INVALID_CHARACTER_ERR Raised if the specified * prefix contains an invalid character. * * @since WD-DOM-Level-2-19990923 */ public void setPrefix(String prefix) throws DOMException { if (syncData) { synchronizeData(); } if (ownerDocument.errorChecking && !DocumentImpl.isXMLName(prefix)) { throw new DOMExceptionImpl(DOMException.INVALID_CHARACTER_ERR, "INVALID_CHARACTER_ERR"); } this.prefix = prefix; this.name = prefix+":"+localName; } /** * Introduced in DOM Level 2. <p> * * Returns the local part of the qualified name of this node. * @since WD-DOM-Level-2-19990923 */ public String getLocalName() { if (syncData) { synchronizeData(); } return localName; } /** * Returns the name of the Element. Note that Element.nodeName() is * defined to also return the tag name. * <p> * This is case-preserving in XML. HTML should uppercasify it on the * way in. */ public String getTagName() { if (syncData) { synchronizeData(); } return name; } /** * In "normal form" (as read from a source file), there will never be two * Text children in succession. But DOM users may create successive Text * nodes in the course of manipulating the document. Normalize walks the * sub-tree and merges adjacent Texts, as if the DOM had been written out * and read back in again. This simplifies implementation of higher-level * functions that may want to assume that the document is in standard form. * <p> * To normalize a Document, normalize its top-level Element child. * <p> * As of PR-DOM-Level-1-19980818, CDATA -- despite being a subclass of * Text -- is considered "markup" and will _not_ be merged either with * normal Text or with other CDATASections. */ public void normalize() { Node kid, next; for (kid = getFirstChild(); kid != null; kid = next) { next = kid.getNextSibling(); // If kid and next are both Text nodes (but _not_ CDATASection, // which is a subclass of Text), they can be merged. if (next != null && kid.getNodeType() == Node.TEXT_NODE && next.getNodeType() == Node.TEXT_NODE) { ((Text)kid).appendData(next.getNodeValue()); removeChild(next); next = kid; // Don't advance; there might be another. } // Otherwise it might be an Element, which is handled recursively else if (kid.getNodeType() == Node.ELEMENT_NODE) { ((Element)kid).normalize(); } } // changed() will have occurred when the removeChild() was done, // so does not have to be reissued. } // normalize() /** * Remove the named attribute from this Element. If the removed * Attribute has a default value, it is immediately replaced thereby. * <P> * The default logic is actually implemented in NamedNodeMapImpl. * PR-DOM-Level-1-19980818 doesn't fully address the DTD, so some * of this behavior is likely to change in future versions. ????? * <P> * Note that this call "succeeds" even if no attribute by this name * existed -- unlike removeAttributeNode, which will throw a not-found * exception in that case. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is * readonly. */ public void removeAttribute(String name) { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } AttrImpl att = (AttrImpl) attributes.getNamedItem(name); // Remove it (and let the NamedNodeMap recreate the default, if any) if (att != null) { att.owned = false; attributes.removeNamedItem(name); } } // removeAttribute(String) /** * Remove the specified attribute/value pair. If the removed * Attribute has a default value, it is immediately replaced. * <p> * NOTE: Specifically removes THIS NODE -- not the node with this * name, nor the node with these contents. If the specific Attribute * object passed in is not stored in this Element, we throw a * DOMException. If you really want to remove an attribute by name, * use removeAttribute(). * * @return the Attribute object that was removed. * @throws DOMException(NOT_FOUND_ERR) if oldattr is not an attribute of * this Element. * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is * readonly. */ public Attr removeAttributeNode(Attr oldAttr) throws DOMException { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } AttrImpl found = (AttrImpl) attributes.getNamedItem(oldAttr.getName()); // If it is in fact the right object, remove it (and let the // NamedNodeMap recreate the default, if any) if (found == oldAttr) { attributes.removeNamedItem(oldAttr.getName()); found.owned = false; return found; } throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR, "NOT_FOUND_ERR"); } // removeAttributeNode(Attr):Attr /** * Add a new name/value pair, or replace the value of the existing * attribute having that name. * * Note: this method supports only the simplest kind of Attribute, * one whose value is a string contained in a single Text node. * If you want to assert a more complex value (which XML permits, * though HTML doesn't), see setAttributeNode(). * * The attribute is created with specified=true, meaning it's an * explicit value rather than inherited from the DTD as a default. * Again, setAttributeNode can be used to achieve other results. * * @throws DOMException(INVALID_NAME_ERR) if the name is not acceptable. * (Attribute factory will do that test for us.) * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if the node is * readonly. */ public void setAttribute(String name, String value) { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } AttrImpl newAttr = (AttrImpl)getOwnerDocument().createAttribute(name); newAttr.setNodeValue(value); attributes.setNamedItem(newAttr); newAttr.owned = true; // Set true AFTER adding -- or move in????? } // setAttribute(String,String) /** * Add a new attribute/value pair, or replace the value of the * existing attribute with that name. * <P> * This method allows you to add an Attribute that has already been * constructed, and hence avoids the limitations of the simple * setAttribute() call. It can handle attribute values that have * arbitrarily complex tree structure -- in particular, those which * had entity references mixed into their text. * * @throws DOMException(INUSE_ATTRIBUTE_ERR) if the Attribute object * has already been assigned to another Element. */ public Attr setAttributeNode(Attr newAttr) throws DOMException { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } if (ownerDocument.errorChecking && !(newAttr instanceof AttrImpl)) { throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR, "WRONG_DOCUMENT_ERR"); } AttrImpl na = (AttrImpl) newAttr; AttrImpl oldAttr = (AttrImpl) attributes.getNamedItem(newAttr.getName()); // This will throw INUSE if necessary attributes.setNamedItem(na); na.owned = true; // Must set after adding ... or within? return oldAttr; } // setAttributeNode(Attr):Attr // DOM2: Namespace methods /** * Introduced in DOM Level 2. <p> * * Retrieves an attribute value by local name and namespace URI. * * @param namespaceURI * The namespace URI of the attribute to * retrieve. When it is null or an empty string, * this method behaves like getAttribute. * @param localName The local name of the attribute to retrieve. * @return String The Attr value as a string, or an empty string * if that attribute * does not have a specified or default value. * @since WD-DOM-Level-2-19990923 */ public String getAttributeNS(String namespaceURI, String localName) { if (syncData) { synchronizeData(); } Attr attr = (Attr)(attributes.getNamedItemNS(namespaceURI, localName)); return (attr == null) ? "" : attr.getValue(); } // getAttribute(String):String /** * Introduced in DOM Level 2. <p> * * Adds a new attribute. If an attribute with that local name and namespace URI is * already present in the element, its value is changed to be that of the value * parameter. This value is a simple string, it is not parsed as it is being set. So any * markup (such as syntax to be recognized as an entity reference) is treated as * literal text, and needs to be appropriately escaped by the implementation when * it is written out. In order to assign an attribute value that contains entity * references, the user must create an Attr node plus any Text and * EntityReference nodes, build the appropriate subtree, and use * setAttributeNodeNS or setAttributeNode to assign it as the value of an * attribute. HTML-only DOM implementations do not need to implement this * method. * @param namespaceURI * The namespace URI of the attribute to create * or alter. When it is null or an empty string, * this method behaves like getAttribute. * @param localName The local name of the attribute to create or * alter. * @param value The value to set in string form. * @throws INVALID_CHARACTER_ERR: Raised if the specified * name contains an invalid character. * * @throws NO_MODIFICATION_ALLOWED_ERR: Raised if this * node is readonly. * @since WD-DOM-Level-2-19990923 */ public void setAttributeNS(String namespaceURI, String localName, String value) { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } //REVISTNS: THe createAttributeNS input params is qualifiedName, // but we only have localName. What are implications? AttrImpl newAttr = (AttrImpl) ((DocumentImpl)getOwnerDocument()). createAttributeNS(namespaceURI, localName); newAttr.setNodeValue(value); attributes.setNamedItem(newAttr); newAttr.owned = true; // Set true AFTER adding -- or move in????? } // setAttributeNS(String,String,String) /** * Introduced in DOM Level 2. <p> * * Removes an attribute by local name and namespace URI. If the removed * attribute has a default value it is immediately replaced.<p> * * @param namespaceURI The namespace URI of the attribute to remove. * When it is null or an empty string, this method * behaves like removeAttribute. * @param localName The local name of the attribute to remove. * @since WD-DOM-Level-2-19990923 */ public void removeAttributeNS(String namespaceURI, String localName) { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } AttrImpl att = (AttrImpl) attributes.getNamedItemNS(namespaceURI, localName); // Remove it (and let the NamedNodeMap recreate the default, if any) if (att != null) { att.owned = false; attributes.removeNamedItemNS(namespaceURI, localName); } } // removeAttributeNS(String,String) /** * Retrieves an Attr node by local name and namespace URI. * * @param namespaceURI The namespace URI of the attribute to * retrieve. When it is null or an empty string, * this method behaves like getAttribute. * @param localName The local name of the attribute to retrieve. * @return Attr The Attr node with the specified attribute * local name and namespace * URI or null if there is no such attribute. * @since WD-DOM-Level-2-19990923 */ public Attr getAttributeNodeNS(String namespaceURI, String localName){ if (syncData) { synchronizeData(); } return (Attr)attributes.getNamedItemNS( namespaceURI, localName); } // getAttributeNodeNS(String,String):Attr /** * Introduced in DOM Level 2. <p> * * Adds a new attribute. If an attribute with that local name and * namespace URI is already present in the element, it is replaced * by the new one. * * @param Attr The Attr node to add to the attribute list. When * the Node has no namespaceURI, this method behaves * like setAttributeNode. * @return Attr If the newAttr attribute replaces an existing attribute with the same * local name and namespace URI, the previously existing Attr node is * returned, otherwise null is returned. * @since WD-DOM-Level-2-19990923 */ public Attr setAttributeNodeNS(Attr newAttr) throws DOMException { if (readOnly) { throw new DOMExceptionImpl( DOMException.NO_MODIFICATION_ALLOWED_ERR, "NO_MODIFICATION_ALLOWED_ERR"); } if (syncData) { synchronizeData(); } if (ownerDocument.errorChecking && !(newAttr instanceof AttrImpl)) { throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR, "WRONG_DOCUMENT_ERR"); } AttrImpl na = (AttrImpl) newAttr; AttrImpl oldAttr = (AttrImpl) attributes.getNamedItemNS(na.getNamespaceURI(), na.getLocalName()); // This will throw INUSE if necessary attributes.setNamedItem(na); na.owned = true; // Must set after adding ... or within? return oldAttr; } // setAttributeNodeNS(Attr):Attr /** * Introduced in DOM Level 2. <p> * * Returns a NodeList of all the Elements with a given local name and * namespace URI in the order in which they would be encountered in a preorder * traversal of the Document tree, starting from this node. * * @param namespaceURI The namespace URI of the elements to match * on. The special value "*" matches all * namespaces. When it is null or an empty * string, this method behaves like * getElementsByTagName. * @param localName The local name of the elements to match on. * The special value "*" matches all local names. * @return NodeList A new NodeList object containing all the matched Elements. * @since WD-DOM-Level-2-19990923 */ public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { return new DeepNodeListImpl(this, namespaceURI, localName); } // Public methods /** * NON-DOM: Subclassed to flip the attributes' readonly switch as well. * @see NodeImpl#setReadOnly */ public void setReadOnly(boolean readOnly, boolean deep) { super.setReadOnly(readOnly,deep); if (syncChildren) { synchronizeChildren(); } attributes.setReadOnly(readOnly,true); } // setReadOnly(boolean,boolean) // Protected methods /** Synchronizes the data (name and value) for fast nodes. */ protected void synchronizeData() { // no need to sync in the future syncData = false; // attributes setupDefaultAttributes(); } // synchronizeData() /** Setup the default attributes. */ protected void setupDefaultAttributes() { // If there is an ElementDefintion, set its Attributes up as // shadows behind our own. NamedNodeMapImpl defaultAttrs = null; DocumentTypeImpl doctype = (DocumentTypeImpl)ownerDocument.getDoctype(); if (doctype != null) { ElementDefinitionImpl eldef = (ElementDefinitionImpl)doctype.getElements() .getNamedItem(getNodeName()); if (eldef != null) { defaultAttrs = (NamedNodeMapImpl)eldef.getAttributes(); } } // create attributes attributes = new NamedNodeMapImpl(this, defaultAttrs); } // setupAttributes(DocumentImpl) } // class ElementImpl
package org.biojava.bio.dp; import java.io.*; import java.util.*; import org.w3c.dom.*; import org.biojava.utils.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; import org.biojava.bio.dist.*; public class XmlMarkovModel { public static WeightMatrix readMatrix(Element root) throws IllegalSymbolException, IllegalAlphabetException, BioException { Element alphaE = (Element) root.getElementsByTagName("alphabet").item(0); Alphabet sa = AlphabetManager.alphabetForName( alphaE.getAttribute("name")); if(! (sa instanceof FiniteAlphabet)) { throw new IllegalAlphabetException( "Can't read WeightMatrix over infinite alphabet " + sa.getName() + " of type " + sa.getClass() ); } FiniteAlphabet seqAlpha = (FiniteAlphabet) sa; SymbolParser symParser = seqAlpha.getParser("token"); SymbolParser nameParser = seqAlpha.getParser("name"); int columns = 0; NodeList colL = root.getElementsByTagName("col"); for(int i = 0; i < colL.getLength(); i++) { int indx = Integer.parseInt(((Element) colL.item(i)).getAttribute("indx")); columns = Math.max(columns, indx); } WeightMatrix wm = new SimpleWeightMatrix(seqAlpha, columns, DistributionFactory.DEFAULT); colL = root.getElementsByTagName("col"); for(int i = 0; i < colL.getLength(); i++) { Element colE = (Element) colL.item(i); int indx = Integer.parseInt(colE.getAttribute("indx")) - 1; NodeList weights = colE.getElementsByTagName("weight"); for(int j = 0; j < weights.getLength(); j++) { Element weightE = (Element) weights.item(j); String resName = weightE.getAttribute("res"); Symbol res; if(resName.length() > 1) { res = nameParser.parseToken(resName); } else { res = symParser.parseToken(resName); } try { wm.getColumn(indx).setWeight(res, Double.parseDouble(weightE.getAttribute("prob"))); } catch (ChangeVetoException cve) { throw new BioError("Assertion failure: Should be able to set the weights"); } } } return wm; } public static MarkovModel readModel(Element root) throws BioException, IllegalSymbolException, IllegalAlphabetException { if(root.getTagName().equals("WeightMatrix")) { return new WMAsMM(readMatrix(root)); } int heads = Integer.parseInt(root.getAttribute("heads")); Element alphaE = (Element) root.getElementsByTagName("alphabet").item(0); Alphabet seqAlpha = AlphabetManager.alphabetForName( alphaE.getAttribute("name") ); SimpleMarkovModel model = new SimpleMarkovModel(heads, seqAlpha); int [] advance = new int[heads]; for(int i = 0; i < heads; i++) { advance[i] = 1; } SymbolParser nameParser = null; SymbolParser symbolParser = null; try { nameParser = seqAlpha.getParser("name"); } catch (NoSuchElementException nsee) { } try { symbolParser = seqAlpha.getParser("token"); } catch (NoSuchElementException nsee) { } if(nameParser == null && symbolParser == null) { throw new BioException( "Couldn't find a parser for alphabet " + seqAlpha.getName() ); } Map nameToState = new HashMap(); nameToState.put("_start_", model.magicalState()); nameToState.put("_end_", model.magicalState()); nameToState.put("_START_", model.magicalState()); nameToState.put("_END_", model.magicalState()); NodeList states = root.getElementsByTagName("state"); for(int i = 0; i < states.getLength(); i++) { Element stateE = (Element) states.item(i); String name = stateE.getAttribute("name"); Distribution dis = DistributionFactory.DEFAULT.createDistribution(seqAlpha); EmissionState state = new SimpleEmissionState( name, Annotation.EMPTY_ANNOTATION, advance, dis ); nameToState.put(name, state); NodeList weights = stateE.getElementsByTagName("weight"); for(int j = 0; j < weights.getLength(); j++) { Element weightE = (Element) weights.item(j); String resName = weightE.getAttribute("res"); Symbol res; if(resName.length() == 1) { if(symbolParser != null) { res = symbolParser.parseToken(resName); } else { res = nameParser.parseToken(resName); } } else { if(nameParser != null) { res = nameParser.parseToken(resName); } else { res = symbolParser.parseToken(resName); } } try { dis.setWeight(res, Double.parseDouble(weightE.getAttribute("prob"))); } catch (ChangeVetoException cve) { throw new BioError( cve, "Assertion failure: Should be able to edit distribution" ); } } try { model.addState(state); } catch (ChangeVetoException cve) { throw new BioError( cve, "Assertion failure: Should be able to add states to model" ); } } NodeList transitions = root.getElementsByTagName("transition"); for(int i = 0; i < transitions.getLength(); i++) { Element transitionE = (Element) transitions.item(i); State from = (State) nameToState.get(transitionE.getAttribute("from")); State to = (State) nameToState.get(transitionE.getAttribute("to")); double prob = Double.parseDouble(transitionE.getAttribute("prob")); try { model.createTransition(from, to); } catch (IllegalSymbolException ite) { throw new BioError( ite, "We should have unlimited write-access to this model. " + "Something is very wrong." ); } catch (ChangeVetoException cve) { throw new BioError( cve, "We should have unlimited write-access to this model. " + "Something is very wrong." ); } } for(int i = 0; i < transitions.getLength(); i++) { Element transitionE = (Element) transitions.item(i); State from = (State) nameToState.get(transitionE.getAttribute("from")); State to = (State) nameToState.get(transitionE.getAttribute("to")); double prob = Double.parseDouble(transitionE.getAttribute("prob")); try { model.getWeights(from).setWeight(to, prob); } catch (IllegalSymbolException ite) { throw new BioError( ite, "We should have unlimited write-access to this model. " + "Something is very wrong." ); } catch (ChangeVetoException cve) { throw new BioError( cve, "We should have unlimited write-access to this model. " + "Something is very wrong." ); } } return model; } public static void writeMatrix(WeightMatrix matrix, PrintStream out) throws Exception { FiniteAlphabet resA = (FiniteAlphabet) matrix.getAlphabet(); out.println("<MarkovModel>\n <alphabet name=\"" + resA.getName() + "\"/>"); for(int i = 0; i < matrix.columns(); i++) { out.println(" <col indx=\"" + (i+1) + "\">"); for(Iterator ri = resA.iterator(); ri.hasNext(); ) { Symbol r = (Symbol) ri.next(); out.println(" <weight res=\"" + r.getName() + "\" prob=\"" + matrix.getColumn(i).getWeight(r) + "\"/>"); } out.println(" </col>"); } out.println("</MarkovModel>"); } public static void writeModel(MarkovModel model, PrintStream out) throws Exception { model = DP.flatView(model); FiniteAlphabet stateA = model.stateAlphabet(); FiniteAlphabet resA = (FiniteAlphabet) model.emissionAlphabet(); SymbolList stateR = stateA.symbols(); List stateL = stateR.toList(); SymbolList resR = resA.symbols(); out.println("<MarkovModel heads=\"" + model.heads() + "\">"); out.println("<alphabet name=\"" + resA.getName() + "\"/>"); // print out states & scores for(Iterator stateI = stateL.iterator(); stateI.hasNext(); ) { State s = (State) stateI.next(); if(! (s instanceof MagicalState)) { out.println(" <state name=\"" + s.getName() + "\">"); if(s instanceof EmissionState) { EmissionState es = (EmissionState) s; Distribution dis = es.getDistribution(); for(Iterator resI = resR.iterator(); resI.hasNext(); ) { Symbol r = (Symbol) resI.next(); out.println(" <weight res=\"" + r.getName() + "\" prob=\"" + dis.getWeight(r) + "\"/>"); } } out.println(" </state>"); } } // print out transitions for(Iterator i = stateL.iterator(); i.hasNext(); ) { State from = (State) i.next(); printTransitions(model, from, out); } out.println("</MarkovModel>"); } static private void printTransitions(MarkovModel model, State from, PrintStream out) throws IllegalSymbolException { for(Iterator i = model.transitionsFrom(from).iterator(); i.hasNext(); ) { State to = (State) i.next(); try { out.println(" <transition from=\"" + ((from instanceof MagicalState) ? "_start_" : from.getName()) + "\" to=\"" + ((to instanceof MagicalState) ? "_end_" : to.getName()) + "\" prob=\"" + model.getWeights(from).getWeight(to) + "\"/>"); } catch (IllegalSymbolException ite) { throw new BioError(ite, "Transition listed in transitionsFrom(" + from.getName() + ") has dissapeared"); } } } }
package org.biojava.bio.taxa; import org.biojava.utils.*; import org.biojava.bio.*; public abstract class AbstractTaxa extends AbstractChangeable implements Taxa { private transient ChangeListener annotationForwarder; private Annotation ann; private String commonName; private String scientificName; protected AbstractTaxa() {} protected AbstractTaxa(String scientificName, String commonName) { this.scientificName = scientificName; this.commonName = commonName; } // ensure that change support gubbins gets wired in for the annotation object. protected ChangeSupport getChangeSupport(ChangeType ct) { ChangeSupport cs = super.getChangeSupport(ct); if( (annotationForwarder == null) && (ct == null || ct == Annotatable.ANNOTATION) ) { annotationForwarder = new Annotatable.AnnotationForwarder( this, cs ); getAnnotation().addChangeListener( annotationForwarder, Annotatable.ANNOTATION ); } return cs; } public String getCommonName() { return commonName; } public void setCommonName(String commonName) throws ChangeVetoException { if(this.commonName != null) { throw new ChangeVetoException( "Common name already set to: " + this.commonName + " so you can't set it to: " + commonName ); } if(hasListeners()) { ChangeSupport cs = getChangeSupport(Taxa.CHANGE_COMMON_NAME); ChangeEvent cevt = new ChangeEvent(this, Taxa.CHANGE_COMMON_NAME, commonName); synchronized(cs) { cs.firePreChangeEvent(cevt); this.commonName = commonName; cs.firePostChangeEvent(cevt); } } else { this.commonName = commonName; } } public String getScientificName() { return scientificName; } public void setScientificName(String scientificName) throws ChangeVetoException { if(this.scientificName != null) { throw new ChangeVetoException( "Common name already set to: " + this.scientificName + " so you can't set it to: " + scientificName ); } if(hasListeners()) { ChangeSupport cs = getChangeSupport(Taxa.CHANGE_SCIENTIFIC_NAME); ChangeEvent cevt = new ChangeEvent(this, Taxa.CHANGE_SCIENTIFIC_NAME, scientificName); synchronized(cs) { cs.firePreChangeEvent(cevt); this.scientificName = scientificName; cs.firePostChangeEvent(cevt); } } else { this.scientificName = scientificName; } } public Annotation getAnnotation() { if(ann == null) { ann = new SmallAnnotation(); } return ann; } public boolean equals(Object o) { if(o instanceof Taxa) { Taxa t = (Taxa) o; return this == t || ( safeEq(this.getScientificName(), t.getScientificName()) && safeEq(this.getCommonName(), t.getCommonName()) && safeEq(this.getChildren(), t.getChildren()) ); } return false; } public String toString() { Taxa parent = getParent(); String scientificName = getScientificName(); if(parent != null) { return parent.toString() + " -> " + scientificName; } else { return scientificName; } } public int hashCode() { return getScientificName().hashCode(); } private boolean safeEq(Object a, Object b) { if(a == null && b == null) { return true; } else if(a == null || b == null) { return false; } else { return a.equals(b); } } }
package org.exist.xquery.value; import java.text.Collator; import org.exist.dom.QName; import org.exist.xquery.Constants; import org.exist.xquery.XQueryContext; import org.exist.xquery.XPathException; /** * Wrapper class around a {@link org.exist.dom.QName} value which extends * {@link org.exist.xquery.value.AtomicValue}. * * @author wolf */ public class QNameValue extends AtomicValue { private XQueryContext context; private QName qname; /** * Constructs a new QNameValue by parsing the given name using * the namespace declarations in context. * * @param context * @param name * @throws XPathException */ public QNameValue(XQueryContext context, String name) throws XPathException { this.context = context; this.qname = QName.parse(context, name, context.getURIForPrefix("")); } public QNameValue(XQueryContext context, QName name) { this.context = context; this.qname = name; } /** * @see org.exist.xquery.value.AtomicValue#getType() */ public int getType() { return Type.QNAME; } /** * Returns the wrapped QName object. * @return */ public QName getQName() { return qname; } /** * @see org.exist.xquery.value.Sequence#getStringValue() */ public String getStringValue() throws XPathException { if(qname.needsNamespaceDecl()) { String prefix = context.getPrefixForURI(qname.getNamespaceURI()); if (prefix == null) throw new XPathException( "namespace " + qname.getNamespaceURI() + " is not defined"); qname.setPrefix(prefix); } return qname.toString(); } /** * @see org.exist.xquery.value.Sequence#convertTo(int) */ public AtomicValue convertTo(int requiredType) throws XPathException { switch (requiredType) { case Type.ATOMIC : case Type.ITEM : case Type.QNAME : return this; case Type.STRING : return new StringValue( getStringValue() ); default : throw new XPathException( "A QName cannot be converted to " + Type.getTypeName(requiredType)); } } /** * @see org.exist.xquery.value.AtomicValue#compareTo(int, org.exist.xquery.value.AtomicValue) */ public boolean compareTo(Collator collator, int operator, AtomicValue other) throws XPathException { if (other.getType() == Type.QNAME) { int cmp = qname.compareTo(((QNameValue) other).qname); switch (operator) { case Constants.EQ : return cmp == 0; case Constants.NEQ : return cmp != 0; case Constants.GT : return cmp > 0; case Constants.GTEQ : return cmp >= 0; case Constants.LT : return cmp < 0; case Constants.LTEQ : return cmp >= 0; default : throw new XPathException("Type error: cannot apply operator to QName"); } } else throw new XPathException( "Type error: cannot compare QName to " + Type.getTypeName(other.getType())); } /** * @see org.exist.xquery.value.AtomicValue#compareTo(org.exist.xquery.value.AtomicValue) */ public int compareTo(Collator collator, AtomicValue other) throws XPathException { if (other.getType() == Type.QNAME) { return qname.compareTo(((QNameValue) other).qname); } else throw new XPathException( "Type error: cannot compare QName to " + Type.getTypeName(other.getType())); } /** * @see org.exist.xquery.value.AtomicValue#max(org.exist.xquery.value.AtomicValue) */ public AtomicValue max(Collator collator, AtomicValue other) throws XPathException { throw new XPathException("Invalid argument to aggregate function: QName"); } public AtomicValue min(Collator collator, AtomicValue other) throws XPathException { throw new XPathException("Invalid argument to aggregate function: QName"); } /** * @see org.exist.xquery.value.Item#conversionPreference(java.lang.Class) */ public int conversionPreference(Class javaClass) { if (javaClass.isAssignableFrom(QNameValue.class)) return 0; if (javaClass == String.class) return 1; if (javaClass == Object.class) return 20; return Integer.MAX_VALUE; } /** * @see org.exist.xquery.value.Item#toJavaObject(java.lang.Class) */ public Object toJavaObject(Class target) throws XPathException { if (target.isAssignableFrom(QNameValue.class)) return this; else if (target == String.class) return getStringValue(); else if (target == Object.class) return qname; throw new XPathException( "cannot convert value of type " + Type.getTypeName(getType()) + " to Java object of type " + target.getName()); } }
package org.jaudiotagger.tag.id3; import org.jaudiotagger.audio.generic.Utils; import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.logging.ErrorMessage; import org.jaudiotagger.tag.*; import org.jaudiotagger.tag.images.Artwork; import org.jaudiotagger.tag.reference.GenreTypes; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.*; import java.util.regex.Matcher; /** * Represents an ID3v1 tag. * * @author : Eric Farng * @author : Paul Taylor */ public class ID3v1Tag extends AbstractID3v1Tag implements Tag { static EnumMap<FieldKey, ID3v1FieldKey> tagFieldToID3v1Field = new EnumMap<FieldKey, ID3v1FieldKey>(FieldKey.class); static { tagFieldToID3v1Field.put(FieldKey.ARTIST, ID3v1FieldKey.ARTIST); tagFieldToID3v1Field.put(FieldKey.ALBUM, ID3v1FieldKey.ALBUM); tagFieldToID3v1Field.put(FieldKey.TITLE, ID3v1FieldKey.TITLE); tagFieldToID3v1Field.put(FieldKey.TRACK, ID3v1FieldKey.TRACK); tagFieldToID3v1Field.put(FieldKey.YEAR, ID3v1FieldKey.YEAR); tagFieldToID3v1Field.put(FieldKey.GENRE, ID3v1FieldKey.GENRE); tagFieldToID3v1Field.put(FieldKey.COMMENT, ID3v1FieldKey.COMMENT); } //For writing output protected static final String TYPE_COMMENT = "comment"; protected static final int FIELD_COMMENT_LENGTH = 30; protected static final int FIELD_COMMENT_POS = 97; protected static final int BYTE_TO_UNSIGNED = 0xff; protected static final int GENRE_UNDEFINED = 0xff; protected String album = ""; protected String artist = ""; protected String comment = ""; protected String title = ""; protected String year = ""; protected byte genre = (byte) -1; private static final byte RELEASE = 1; private static final byte MAJOR_VERSION = 0; private static final byte REVISION = 0; /** * Retrieve the Release */ public byte getRelease() { return RELEASE; } /** * Retrieve the Major Version */ public byte getMajorVersion() { return MAJOR_VERSION; } /** * Retrieve the Revision */ public byte getRevision() { return REVISION; } /** * Creates a new ID3v1 datatype. */ public ID3v1Tag() { } public ID3v1Tag(ID3v1Tag copyObject) { super(copyObject); this.album = copyObject.album; this.artist = copyObject.artist; this.comment = copyObject.comment; this.title = copyObject.title; this.year = copyObject.year; this.genre = copyObject.genre; } public ID3v1Tag(AbstractTag mp3tag) { if (mp3tag != null) { ID3v11Tag convertedTag; if (mp3tag instanceof ID3v1Tag) { throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument"); } if (mp3tag instanceof ID3v11Tag) { convertedTag = (ID3v11Tag) mp3tag; } else { convertedTag = new ID3v11Tag(mp3tag); } this.album = convertedTag.album; this.artist = convertedTag.artist; this.comment = convertedTag.comment; this.title = convertedTag.title; this.year = convertedTag.year; this.genre = convertedTag.genre; } } /** * Creates a new ID3v1 datatype. * * @param file * @param loggingFilename * @throws TagNotFoundException * @throws IOException */ public ID3v1Tag(RandomAccessFile file, String loggingFilename) throws TagNotFoundException, IOException { setLoggingFilename(loggingFilename); FileChannel fc; ByteBuffer byteBuffer; fc = file.getChannel(); fc.position(file.length() - TAG_LENGTH); byteBuffer = ByteBuffer.allocate(TAG_LENGTH); fc.read(byteBuffer); byteBuffer.flip(); read(byteBuffer); } /** * Creates a new ID3v1 datatype. * * @param file * @throws TagNotFoundException * @throws IOException * @deprecated use {@link #ID3v1Tag(RandomAccessFile,String)} instead */ public ID3v1Tag(RandomAccessFile file) throws TagNotFoundException, IOException { this(file, ""); } public void addField(TagField field) { //TODO } public List<TagField> getFields(String id) { if (FieldKey.ARTIST.name().equals(id)) { return getArtist(); } else if (FieldKey.ALBUM.name().equals(id)) { return getAlbum(); } else if (FieldKey.TITLE.name().equals(id)) { return getTitle(); } else if (FieldKey.GENRE.name().equals(id)) { return getGenre(); } else if (FieldKey.YEAR.name().equals(id)) { return getYear(); } else if (FieldKey.COMMENT.name().equals(id)) { return getComment(); } return new ArrayList<TagField>(); } public int getFieldCount() { return 6; } public int getFieldCountIncludingSubValues() { return getFieldCount(); } protected List<TagField> returnFieldToList(ID3v1TagField field) { List<TagField> fields = new ArrayList<TagField>(); fields.add(field); return fields; } /** * Set Album * * @param album */ public void setAlbum(String album) { if (album == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } this.album = ID3Tags.truncate(album, FIELD_ALBUM_LENGTH); } /** * Get Album * * @return album */ protected String getFirstAlbum() { return album; } /** * @return album within list or empty if does not exist */ public List<TagField> getAlbum() { if (getFirstAlbum().length() > 0) { ID3v1TagField field = new ID3v1TagField(ID3v1FieldKey.ALBUM.name(), getFirstAlbum()); return returnFieldToList(field); } else { return new ArrayList<TagField>(); } } /** * Set Artist * * @param artist */ public void setArtist(String artist) { if (artist == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } this.artist = ID3Tags.truncate(artist, FIELD_ARTIST_LENGTH); } /** * Get Artist * * @return artist */ public String getFirstArtist() { return artist; } /** * @return Artist within list or empty if does not exist */ public List<TagField> getArtist() { if (getFirstArtist().length() > 0) { ID3v1TagField field = new ID3v1TagField(ID3v1FieldKey.ARTIST.name(), getFirstArtist()); return returnFieldToList(field); } else { return new ArrayList<TagField>(); } } public void setComment(String comment) { if (comment == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } this.comment = ID3Tags.truncate(comment, FIELD_COMMENT_LENGTH); } /** * @return comment within list or empty if does not exist */ public List<TagField> getComment() { if (getFirstComment().length() > 0) { ID3v1TagField field = new ID3v1TagField(ID3v1FieldKey.COMMENT.name(), getFirstComment()); return returnFieldToList(field); } else { return new ArrayList<TagField>(); } } /** * Get Comment * * @return comment */ public String getFirstComment() { return comment; } /** * Sets the genreID, * <p/> * <p>ID3v1 only supports genres defined in a predefined list * so if unable to find value in list set 255, which seems to be the value * winamp uses for undefined. * * @param genreVal */ public void setGenre(String genreVal) { if (genreVal == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } Integer genreID = GenreTypes.getInstanceOf().getIdForValue(genreVal); if (genreID != null) { this.genre = genreID.byteValue(); } else { this.genre = (byte) GENRE_UNDEFINED; } } /** * Get Genre * * @return genre or empty string if not valid */ public String getFirstGenre() { Integer genreId = genre & BYTE_TO_UNSIGNED; String genreValue = GenreTypes.getInstanceOf().getValueForId(genreId); if (genreValue == null) { return ""; } else { return genreValue; } } /** * Get Genre field * <p/> * <p>Only a single genre is available in ID3v1 * * @return */ public List<TagField> getGenre() { if (getFirst(FieldKey.GENRE).length() > 0) { ID3v1TagField field = new ID3v1TagField(ID3v1FieldKey.GENRE.name(), getFirst(FieldKey.GENRE)); return returnFieldToList(field); } else { return new ArrayList<TagField>(); } } /** * Set Title * * @param title */ public void setTitle(String title) { if (title == null) { throw new IllegalArgumentException(ErrorMessage.GENERAL_INVALID_NULL_ARGUMENT.getMsg()); } this.title = ID3Tags.truncate(title, FIELD_TITLE_LENGTH); } /** * Get title * * @return Title */ public String getFirstTitle() { return title; } /** * Get title field * <p/> * <p>Only a single title is available in ID3v1 * * @return */ public List<TagField> getTitle() { if (getFirst(FieldKey.TITLE).length() > 0) { ID3v1TagField field = new ID3v1TagField(ID3v1FieldKey.TITLE.name(), getFirst(FieldKey.TITLE)); return returnFieldToList(field); } else { return new ArrayList<TagField>(); } } /** * Set year * * @param year */ public void setYear(String year) { this.year = ID3Tags.truncate(year, FIELD_YEAR_LENGTH); } /** * Get year * * @return year */ public String getFirstYear() { return year; } /** * Get year field * <p/> * <p>Only a single year is available in ID3v1 * * @return */ public List<TagField> getYear() { if (getFirst(FieldKey.YEAR).length() > 0) { ID3v1TagField field = new ID3v1TagField(ID3v1FieldKey.YEAR.name(), getFirst(FieldKey.YEAR)); return returnFieldToList(field); } else { return new ArrayList<TagField>(); } } public String getFirstTrack() { throw new UnsupportedOperationException("ID3v10 cannot store track numbers"); } public List<TagField> getTrack() { throw new UnsupportedOperationException("ID3v10 cannot store track numbers"); } public TagField getFirstField(String id) { List<TagField> results = null; if (FieldKey.ARTIST.name().equals(id)) { results = getArtist(); } else if (FieldKey.ALBUM.name().equals(id)) { results = getAlbum(); } else if (FieldKey.TITLE.name().equals(id)) { results = getTitle(); } else if (FieldKey.GENRE.name().equals(id)) { results = getGenre(); } else if (FieldKey.YEAR.name().equals(id)) { results = getYear(); } else if (FieldKey.COMMENT.name().equals(id)) { results = getComment(); } if (results != null) { if (results.size() > 0) { return results.get(0); } } return null; } public Iterator<TagField> getFields() { throw new UnsupportedOperationException("TODO:Not done yet"); } public boolean hasCommonFields() { //TODO return true; } public boolean hasField(String id) { //TODO throw new UnsupportedOperationException("TODO:Not done yet"); } public boolean isEmpty() { return !(getFirst(FieldKey.TITLE).length() > 0 || getFirstArtist().length() > 0 || getFirstAlbum().length() > 0 || getFirst(FieldKey.GENRE).length() > 0 || getFirst(FieldKey.YEAR).length() > 0 || getFirstComment().length() > 0); } public void setField(FieldKey genericKey, String value) throws KeyNotFoundException, FieldDataInvalidException { TagField tagfield = createField(genericKey,value); setField(tagfield); } public void addField(FieldKey genericKey, String value) throws KeyNotFoundException, FieldDataInvalidException { setField(genericKey,value); } public void setField(TagField field) { FieldKey genericKey = FieldKey.valueOf(field.getId()); switch (genericKey) { case ARTIST: setArtist(field.toString()); break; case ALBUM: setAlbum(field.toString()); break; case TITLE: setTitle(field.toString()); break; case GENRE: setGenre(field.toString()); break; case YEAR: setYear(field.toString()); break; case COMMENT: setComment(field.toString()); break; } } /** * @param encoding * @return */ public boolean setEncoding(String encoding) { return true; } /** * Create Tag Field using generic key */ public TagField createField(FieldKey genericKey, String value) { return new ID3v1TagField(tagFieldToID3v1Field.get(genericKey).name(), value); } public String getEncoding() { return "ISO-8859-1"; } public TagField getFirstField(FieldKey genericKey) { List<TagField> l = getFields(genericKey); return (l.size() != 0) ? l.get(0) : null; } /** * Returns a {@linkplain List list} of {@link TagField} objects whose &quot;{@linkplain TagField#getId() id}&quot; * is the specified one.<br> * * @param genericKey The generic field key * @return A list of {@link TagField} objects with the given &quot;id&quot;. */ public List<TagField> getFields(FieldKey genericKey) { switch (genericKey) { case ARTIST: return getArtist(); case ALBUM: return getAlbum(); case TITLE: return getTitle(); case GENRE: return getGenre(); case YEAR: return getYear(); case COMMENT: return getComment(); default: return new ArrayList<TagField>(); } } /** * Retrieve the first value that exists for this key id * * @param genericKey * @return */ public String getFirst(String genericKey) { FieldKey matchingKey = FieldKey.valueOf(genericKey); if (matchingKey != null) { return getFirst(matchingKey); } else { return ""; } } /** * Retrieve the first value that exists for this generic key * * @param genericKey * @return */ public String getFirst(FieldKey genericKey) { switch (genericKey) { case ARTIST: return getFirstArtist(); case ALBUM: return getFirstAlbum(); case TITLE: return getFirstTitle(); case GENRE: return getFirstGenre(); case YEAR: return getFirstYear(); case COMMENT: return getFirstComment(); default: return ""; } } /** * The m parameter is effectively ignored * * @param id * @param n * @param m * @return */ public String getSubValue(FieldKey id, int n, int m) { return getValue(id,n); } public String getValue(FieldKey genericKey, int index) { return getFirst(genericKey); } /** * Delete any instance of tag fields with this key * * @param genericKey */ public void deleteField(FieldKey genericKey) { switch (genericKey) { case ARTIST: setArtist(""); break; case ALBUM: setAlbum(""); break; case TITLE: setTitle(""); break; case GENRE: setGenre(""); break; case YEAR: setYear(""); break; case COMMENT: setComment(""); break; } } public void deleteField(String id) { FieldKey key = FieldKey.valueOf(id); if(key!=null) { deleteField(key); } } /** * @param obj * @return true if this and obj are equivalent */ public boolean equals(Object obj) { if (!(obj instanceof ID3v1Tag)) { return false; } ID3v1Tag object = (ID3v1Tag) obj; if (!this.album.equals(object.album)) { return false; } if (!this.artist.equals(object.artist)) { return false; } if (!this.comment.equals(object.comment)) { return false; } if (this.genre != object.genre) { return false; } if (!this.title.equals(object.title)) { return false; } return this.year.equals(object.year) && super.equals(obj); } /** * @return an iterator to iterate through the fields of the tag */ public Iterator iterator() { return new ID3v1Iterator(this); } /** * @param byteBuffer * @throws TagNotFoundException */ public void read(ByteBuffer byteBuffer) throws TagNotFoundException { if (!seek(byteBuffer)) { throw new TagNotFoundException(getLoggingFilename() + ":" + "ID3v1 tag not found"); } logger.finer(getLoggingFilename() + ":" + "Reading v1 tag"); //Do single file read of data to cut down on file reads byte[] dataBuffer = new byte[TAG_LENGTH]; byteBuffer.position(0); byteBuffer.get(dataBuffer, 0, TAG_LENGTH); title = Utils.getString(dataBuffer, FIELD_TITLE_POS, FIELD_TITLE_LENGTH, "ISO-8859-1").trim(); Matcher m = AbstractID3v1Tag.endofStringPattern.matcher(title); if (m.find()) { title = title.substring(0, m.start()); } artist = Utils.getString(dataBuffer, FIELD_ARTIST_POS, FIELD_ARTIST_LENGTH, "ISO-8859-1").trim(); m = AbstractID3v1Tag.endofStringPattern.matcher(artist); if (m.find()) { artist = artist.substring(0, m.start()); } album = Utils.getString(dataBuffer, FIELD_ALBUM_POS, FIELD_ALBUM_LENGTH, "ISO-8859-1").trim(); m = AbstractID3v1Tag.endofStringPattern.matcher(album); logger.finest(getLoggingFilename() + ":" + "Orig Album is:" + comment + ":"); if (m.find()) { album = album.substring(0, m.start()); logger.finest(getLoggingFilename() + ":" + "Album is:" + album + ":"); } year = Utils.getString(dataBuffer, FIELD_YEAR_POS, FIELD_YEAR_LENGTH, "ISO-8859-1").trim(); m = AbstractID3v1Tag.endofStringPattern.matcher(year); if (m.find()) { year = year.substring(0, m.start()); } comment = Utils.getString(dataBuffer, FIELD_COMMENT_POS, FIELD_COMMENT_LENGTH, "ISO-8859-1").trim(); m = AbstractID3v1Tag.endofStringPattern.matcher(comment); logger.finest(getLoggingFilename() + ":" + "Orig Comment is:" + comment + ":"); if (m.find()) { comment = comment.substring(0, m.start()); logger.finest(getLoggingFilename() + ":" + "Comment is:" + comment + ":"); } genre = dataBuffer[FIELD_GENRE_POS]; } /** * Does a tag of this version exist within the byteBuffer * * @return whether tag exists within the byteBuffer */ public boolean seek(ByteBuffer byteBuffer) { byte[] buffer = new byte[FIELD_TAGID_LENGTH]; // read the TAG value byteBuffer.get(buffer, 0, FIELD_TAGID_LENGTH); return (Arrays.equals(buffer, TAG_ID)); } /** * Write this tag to the file, replacing any tag previously existing * * @param file * @throws IOException */ public void write(RandomAccessFile file) throws IOException { logger.config("Saving ID3v1 tag to file"); byte[] buffer = new byte[TAG_LENGTH]; int i; String str; delete(file); file.seek(file.length()); //Copy the TAGID into new buffer System.arraycopy(TAG_ID, FIELD_TAGID_POS, buffer, FIELD_TAGID_POS, TAG_ID.length); int offset = FIELD_TITLE_POS; if (TagOptionSingleton.getInstance().isId3v1SaveTitle()) { str = ID3Tags.truncate(title, FIELD_TITLE_LENGTH); for (i = 0; i < str.length(); i++) { buffer[i + offset] = (byte) str.charAt(i); } } offset = FIELD_ARTIST_POS; if (TagOptionSingleton.getInstance().isId3v1SaveArtist()) { str = ID3Tags.truncate(artist, FIELD_ARTIST_LENGTH); for (i = 0; i < str.length(); i++) { buffer[i + offset] = (byte) str.charAt(i); } } offset = FIELD_ALBUM_POS; if (TagOptionSingleton.getInstance().isId3v1SaveAlbum()) { str = ID3Tags.truncate(album, FIELD_ALBUM_LENGTH); for (i = 0; i < str.length(); i++) { buffer[i + offset] = (byte) str.charAt(i); } } offset = FIELD_YEAR_POS; if (TagOptionSingleton.getInstance().isId3v1SaveYear()) { str = ID3Tags.truncate(year, AbstractID3v1Tag.FIELD_YEAR_LENGTH); for (i = 0; i < str.length(); i++) { buffer[i + offset] = (byte) str.charAt(i); } } offset = FIELD_COMMENT_POS; if (TagOptionSingleton.getInstance().isId3v1SaveComment()) { str = ID3Tags.truncate(comment, FIELD_COMMENT_LENGTH); for (i = 0; i < str.length(); i++) { buffer[i + offset] = (byte) str.charAt(i); } } offset = FIELD_GENRE_POS; if (TagOptionSingleton.getInstance().isId3v1SaveGenre()) { buffer[offset] = genre; } file.write(buffer); logger.config("Saved ID3v1 tag to file"); } /** * Create structured representation of this item. */ public void createStructure() { MP3File.getStructureFormatter().openHeadingElement(TYPE_TAG, getIdentifier()); //Header MP3File.getStructureFormatter().addElement(TYPE_TITLE, this.title); MP3File.getStructureFormatter().addElement(TYPE_ARTIST, this.artist); MP3File.getStructureFormatter().addElement(TYPE_ALBUM, this.album); MP3File.getStructureFormatter().addElement(TYPE_YEAR, this.year); MP3File.getStructureFormatter().addElement(TYPE_COMMENT, this.comment); MP3File.getStructureFormatter().addElement(TYPE_GENRE, this.genre); MP3File.getStructureFormatter().closeHeadingElement(TYPE_TAG); } public List<Artwork> getArtworkList() { return Collections.emptyList(); } public Artwork getFirstArtwork() { return null; } public TagField createField(Artwork artwork) throws FieldDataInvalidException { throw new UnsupportedOperationException(ErrorMessage.GENERIC_NOT_SUPPORTED.getMsg()); } public void setField(Artwork artwork) throws FieldDataInvalidException { throw new UnsupportedOperationException(ErrorMessage.GENERIC_NOT_SUPPORTED.getMsg()); } public void addField(Artwork artwork) throws FieldDataInvalidException { throw new UnsupportedOperationException(ErrorMessage.GENERIC_NOT_SUPPORTED.getMsg()); } /** * Delete all instance of artwork Field * * @throws KeyNotFoundException */ public void deleteArtworkField() throws KeyNotFoundException { throw new UnsupportedOperationException(ErrorMessage.GENERIC_NOT_SUPPORTED.getMsg()); } }
package org.jitsi.meet.test; import junit.framework.*; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.*; /** * Adds various tests with the etherpad functionality. * @author Damian Minkov */ public class EtherpadTests extends TestCase { /** * Constructs test. * @param name the method name for the test. */ public EtherpadTests(String name) { super(name); } /** * Orders the tests. * @return the suite with order tests. */ public static junit.framework.Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new EtherpadTests("enterEtherpad")); suite.addTest(new EtherpadTests("writeTextAndCheck")); suite.addTest(new EtherpadTests("closeEtherpadCheck")); // lets check after closing etherpad we are able to click on videos suite.addTest(new EtherpadTests("focusClickOnLocalVideoAndTest")); suite.addTest(new EtherpadTests("focusClickOnRemoteVideoAndTest")); suite.addTest(new EtherpadTests("enterEtherpad")); //suite.addTest(new EtherpadTests("writeTextAndCheck")); //lets not directly click on videos without closing etherpad suite.addTest(new SwitchVideoTests("focusClickOnLocalVideoAndTest")); suite.addTest(new SwitchVideoTests("focusClickOnRemoteVideoAndTest")); return suite; } /** * Clicks on share document button and check whether etherpad is loaded * and video is hidden. */ public void enterEtherpad() { // waits for etherpad button to be displayed in the toolbar TestUtils.waitsForDisplayedElementByID( ConferenceFixture.getFocus(), "etherpadButton", 15); TestUtils.clickOnToolbarButtonByClass(ConferenceFixture.getFocus(), "icon-share-doc"); TestUtils.waits(5000); TestUtils.waitsForNotDisplayedElementByID( ConferenceFixture.getFocus(), "largeVideo", 10); } /** * Write some text and check on the other side, whether the text * is visible. */ public void writeTextAndCheck() { try { WebDriverWait wait = new WebDriverWait( ConferenceFixture.getFocus(), 30); wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt( By.tagName("iframe"))); wait = new WebDriverWait( ConferenceFixture.getFocus(), 30); wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt( By.name("ace_outer"))); wait = new WebDriverWait( ConferenceFixture.getFocus(), 30); wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt( By.name("ace_inner"))); String textToEnter = "SomeTestText"; ConferenceFixture.getFocus().findElement( By.id("innerdocbody")).sendKeys(textToEnter); TestUtils.waits(2000); // now search and check the text String txt = ConferenceFixture.getFocus().findElement( By.xpath("//span[contains(@class, 'author')]")).getText(); assertEquals("Texts do not match", textToEnter, txt); } finally { ConferenceFixture.getFocus().switchTo().defaultContent(); } } /** * Close the etherpad and checks whether video is still visible. */ public void closeEtherpadCheck() { TestUtils.clickOnToolbarButtonByClass(ConferenceFixture.getFocus(), "icon-share-doc"); TestUtils.waits(5000); TestUtils.waitsForDisplayedElementByID( ConferenceFixture.getFocus(), "largeVideo", 10); } /** * Click on local video thumbnail and checks whether the large video * is the local one. */ public void focusClickOnLocalVideoAndTest() { new SwitchVideoTests("focusClickOnLocalVideoAndTest") .focusClickOnLocalVideoAndTest(); } /** * Clicks on the remote video thumbnail and checks whether the large video * is the remote one. */ public void focusClickOnRemoteVideoAndTest() { new SwitchVideoTests("focusClickOnRemoteVideoAndTest") .focusClickOnRemoteVideoAndTest(); } }
/* * $Id: BasePlugin.java,v 1.37 2006-04-05 22:54:41 tlipkis Exp $ */ package org.lockss.plugin.base; import java.util.*; import org.lockss.util.*; import org.lockss.util.urlconn.*; import org.lockss.app.*; import org.lockss.config.ConfigManager; import org.lockss.config.Configuration; import org.lockss.daemon.*; import org.lockss.plugin.*; /** * Abstract base class for Plugins. Plugins are encouraged to extend this * class to get some common Plugin functionality. */ public abstract class BasePlugin implements Plugin { static Logger log = Logger.getLogger("BasePlugin"); static final String PARAM_TITLE_DB = ConfigManager.PARAM_TITLE_DB; // Below org.lockss.title.xxx. static final String TITLE_PARAM_TITLE = "title"; static final String TITLE_PARAM_JOURNAL = "journalTitle"; public static final String TITLE_PARAM_PLUGIN = "plugin"; static final String TITLE_PARAM_PLUGIN_VERSION = "pluginVersion"; static final String TITLE_PARAM_EST_SIZE = "estSize"; static final String TITLE_PARAM_ATTRIBUTES = "attributes"; static final String TITLE_PARAM_PARAM = "param"; // Below org.lockss.title.xxx.param.n. static final String TITLE_PARAM_PARAM_KEY = "key"; static final String TITLE_PARAM_PARAM_VALUE = "value"; static final String TITLE_PARAM_PARAM_EDITABLE = "editable"; protected LockssDaemon theDaemon; protected PluginManager pluginMgr; protected Collection aus = new ArrayList(); protected Map titleConfigMap; // XXX need to generalize this protected CacheResultMap resultMap; /** * Must invoke this constructor in plugin subclass. */ protected BasePlugin() { } public void initPlugin(LockssDaemon daemon) { theDaemon = daemon; pluginMgr = theDaemon.getPluginManager(); theDaemon.getConfigManager().registerConfigurationCallback(new Configuration.Callback() { public void configurationChanged(Configuration newConfig, Configuration prevConfig, Configuration.Differences changedKeys) { setConfig(newConfig, prevConfig, changedKeys); } public String toString() { return getPluginId(); } }); initResultMap(); } public void stopPlugin() { } public void stopAu(ArchivalUnit au) { // Is there any reason to notify the AU itself? aus.remove(au); } /** * Default implementation collects keys from titleConfigMap. * @return a List */ public List getSupportedTitles() { if (titleConfigMap == null) { return Collections.EMPTY_LIST; } return new ArrayList(titleConfigMap.keySet()); } /** * Default implementation looks in titleConfigMap. */ public TitleConfig getTitleConfig(String title) { if (titleConfigMap == null) { return null; } return (TitleConfig)titleConfigMap.get(title); } /** Set up our titleConfigMap from the title definitions in the * Configuration. Each title config looks like:<pre> * org.lockss.title.uid.title=Sample Title * org.lockss.title.uid.plugin=org.lockss.plugin.sample.SamplePlugin * org.lockss.title.uid.param.1.key=base_url * org.lockss.title.uid.param.1.value=http\://sample.org/ * org.lockss.title.uid.param.2.key=year * org.lockss.title.uid.param.2.value=2003 * org.lockss.title.uid.param.2.editable=true</pre> where * <code>uid</code> is an identifier that is unique for each title. * Parameters for which <code>editable</code> is true (<i>eg</i>, * <code>year</code>) may be edited by the user to select a related AU. * <br>See TitleParams (and test/scripts/title-params) for an easy way to * create these property files. */ protected void setConfig(Configuration newConfig, Configuration prevConfig, Configuration.Differences changedKeys) { if (changedKeys.contains(PARAM_TITLE_DB)) { setTitleConfig(newConfig); } } private void setTitleConfig(Configuration config) { String myName = getPluginId(); Map titleMap = new HashMap(); Collection myTitles = config.getTitleConfigs(myName); if (myTitles != null) { for (Iterator iter = myTitles.iterator(); iter.hasNext(); ) { Configuration titleConfig = (Configuration)iter.next(); String pluginName = titleConfig.get(TITLE_PARAM_PLUGIN); if (myName.equals(pluginName)) { if (log.isDebug2()) { log.debug2("my titleConfig: " + titleConfig); } String title = titleConfig.get(TITLE_PARAM_TITLE); TitleConfig tc = initOneTitle(titleConfig); titleMap.put(title, tc); } else { if (log.isDebug3()) { log.debug3("titleConfig: " + titleConfig); } } } } //TODO: decide on how to support plug-ins which do not use the title registry if (!titleMap.isEmpty()) { setTitleConfigMap(titleMap); notifyAusTitleDbChanged(); } } TitleConfig initOneTitle(Configuration titleConfig) { String title = titleConfig.get(TITLE_PARAM_TITLE); TitleConfig tc = new TitleConfig(title, this); tc.setPluginVersion(titleConfig.get(TITLE_PARAM_PLUGIN_VERSION)); tc.setJournalTitle(titleConfig.get(TITLE_PARAM_JOURNAL)); if (titleConfig.containsKey(TITLE_PARAM_EST_SIZE)) { tc.setEstimatedSize(titleConfig.getSize(TITLE_PARAM_EST_SIZE, 0)); } Configuration attrs = titleConfig.getConfigTree(TITLE_PARAM_ATTRIBUTES); if (!attrs.isEmpty()) { Map attrMap = new HashMap(); for (Iterator iter = attrs.nodeIterator(); iter.hasNext(); ) { String attr = (String)iter.next(); String val = attrs.get(attr); attrMap.put(attr, val); } tc.setAttributes(attrMap); } List params = new ArrayList(); Configuration allParams = titleConfig.getConfigTree(TITLE_PARAM_PARAM); for (Iterator iter = allParams.nodeIterator(); iter.hasNext(); ) { Configuration oneParam = allParams.getConfigTree((String)iter.next()); String key = oneParam.get(TITLE_PARAM_PARAM_KEY); String val = oneParam.get(TITLE_PARAM_PARAM_VALUE); ConfigParamDescr descr = findParamDescr(key); if (descr != null) { ConfigParamAssignment cpa = new ConfigParamAssignment(descr, val); if (oneParam.containsKey(TITLE_PARAM_PARAM_EDITABLE)) { cpa.setEditable(oneParam.getBoolean(TITLE_PARAM_PARAM_EDITABLE, cpa.isEditable())); } params.add(cpa); } else { log.warning("Unknown parameter key: " + key + " in title: " + title); log.debug(" title config: " + titleConfig); } } tc.setParams(params); return tc; } protected void setTitleConfigMap(Map titleConfigMap) { this.titleConfigMap = titleConfigMap; pluginMgr.resetTitles(); } protected void notifyAusTitleDbChanged() { for (Iterator iter = getAllAus().iterator(); iter.hasNext(); ) { // They should all be BaseArchivalUnits, but just in case... try { BaseArchivalUnit au = (BaseArchivalUnit)iter.next(); au.titleDbChanged(); } catch (Exception e) { log.warning("notifyAusTitleDbChanged: " + this, e); } } } public List getAuConfigDescrs() { List res = new ArrayList(getLocalAuConfigDescrs()); if (res.isEmpty()) { // Don't add internal params if plugin has no params. (testing) return res; } res.add(ConfigParamDescr.AU_CLOSED); res.add(ConfigParamDescr.PUB_DOWN); res.add(ConfigParamDescr.PROTOCOL_VERSION); return res; } abstract protected List getLocalAuConfigDescrs(); /** * Find the ConfigParamDescr that this plugin uses for the specified key. * @return the element of {@link #getAuConfigDescrs()} whose key * matches <code>key</code>, or null if none. */ protected ConfigParamDescr findParamDescr(String key) { List descrs = getAuConfigDescrs(); for (Iterator iter = descrs.iterator(); iter.hasNext(); ) { ConfigParamDescr descr = (ConfigParamDescr)iter.next(); if (descr.getKey().equals(key)) { return descr; } } return null; } // for now use the plugin's class name // tk - this will have to change to account for versioning public String getPluginId() { return this.getClass().getName(); } public Collection getAllAus() { if (log.isDebug2()) log.debug2("getAllAus: aus: " + aus); return aus; } public ArchivalUnit configureAu(Configuration config, ArchivalUnit au) throws ArchivalUnit.ConfigurationException { if(config == null) { throw new ArchivalUnit.ConfigurationException("Null Configuration"); } if (au != null) { au.setConfiguration(config); } else { au = createAu(config); aus.add(au); } return au; } /** * Return the LockssDaemon instance * @return the LockssDaemon instance */ public LockssDaemon getDaemon() { return theDaemon; } /** * return the CacheResultMap to use with this plugin * @return CacheResultMap */ public CacheResultMap getCacheResultMap() { return resultMap; } protected void initResultMap() { resultMap = new HttpResultMap(); } }
package org.myrobotlab.service; import org.myrobotlab.framework.Peers; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.Status; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.LeapMotion2.LeapData; import org.myrobotlab.service.interfaces.LeapDataListener; import org.slf4j.Logger; public class InMoovHand extends Service implements LeapDataListener { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(InMoovHand.class); /** * peer services */ transient public LeapMotion2 leap; transient public Servo thumb; transient public Servo index; transient public Servo majeure; transient public Servo ringFinger; transient public Servo pinky; transient public Servo wrist; transient public Arduino arduino; private String side; // static in Java are not overloaded but overwritten - there is no // polymorphism for statics public static Peers getPeers(String name) { Peers peers = new Peers(name); peers.put("thumb", "Servo", "Thumb servo"); peers.put("index", "Servo", "Index servo"); peers.put("majeure", "Servo", "Majeure servo"); peers.put("ringFinger", "Servo", "RingFinger servo"); peers.put("pinky", "Servo", "Pinky servo"); peers.put("wrist", "Servo", "Wrist servo"); peers.put("arduino", "Arduino", "Arduino controller for this arm"); peers.put("leap", "LeapMotion2", "Leap Motion Service"); // peers.put("keyboard", "Keyboard", "Keyboard control"); // peers.put("xmpp", "XMPP", "XMPP control"); return peers; } public InMoovHand(String n) { super(n); thumb = (Servo) createPeer("thumb"); index = (Servo) createPeer("index"); majeure = (Servo) createPeer("majeure"); ringFinger = (Servo) createPeer("ringFinger"); pinky = (Servo) createPeer("pinky"); wrist = (Servo) createPeer("wrist"); arduino = (Arduino) createPeer("arduino"); thumb.setRest(2); index.setRest(2); majeure.setRest(2); ringFinger.setRest(2); pinky.setRest(2); wrist.setRest(90); // connection details thumb.setPin(2); index.setPin(3); majeure.setPin(4); ringFinger.setPin(5); pinky.setPin(6); wrist.setPin(7); thumb.setController(arduino); index.setController(arduino); majeure.setController(arduino); ringFinger.setController(arduino); pinky.setController(arduino); wrist.setController(arduino); } // FIXME make // .isValidToStart() !!! < check all user data !!! @Override public void startService() { super.startService(); thumb.startService(); index.startService(); majeure.startService(); ringFinger.startService(); pinky.startService(); wrist.startService(); arduino.startService(); } // FIXME FIXME - this method must be called // user data needed /** * connect - user data needed * * @param port * @return */ public boolean connect(String port) { startService(); if (arduino == null) { error("arduino is invalid"); return false; } arduino.connect(port); if (!arduino.isConnected()) { error("arduino %s not connected", arduino.getName()); return false; } attach(); setSpeed(0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f); rest(); sleep(2000); setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); broadcastState(); return true; } /** * attach all the servos - this must be re-entrant and accomplish the * re-attachment when servos are detached * * @return */ public boolean attach() { sleep(InMoov.attachPauseMs); thumb.attach(); sleep(InMoov.attachPauseMs); index.attach(); sleep(InMoov.attachPauseMs); majeure.attach(); sleep(InMoov.attachPauseMs); ringFinger.attach(); sleep(InMoov.attachPauseMs); pinky.attach(); sleep(InMoov.attachPauseMs); wrist.attach(); return true; } public void startLeapTracking() { if (leap == null) { leap = (LeapMotion2) startPeer("leap");} this.index.map(90,0,this.index.getMin(),this.index.getMax()); this.thumb.map(90,50,this.thumb.getMin(),this.thumb.getMax()); this.majeure.map(90,0,this.majeure.getMin(),this.majeure.getMax()); this.ringFinger.map(90,0,this.ringFinger.getMin(),this.ringFinger.getMax()); this.pinky.map(90,0,this.pinky.getMin(),this.pinky.getMax()); leap.addLeapDataListener(this); leap.startTracking(); return; } public void stopLeapTracking() { leap.stopTracking(); this.index.map(this.index.getMin(),this.index.getMax(),this.index.getMin(),this.index.getMax()); this.thumb.map(this.thumb.getMin(),this.thumb.getMax(),this.thumb.getMin(),this.thumb.getMax()); this.majeure.map(this.majeure.getMin(),this.majeure.getMax(),this.majeure.getMin(),this.majeure.getMax()); this.ringFinger.map(this.ringFinger.getMin(),this.ringFinger.getMax(),this.ringFinger.getMin(),this.ringFinger.getMax()); this.pinky.map(this.pinky.getMin(),this.pinky.getMax(),this.pinky.getMin(),this.pinky.getMax()); this.rest(); return; } @Override public String getDescription() { return "hand service for inmoov"; } // TODO - waving thread fun public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky) { moveTo(thumb, index, majeure, ringFinger, pinky, null); } public void moveTo(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { if (log.isDebugEnabled()) { log.debug(String.format("%s.moveTo %d %d %d %d %d %d", getName(), thumb, index, majeure, ringFinger, pinky, wrist)); } this.thumb.moveTo(thumb); this.index.moveTo(index); this.majeure.moveTo(majeure); this.ringFinger.moveTo(ringFinger); this.pinky.moveTo(pinky); if (wrist != null) this.wrist.moveTo(wrist); } public void rest() { // initial positions setSpeed(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); thumb.rest(); index.rest(); majeure.rest(); ringFinger.rest(); pinky.rest(); wrist.rest(); } public void broadcastState() { // notify the gui thumb.broadcastState(); index.broadcastState(); majeure.broadcastState(); ringFinger.broadcastState(); pinky.broadcastState(); wrist.broadcastState(); } public void detach() { thumb.detach(); sleep(InMoov.attachPauseMs); index.detach(); sleep(InMoov.attachPauseMs); majeure.detach(); sleep(InMoov.attachPauseMs); ringFinger.detach(); sleep(InMoov.attachPauseMs); pinky.detach(); sleep(InMoov.attachPauseMs); wrist.detach(); } public void release() { detach(); thumb.releaseService(); index.releaseService(); majeure.releaseService(); ringFinger.releaseService(); pinky.releaseService(); wrist.releaseService(); } public void setSpeed(Float thumb, Float index, Float majeure, Float ringFinger, Float pinky, Float wrist) { this.thumb.setSpeed(thumb); this.index.setSpeed(index); this.majeure.setSpeed(majeure); this.ringFinger.setSpeed(ringFinger); this.pinky.setSpeed(pinky); this.wrist.setSpeed(wrist); } public void victory() { moveTo(150, 0, 0, 180, 180, 90); } public void devilHorns() { moveTo(150, 0, 180, 180, 0, 90); } public void hangTen() { moveTo(0, 180, 180, 180, 0, 90); } public void bird() { moveTo(150, 180, 0, 180, 180, 90); } public void thumbsUp() { moveTo(0, 180, 180, 180, 180, 90); } public void ok() { moveTo(150, 180, 0, 0, 0, 90); } public void one() { moveTo(150, 0, 180, 180, 180, 90); } public void two() { victory(); } public void three() { moveTo(150, 0, 0, 0, 180, 90); } public void four() { moveTo(150, 0, 0, 0, 0, 90); } public void five() { open(); } public void count() { one(); sleep(1); two(); sleep(1); three(); sleep(1); four(); sleep(1); five(); } public String getScript(String inMoovServiceName) { return String.format("%s.moveHand(\"%s\",%d,%d,%d,%d,%d,%d)\n", inMoovServiceName, side, thumb.getPos(), index.getPos(), majeure.getPos(), ringFinger.getPos(), pinky.getPos(), wrist.getPos()); } public void setPins(int thumb, int index, int majeure, int ringFinger, int pinky, int wrist) { log.info(String.format("setPins %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setPin(thumb); this.index.setPin(index); this.majeure.setPin(majeure); this.ringFinger.setPin(ringFinger); this.pinky.setPin(pinky); this.wrist.setPin(wrist); } public void close() { moveTo(130, 180, 180, 180, 180); } public void open() { rest(); } public void openPinch() { moveTo(0, 0, 180, 180, 180); } public void closePinch() { moveTo(130, 140, 180, 180, 180); } public Status test() { Status status = Status.info("starting %s %s test", getName(), getType()); try { if (arduino == null) { // gson encoding prevents this throw new Exception("arduino is null"); } if (!arduino.isConnected()) { throw new Exception("arduino not connected"); } thumb.moveTo(thumb.getPos() + 2); index.moveTo(index.getPos() + 2); majeure.moveTo(majeure.getPos() + 2); ringFinger.moveTo(ringFinger.getPos() + 2); pinky.moveTo(pinky.getPos() + 2); wrist.moveTo(wrist.getPos() + 2); } catch (Exception e) { status.addError(e); } status.addInfo("test completed"); return status; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); InMoovHand rightHand = new InMoovHand("r01"); Runtime.createAndStart("gui", "GUIService"); rightHand.connect("COM12"); rightHand.startService(); Runtime.createAndStart("webgui", "WebGUI"); // rightHand.connect("COM12"); TEST RECOVERY !!! rightHand.close(); rightHand.open(); rightHand.openPinch(); rightHand.closePinch(); rightHand.rest(); /* * GUIService gui = new GUIService("gui"); gui.startService(); */ } public void setSide(String side) { this.side = side; } public String getSide() { return side; } public long getLastActivityTime() { long lastActivityTime = Math.max(index.getLastActivityTime(), thumb.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, index.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, majeure.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, ringFinger.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, pinky.getLastActivityTime()); lastActivityTime = Math.max(lastActivityTime, wrist.getLastActivityTime()); return lastActivityTime; } public boolean isAttached() { boolean attached = false; attached |= thumb.isAttached(); attached |= index.isAttached(); attached |= majeure.isAttached(); attached |= ringFinger.isAttached(); attached |= pinky.isAttached(); attached |= wrist.isAttached(); return attached; } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky){ setRest(thumb, index, majeure, ringFinger, pinky, null); } public void setRest(int thumb, int index, int majeure, int ringFinger, int pinky, Integer wrist) { log.info(String.format("setRest %d %d %d %d %d %d", thumb, index, majeure, ringFinger, pinky, wrist)); this.thumb.setRest(thumb); this.index.setRest(index); this.majeure.setRest(majeure); this.ringFinger.setRest(ringFinger); this.pinky.setRest(pinky); if (wrist != null){ this.wrist.setRest(wrist); } } public void map(int minX, int maxX, int minY, int maxY){ thumb.map(minX, maxX, minY, maxY); index.map(minX, maxX, minY, maxY); majeure.map(minX, maxX, minY, maxY); ringFinger.map(minX, maxX, minY, maxY); pinky.map(minX, maxX, minY, maxY); } public boolean save(){ super.save(); thumb.save(); index.save(); majeure.save(); ringFinger.save(); pinky.save(); wrist.save(); return true; } @Override public LeapData onLeapData(LeapData data) { //if (this.getSide() == "right") { //System.out.println(data.frame.hands().rightmost().isValid()); //System.out.println(data.frame.hands().rightmost().confidence()); if (data.frame.hands().rightmost().isValid() == true) { index.moveTo(data.rightHand.index); thumb.moveTo(data.rightHand.thumb); pinky.moveTo(data.rightHand.pinky); ringFinger.moveTo(data.rightHand.ring); majeure.moveTo(data.rightHand.middle); } return data; } }
package org.nutz.ioc.impl; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.nutz.ioc.IocEventTrigger; import org.nutz.ioc.IocException; import org.nutz.ioc.IocMaking; import org.nutz.ioc.ObjectMaker; import org.nutz.ioc.ObjectProxy; import org.nutz.ioc.ValueProxy; import org.nutz.ioc.meta.IocEventSet; import org.nutz.ioc.meta.IocField; import org.nutz.ioc.meta.IocObject; import org.nutz.ioc.weaver.DefaultWeaver; import org.nutz.ioc.weaver.FieldInjector; import org.nutz.lang.Lang; import org.nutz.lang.Mirror; import org.nutz.lang.Strings; import org.nutz.lang.born.Borning; import org.nutz.lang.born.MethodBorning; import org.nutz.lang.born.MethodCastingBorning; import org.nutz.lang.reflect.FastClassFactory; import org.nutz.lang.reflect.FastMethod; /** * AOP * * @author zozoh(zozohtnt@gmail.com) * @author wendal(wendal1985@gmail.com) */ public class ObjectMakerImpl implements ObjectMaker { public ObjectProxy make(final IocMaking ing, IocObject iobj) { IocEventSet iocEventSet = iobj.getEvents(); // singleton // null ObjectProxy op = new ObjectProxy(); if (iobj.isSingleton() && null != ing.getObjectName()) ing.getContext().save(iobj.getScope(), ing.getObjectName(), op); try { DefaultWeaver dw = new DefaultWeaver(); op.setWeaver(dw); ValueProxy[] vps = new ValueProxy[Lang.eleSize(iobj.getArgs())]; for (int i = 0; i < vps.length; i++) vps[i] = ing.makeValue(iobj.getArgs()[i]); dw.setArgs(vps); Object[] args = new Object[vps.length]; boolean hasNullArg = false; for (int i = 0; i < args.length; i++) { args[i] = vps[i].get(ing); if (args[i] == null) { hasNullArg = true; } } // Mirror AOP Mirror<?> mirror = null; if (iobj.getFactory() != null) { // factory, # $iocbean# final String[] ss = iobj.getFactory().split(" if (ss[0].startsWith("$")) { dw.setBorning(new Borning<Object>() { public Object born(Object... args) { Object factoryBean = ing.getIoc().get(null, ss[0].substring(1)); return Mirror.me(factoryBean).invoke(factoryBean, ss[1], args); } }); } else { Mirror<?> mi = Mirror.me(Lang.loadClass(ss[0])); Method m; if (hasNullArg) { m = (Method) Lang.first(mi.findMethods(ss[1],args.length)); if (m == null) throw new IocException(ing.getObjectName(), "Factory method not found --> ", iobj.getFactory()); dw.setBorning(new MethodCastingBorning<Object>(m)); } else { m = mi.findMethod(ss[1], args); dw.setBorning(new MethodBorning<Object>(m)); } if (iobj.getType() == null) iobj.setType(m.getReturnType()); } if (iobj.getType() != null) mirror = ing.getMirrors().getMirror(iobj.getType(), ing.getObjectName()); } else { mirror = ing.getMirrors().getMirror(iobj.getType(), ing.getObjectName()); dw.setBorning((Borning<?>) mirror.getBorning(args)); } if (null != iobj.getEvents()) { op.setFetch(createTrigger(mirror, iocEventSet.getFetch())); op.setDepose(createTrigger(mirror, iocEventSet.getDepose())); dw.setCreate(createTrigger(mirror, iocEventSet.getCreate())); } Object obj = null; if (iobj.isSingleton()) { obj = dw.born(ing); op.setObj(obj); } List<IocField> _fields = new ArrayList<IocField>(iobj.getFields().values()); FieldInjector[] fields = new FieldInjector[_fields.size()]; for (int i = 0; i < fields.length; i++) { IocField ifld = _fields.get(i); try { ValueProxy vp = ing.makeValue(ifld.getValue()); fields[i] = FieldInjector.create(mirror, ifld.getName(), vp, ifld.isOptional()); } catch (Exception e) { throw Lang.wrapThrow(e, "Fail to eval Injector for field: '%s'", ifld.getName()); } } dw.setFields(fields); if (null != obj) dw.fill(ing, obj); // create dw.onCreate(obj); } catch (IocException e) { ing.getContext().remove(iobj.getScope(), ing.getObjectName()); ((IocException)e).addBeanNames(ing.getObjectName()); throw e; } // context ObjectProxy catch (Throwable e) { ing.getContext().remove(iobj.getScope(), ing.getObjectName()); throw new IocException(ing.getObjectName(), e, "throw Exception when creating"); } return op; } @SuppressWarnings({"unchecked"}) private static IocEventTrigger<Object> createTrigger(Mirror<?> mirror, final String str) { if (Strings.isBlank(str)) return null; if (str.contains(".")) { try { return (IocEventTrigger<Object>) Mirror.me(Lang.loadClass(str)) .born(); } catch (Exception e) { throw Lang.wrapThrow(e); } } return new IocEventTrigger<Object>() { protected FastMethod fm; public void trigger(Object obj) { try { if (fm == null) { Method method = Mirror.me(obj).findMethod(str); fm = FastClassFactory.get(method); } fm.invoke(obj); } catch (Exception e) { throw Lang.wrapThrow(e); } } }; } }
package org.objectweb.proactive; import org.apache.log4j.Logger; import org.objectweb.fractal.api.Component; import org.objectweb.fractal.api.NoSuchInterfaceException; import org.objectweb.fractal.api.factory.GenericFactory; import org.objectweb.fractal.api.factory.InstantiationException; import org.objectweb.fractal.util.Fractal; import org.objectweb.proactive.core.Constants; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.body.ActiveBody; import org.objectweb.proactive.core.body.LocalBodyStore; import org.objectweb.proactive.core.body.MetaObjectFactory; import org.objectweb.proactive.core.body.ProActiveMetaObjectFactory; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.future.Future; import org.objectweb.proactive.core.body.future.FuturePool; import org.objectweb.proactive.core.body.ibis.IbisRemoteBodyAdapter; import org.objectweb.proactive.core.body.migration.Migratable; import org.objectweb.proactive.core.body.migration.MigrationException; import org.objectweb.proactive.core.body.proxy.AbstractProxy; import org.objectweb.proactive.core.body.proxy.BodyProxy; import org.objectweb.proactive.core.body.request.BodyRequest; import org.objectweb.proactive.core.body.rmi.RemoteBodyAdapter; import org.objectweb.proactive.core.component.ComponentParameters; import org.objectweb.proactive.core.component.ContentDescription; import org.objectweb.proactive.core.component.ControllerDescription; import org.objectweb.proactive.core.config.ProActiveConfiguration; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.descriptor.data.VirtualNodeImpl; import org.objectweb.proactive.core.descriptor.xml.ProActiveDescriptorHandler; import org.objectweb.proactive.core.exceptions.NonFunctionalException; import org.objectweb.proactive.core.exceptions.handler.Handler; import org.objectweb.proactive.core.exceptions.handler.HandlerNonFunctionalException; import org.objectweb.proactive.core.group.Group; import org.objectweb.proactive.core.group.ProActiveGroup; import org.objectweb.proactive.core.mop.ClassNotReifiableException; import org.objectweb.proactive.core.mop.ConstructionOfProxyObjectFailedException; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.mop.MOPException; import org.objectweb.proactive.core.mop.StubObject; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.runtime.ProActiveRuntime; import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl; import org.objectweb.proactive.core.runtime.RuntimeFactory; import org.objectweb.proactive.core.util.UrlBuilder; import java.net.UnknownHostException; import java.util.HashMap; public class ProActive { protected static Logger logger = Logger.getLogger(ProActive.class.getName()); /** * This level is used for default handlers */ static public HashMap defaultLevel = null; /** * VM level provides different strategies according to the virtual machine */ static public HashMap VMLevel = null; /** * Code level is used for temporary handlers */ static public HashMap codeLevel = null; static { ProActiveConfiguration.load(); Class c = org.objectweb.proactive.core.runtime.RuntimeFactory.class; // Creation of the default level which contains standard exception handlers defaultLevel = new HashMap(); // We add handler to default level if (logger.isDebugEnabled()) { } setExceptionHandler(HandlerNonFunctionalException.class, NonFunctionalException.class, Handler.ID_Default, null); //ProActiveConfiguration.load(); } private ProActive() { } /** * Creates a new ActiveObject based on classname attached to a default node in the local JVM. * @param classname the name of the class to instanciate as active * @param constructorParameters the parameters of the constructor. * @return a reference (possibly remote) on a Stub of the newly created active object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the DefaultNode cannot be created */ public static Object newActive(String classname, Object[] constructorParameters) throws ActiveObjectCreationException, NodeException { // avoid ambiguity for method parameters types Node nullNode = null; return newActive(classname, constructorParameters, nullNode, null, null); } /** * Creates a new ActiveObject based on classname attached to the node of the given URL. * @param classname the name of the class to instanciate as active * @param constructorParameters the parameters of the constructor. * @param nodeURL the URL of the node where to create the active object. If null, the active object * is created localy on a default node * @return a reference (possibly remote) on a Stub of the newly created active object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node URL cannot be resolved as an existing Node */ public static Object newActive(String classname, Object[] constructorParameters, String nodeURL) throws ActiveObjectCreationException, NodeException { if (nodeURL == null) { // avoid ambiguity for method parameters types Node nullNode = null; return newActive(classname, constructorParameters, nullNode, null, null); } else { return newActive(classname, constructorParameters, NodeFactory.getNode(nodeURL), null, null); } } /** * Creates a new ActiveObject based on classname attached to the given node or on * a default node in the local JVM if the given node is null. * @param classname the name of the class to instanciate as active * @param constructorParameters the parameters of the constructor. * @param node the possibly null node where to create the active object. * @return a reference (possibly remote) on a Stub of the newly created active object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object newActive(String classname, Object[] constructorParameters, Node node) throws ActiveObjectCreationException, NodeException { return newActive(classname, constructorParameters, node, null, null); } /** * Creates a new ActiveObject based on classname attached to the given node or on * a default node in the local JVM if the given node is null. * The object returned is a stub class that extends the target class and that is automatically * generated on the fly. The Stub class reference a the proxy object that reference the body * of the active object. The body referenced by the proxy can either be local of remote, * depending or the respective location of the object calling the newActive and the active object * itself. * @param classname the name of the class to instanciate as active * @param constructorParameters the parameters of the constructor of the object * to instantiate as active. If some parameters are primitive types, the wrapper * class types should be given here. null can be used to specify that no parameter * are passed to the constructor. * @param node the possibly null node where to create the active object. If null, the active object * is created localy on a default node * @param activity the possibly null activity object defining the different step in the activity of the object. * see the definition of the activity in the javadoc of this classe for more information. * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the * body associated to the reified object. If null the default ProActive MataObject factory is used. * @return a reference (possibly remote) on a Stub of the newly created active object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object newActive(String classname, Object[] constructorParameters, Node node, Active activity, MetaObjectFactory factory) throws ActiveObjectCreationException, NodeException { //using default proactive node if (node == null) { node = NodeFactory.getDefaultNode(); } if (factory == null) { factory = ProActiveMetaObjectFactory.newInstance(); } try { return createStubObject(classname, constructorParameters, node, activity, factory); } catch (MOPException e) { Throwable t = e; if (e.getTargetException() != null) { t = e.getTargetException(); } throw new ActiveObjectCreationException(t); } } /** * Creates a new set of active objects based on classname attached to the given virtualnode. * @param classname classname the name of the class to instanciate as active * @param constructorParameters constructorParameters the parameters of the constructor. * @param virtualnode The virtualnode where to create active objects. Active objects will be created * on each node mapped to the given virtualnode in XML deployment descriptor. * @return Object a Group of references (possibly remote) on Stub of newly created active objects * @throws ActiveObjectCreationException if a problem occur while creating the stub or the body * @throws NodeException if the virtualnode was null */ public static Object newActive(String classname, Object[] constructorParameters, VirtualNode virtualnode) throws ActiveObjectCreationException, NodeException { return ProActive.newActive(classname, constructorParameters, virtualnode, null, null); } /** * Creates a new ActiveObject based on classname attached to the given virtualnode. * @param classname classname the name of the class to instanciate as active * @param constructorParameters constructorParameters the parameters of the constructor. * @param virtualnode The virtualnode where to create active objects. Active objects will be created * on each node mapped to the given virtualnode in XML deployment descriptor. * @param activity the possibly null activity object defining the different step in the activity of the object. * see the definition of the activity in the javadoc of this classe for more information. * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the * body associated to the reified object. If null the default ProActive MataObject factory is used. * @return Object a Group of references (possibly remote) on Stub of newly created active objects * @throws ActiveObjectCreationException if a problem occur while creating the stub or the body * @throws NodeException if the virtualnode was null * */ public static Object newActive(String classname, Object[] constructorParameters, VirtualNode virtualnode, Active activity, MetaObjectFactory factory) throws ActiveObjectCreationException, NodeException { if (virtualnode != null) { if (!virtualnode.isActivated()) { virtualnode.activate(); } Node[] nodeTab = virtualnode.getNodes(); Group aoGroup = null; try { aoGroup = ProActiveGroup.getGroup(ProActiveGroup.newGroup( classname)); } catch (ClassNotFoundException e) { throw new ActiveObjectCreationException( "Cannot create group of active objects" + e); } catch (ClassNotReifiableException e) { throw new ActiveObjectCreationException( "Cannot create group of active objects" + e); } for (int i = 0; i < nodeTab.length; i++) { Object tmp = newActive(classname, constructorParameters, (Node) nodeTab[i], activity, factory); aoGroup.add(tmp); } return aoGroup.getGroupByType(); } else { throw new NodeException( "VirtualNode is null, unable to activate the object"); } } /** * Creates a new ProActive component over the specified base class, according to the * given component parameters, and returns a reference on the component of type Component. * A reference on the active object base class can be retreived through the component parameters controller's * method "getStubOnReifiedObject". * * @param classname the name of the base class. "Composite" if the component is a composite, * "ParallelComposite" if the component is a parallel composite component * @param constructorParameters the parameters of the constructor of the object * to instantiate as active. If some parameters are primitive types, the wrapper * class types should be given here. null can be used to specify that no parameter * are passed to the constructor. * @param node the possibly null node where to create the active object. If null, the active object * is created localy on a default node * @param activity the possibly null activity object defining the different step in the activity of the object. * see the definition of the activity in the javadoc of this classe for more information. * @param factory should be null for components (automatically created) * @param componentParameters the parameters of the component * @return a component representative of type Component * @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Component newActiveComponent(String classname, Object[] constructorParameters, Node node, Active activity, MetaObjectFactory factory, ComponentParameters componentParameters) throws ActiveObjectCreationException, NodeException { // COMPONENTS try { Component boot = Fractal.getBootstrapComponent(); GenericFactory cf = Fractal.getGenericFactory(boot); return cf.newFcInstance(componentParameters.getComponentType(), new ControllerDescription(componentParameters.getName(), componentParameters.getHierarchicalType()), new ContentDescription(classname, constructorParameters, node, activity, factory)); } catch (NoSuchInterfaceException e) { throw new ActiveObjectCreationException(e); } catch (InstantiationException e) { if (e.getCause() instanceof NodeException) { throw new NodeException(e); } else { throw new ActiveObjectCreationException(e); } } } /** * Creates a new ProActive component over the specified base class, according to the * given component parameters, and returns a reference on the component of type Component. * * This method allows automatic of primitive components on Virtual Nodes. In that case, the appendix * -cyclicInstanceNumber-<b><i>number</i></b> is added to the name of each of these components. * If the component is not a primitive, only one instance of the component is created, on the first node * retreived from the specified virtual node. * * A reference on the active object base class can be retreived through the component parameters controller's * method "getStubOnReifiedObject". * * @param classname the name of the base class. "Composite" if the component is a composite, * "ParallelComposite" if the component is a parallel composite component * @param constructorParameters the parameters of the constructor of the object * to instantiate as active. If some parameters are primitive types, the wrapper * class types should be given here. null can be used to specify that no parameter * are passed to the constructor. * @param node the possibly null node where to create the active object. If null, the active object * is created localy on a default node * @param activity the possibly null activity object defining the different step in the activity of the object. * see the definition of the activity in the javadoc of this class for more information. * @param factory should be null for components (automatically created) * @param componentParameters the parameters of the component * @return a typed group of component representative elements, of type Component * @exception ActiveObjectCreationException if a problem occurs while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Component newActiveComponent(String className, Object[] constructorParameters, VirtualNode vn, ComponentParameters componentParameters) throws ActiveObjectCreationException, NodeException { // COMPONENTS try { Component boot = Fractal.getBootstrapComponent(); GenericFactory cf = Fractal.getGenericFactory(boot); return cf.newFcInstance(componentParameters.getComponentType(), new ControllerDescription(componentParameters.getName(), componentParameters.getHierarchicalType()), new ContentDescription(className, constructorParameters, vn)); } catch (NoSuchInterfaceException e) { throw new ActiveObjectCreationException(e); } catch (InstantiationException e) { if (e.getCause() instanceof NodeException) { throw new NodeException(e); } else { throw new ActiveObjectCreationException(e); } } } /** * Turns the target object into an ActiveObject attached to a default node in the local JVM. * The type of the stub is is the type of the existing object. * @param target The object to turn active * @return a reference (possibly remote) on a Stub of the existing object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the DefaultNode cannot be created */ public static Object turnActive(Object target) throws ActiveObjectCreationException, NodeException { return turnActive(target, (Node) null); } /** * Turns the target object into an Active Object and send it to the Node * identified by the given url. * The type of the stub is is the type of the existing object. * @param target The object to turn active * @param nodeURL the URL of the node where to create the active object on. If null, the active object * is created localy on a default node * @return a reference (possibly remote) on a Stub of the existing object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object turnActive(Object target, String nodeURL) throws ActiveObjectCreationException, NodeException { if (nodeURL == null) { return turnActive(target, target.getClass().getName(), null, null, null); } else { return turnActive(target, target.getClass().getName(), NodeFactory.getNode(nodeURL), null, null); } } /** * Turns the target object into an Active Object and send it to the given Node * or to a default node in the local JVM if the given node is null. * The type of the stub is is the type of the target object. * @param target The object to turn active * @param node The Node the object should be sent to or null to create the active * object in the local JVM * @return a reference (possibly remote) on a Stub of the target object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object turnActive(Object target, Node node) throws ActiveObjectCreationException, NodeException { return turnActive(target, target.getClass().getName(), node, null, null); } /** * Turns the target object into an Active Object and send it to the given Node * or to a default node in the local JVM if the given node is null. * The type of the stub is is the type of the target object. * @param target The object to turn active * @param node The Node the object should be sent to or null to create the active * object in the local JVM * @param activity the possibly null activity object defining the different step in the activity of the object. * see the definition of the activity in the javadoc of this classe for more information. * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the * body associated to the reified object. If null the default ProActive MataObject factory is used. * @return a reference (possibly remote) on a Stub of the target object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object turnActive(Object target, Node node, Active activity, MetaObjectFactory factory) throws ActiveObjectCreationException, NodeException { return turnActive(target, target.getClass().getName(), node, activity, factory); } /** * Turns a Java object into an Active Object and send it to a remote Node or to a * local node if the given node is null. * The type of the stub is given by the parameter <code>nameOfTargetType</code>. * @param target The object to turn active * @param nameOfTargetType the fully qualified name of the type the stub class should * inherit from. That type can be less specific than the type of the target object. * @param node The Node the object should be sent to or null to create the active * object in the local JVM * @return a reference (possibly remote) on a Stub of the target object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object turnActive(Object target, String nameOfTargetType, Node node) throws ActiveObjectCreationException, NodeException { return turnActive(target, nameOfTargetType, node, null, null); } /** * Turns a Java object into an Active Object and send it to a remote Node or to a * local node if the given node is null. * The type of the stub is given by the parameter <code>nameOfTargetType</code>. * A Stub is dynamically generated for the existing object. The result of the call * will be an instance of the Stub class pointing to the proxy object pointing * to the body object pointing to the existing object. The body can be remote * or local depending if the existing is sent remotely or not. * @param target The object to turn active * @param nameOfTargetType the fully qualified name of the type the stub class should * inherit from. That type can be less specific than the type of the target object. * @param node The Node the object should be sent to or null to create the active * object in the local JVM * @param activity the possibly null activity object defining the different step in the activity of the object. * see the definition of the activity in the javadoc of this classe for more information. * @param factory the possibly null meta factory giving all factories for creating the meta-objects part of the * body associated to the reified object. If null the default ProActive MataObject factory is used. * @return a reference (possibly remote) on a Stub of the target object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object turnActive(Object target, String nameOfTargetType, Node node, Active activity, MetaObjectFactory factory) throws ActiveObjectCreationException, NodeException { if (node == null) { //using default proactive node node = NodeFactory.getDefaultNode(); } if (factory == null) { factory = ProActiveMetaObjectFactory.newInstance(); } try { return createStubObject(target, nameOfTargetType, node, activity, factory); } catch (MOPException e) { Throwable t = e; if (e.getTargetException() != null) { t = e.getTargetException(); } throw new ActiveObjectCreationException(t); } } /** * Turns a Java object into an Active Object and send it to remote Nodes mapped to the given virtualnode in * the XML deployment descriptor. * The type of the stub is given by the parameter <code>nameOfTargetType</code>. * @param target The object to turn active * @param nameOfTargetType the fully qualified name of the type the stub class should * inherit from. That type can be less specific than the type of the target object. * @param virtualnode The VirtualNode where the target object will be turn into an Active Object * Target object will be turned into an Active Object on each node mapped to the given virtualnode in XML deployment descriptor. * @return an array of references (possibly remote) on a Stub of the target object * @exception ActiveObjectCreationException if a problem occur while creating the stub or the body * @exception NodeException if the node was null and that the DefaultNode cannot be created */ public static Object turnActive(Object target, String nameOfTargetType, VirtualNode virtualnode) throws ActiveObjectCreationException, NodeException { if (virtualnode != null) { Node[] nodeTab = virtualnode.getNodes(); Group aoGroup = null; try { aoGroup = ProActiveGroup.getGroup(ProActiveGroup.newGroup( target.getClass().getName())); } catch (ClassNotFoundException e) { throw new ActiveObjectCreationException( "Cannot create group of active objects" + e); } catch (ClassNotReifiableException e) { throw new ActiveObjectCreationException( "Cannot create group of active objects" + e); } for (int i = 0; i < nodeTab.length; i++) { Object tmp = turnActive(target, nameOfTargetType, (Node) nodeTab[i], null, null); aoGroup.add(tmp); } return aoGroup; } else { throw new NodeException( "VirtualNode is null, unable to active the object"); } } /** * Registers an active object into a RMI registry. In fact it is the * remote version of the body of the active object that is registered into the * RMI Registry under the given URL. * @param obj the active object to register. * @param url the url under which the remote body is registered. * @exception java.io.IOException if the remote body cannot be registered */ public static void register(Object obj, String url) throws java.io.IOException { // Check if obj is really a reified object if (!(MOP.isReifiedObject(obj))) { throw new java.io.IOException("The given object " + obj + " is not a reified object"); } // Find the appropriate remoteBody org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy(); if (myProxy == null) { throw new java.io.IOException( "Cannot find a Proxy on the stub object: " + obj); } BodyProxy myBodyProxy = (BodyProxy) myProxy; UniversalBody body = myBodyProxy.getBody().getRemoteAdapter(); if (body instanceof RemoteBodyAdapter) { RemoteBodyAdapter.register((RemoteBodyAdapter) body, url); if (logger.isInfoEnabled()) { logger.info("Success at binding url " + url); } } else { if (body instanceof IbisRemoteBodyAdapter) { IbisRemoteBodyAdapter.register((IbisRemoteBodyAdapter) body, url); if (logger.isInfoEnabled()) { logger.info("Success at binding url " + url); } } else { throw new java.io.IOException( "Cannot reconize the type of this UniversalBody: " + body.getClass().getName()); } } } /** * Unregisters an active object previously registered into a RMI registry. * @param url the url under which the active object is registered. * @exception java.io.IOException if the remote object cannot be removed from the registry */ public static void unregister(String url) throws java.io.IOException { RemoteBodyAdapter.unregister(url); if (logger.isDebugEnabled()) { logger.debug("Success at unbinding url " + url); } } /** * Looks-up an active object previously registered in a RMI registry. In fact it is the * remote version of the body of an active object that can be registered into the * RMI Registry under a given URL. If the lookup is successful, the method reconstructs * a Stub-Proxy couple and point it to the RemoteBody found. * @param classname the fully qualified name of the class the stub should inherit from. * @param url the url under which the remote body is registered. * @return a remote reference on a Stub of type <code>classname</code> pointing to the * remote body found * @exception java.io.IOException if the remote body cannot be found under the given url * or if the object found is not of type RemoteBody * @exception ActiveObjectCreationException if the stub-proxy couple cannot be created */ public static Object lookupActive(String classname, String url) throws ActiveObjectCreationException, java.io.IOException { UniversalBody b = null; if ("ibis".equals(System.getProperty("proactive.communication.protocol"))) { b = IbisRemoteBodyAdapter.lookup(url); } else { b = RemoteBodyAdapter.lookup(url); } try { return createStubObject(classname, b); } catch (MOPException e) { Throwable t = e; if (e.getTargetException() != null) { t = e.getTargetException(); } throw new ActiveObjectCreationException("Exception occured when trying to create stub-proxy", t); } } /** * Blocks the calling thread until the object <code>future</code> * is available. <code>future</code> must be the result object of an * asynchronous call. Usually the the wait by necessity model take care * of blocking the caller thread asking for a result not yet available. * This method allows to block before the result is first used. */ public static void waitFor(Object future) { // If the object is not reified, it cannot be a future if ((MOP.isReifiedObject(future)) == false) { return; } else { org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy(); // If it is reified but its proxy is not of type future, we cannot wait if (!(theProxy instanceof Future)) { return; } else { ((Future) theProxy).waitFor(); } } } /** * Returns a <code>ProActiveDescriptor</code> that gives an object representation * of the XML document located at the given url. * @param xmlDescriptorUrl. The url of the XML document * @return ProActiveDescriptor. The object representation of the XML document * @throws ProActiveException if a problem occurs during the creation of the object * @see org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor * @see org.objectweb.proactive.core.descriptor.data.VirtualNode * @see org.objectweb.proactive.core.descriptor.data.VirtualMachine */ public static ProActiveDescriptor getProactiveDescriptor( String xmlDescriptorUrl) throws ProActiveException { RuntimeFactory.getDefaultRuntime(); if (!xmlDescriptorUrl.startsWith("file:")) { xmlDescriptorUrl = "file:" + xmlDescriptorUrl; } ProActiveRuntimeImpl part = (ProActiveRuntimeImpl) ProActiveRuntimeImpl.getProActiveRuntime(); if (part.getDescriptor(xmlDescriptorUrl) != null) { return part.getDescriptor(xmlDescriptorUrl); } try { if (logger.isInfoEnabled()) { logger.info("************* Reading deployment descriptor: " + xmlDescriptorUrl + " ********************"); } ProActiveDescriptorHandler proActiveDescriptorHandler = ProActiveDescriptorHandler.createProActiveDescriptor(xmlDescriptorUrl); ProActiveDescriptor pad = (ProActiveDescriptor) proActiveDescriptorHandler.getResultObject(); part.registerDescriptor(xmlDescriptorUrl, pad); return pad; } catch (org.xml.sax.SAXException e) { e.printStackTrace(); logger.fatal( "a problem occurs when getting the proActiveDescriptor"); throw new ProActiveException(e); } catch (java.io.IOException e) { e.printStackTrace(); logger.fatal( "a problem occurs during the ProActiveDescriptor object creation"); throw new ProActiveException(e); } } /** * Registers locally the given VirtualNode in a registry such RMIRegistry or JINI Lookup Service. * The VirtualNode to register must exist on the local runtime. This is done when using XML Deployment Descriptors * @param virtualNode the VirtualNode to register. * @param registrationProtocol The protocol used for registration. At this time RMI and JINI are supported * @param replacePreviousBinding * @throws ProActiveException If the VirtualNode with the given name does not exist on the local runtime */ public static void registerVirtualNode(VirtualNode virtualNode, String registrationProtocol, boolean replacePreviousBinding) throws ProActiveException { if (!(virtualNode instanceof VirtualNodeImpl)) { throw new ProActiveException( "Cannot register such virtualNode since it results from a lookup!"); } String virtualnodeName = virtualNode.getName(); ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(registrationProtocol); VirtualNode vn = part.getVirtualNode(virtualnodeName); if (vn == null) { throw new ProActiveException("VirtualNode " + virtualnodeName + " does not exist !"); } part.registerVirtualNode(UrlBuilder.appendVnSuffix(virtualnodeName), replacePreviousBinding); } /** * Looks-up a VirtualNode previously registered in a registry(RMI or JINI) * @param url The url where to perform the lookup * @param protocol The protocol used to perform the lookup(RMI and JINI are supported) * @return VirtualNode The virtualNode returned by the lookup * @throws ProActiveException If no objects are bound with the given url */ public static VirtualNode lookupVirtualNode(String url, String protocol) throws ProActiveException { ProActiveRuntime remoteProActiveRuntime = null; try { remoteProActiveRuntime = RuntimeFactory.getRuntime(UrlBuilder.buildVirtualNodeUrl( url), protocol); } catch (UnknownHostException ex) { throw new ProActiveException(ex); } return remoteProActiveRuntime.getVirtualNode(UrlBuilder.getNameFromUrl( url)); } /** * Unregisters the virtualNode previoulsy registered in a registry such as JINI or RMI. * Calling this method removes the VirtualNode from the local runtime. * @param virtualNode The VirtualNode to unregister * @throws ProActiveException if a problem occurs whle unregistering the VirtualNode */ public static void unregisterVirtualNode(VirtualNode virtualNode) throws ProActiveException { //VirtualNode vn = ((VirtualNodeStrategy)virtualNode).getVirtualNode(); if (!(virtualNode instanceof VirtualNodeImpl)) { throw new ProActiveException( "Cannot unregister such virtualNode since it results from a lookup!"); } String virtualNodeName = virtualNode.getName(); ProActiveRuntime part = RuntimeFactory.getProtocolSpecificRuntime(((VirtualNodeImpl) virtualNode).getRegistrationProtocol()); part.unregisterVirtualNode(UrlBuilder.appendVnSuffix( virtualNode.getName())); if (logger.isInfoEnabled()) { logger.info("Success at unbinding " + virtualNodeName); } } /** * When an active object is created, it is associated with a Body that takes care * of all non fonctionnal properties. Assuming that the active object is only * accessed by the different Stub objects, all method calls end-up as Requests sent * to this Body. Therefore the only thread calling the method of the active object * is the active thread managed by the body. There is an unique mapping between the * active thread and the body responsible for it. From any method in the active object * the current thread caller of the method is the active thread. When a reified method wants * to get a reference to the Body associated to the active object, it can invoke this * method. Assuming that the current thread is the active thread, the associated body * is returned. * @return the body associated to the active object whose active thread is calling * this method. */ public static Body getBodyOnThis() { return LocalBodyStore.getInstance().getCurrentThreadBody(); } /** * Returns a Stub-Proxy couple pointing to the local body associated to the active * object whose active thread is calling this method. * @return a Stub-Proxy couple pointing to the local body. * @see #getBodyOnThis */ public static StubObject getStubOnThis() { Body body = getBodyOnThis(); if (logger.isDebugEnabled()) { //logger.debug("ProActive: getStubOnThis() returns " + body); } if (body == null) { return null; } return getStubForBody(body); } /** * Migrates the active object whose active thread is calling this method to the * same location as the active object given in parameter. * This method must be called from an active object using the active thread as the * current thread will be used to find which active object is calling the method. * The object given as destination must be an active object. * @param activeObject the active object indicating the destination of the migration. * @exception MigrationException if the migration fails * @see #getBodyOnThis */ public static void migrateTo(Object activeObject) throws MigrationException { migrateTo(getNodeFromURL(getNodeURLFromActiveObject(activeObject))); } /** * Migrates the active object whose active thread is calling this method to the * node caracterized by the given url. * This method must be called from an active object using the active thread as the * current thread will be used to find which active object is calling the method. * The url must be the url of an existing node. * @param nodeURL the url of an existing where to migrate to. * @exception MigrationException if the migration fails * @see #getBodyOnThis */ public static void migrateTo(String nodeURL) throws MigrationException { if (logger.isDebugEnabled()) { logger.debug("migrateTo " + nodeURL); } ProActive.migrateTo(getNodeFromURL(nodeURL)); } /** * Migrates the active object whose active thread is calling this method to the * given node. * This method must be called from an active object using the active thread as the * current thread will be used to find which active object is calling the method. * @param node an existing node where to migrate to. * @exception MigrationException if the migration fails * @see #getBodyOnThis */ public static void migrateTo(Node node) throws MigrationException { if (logger.isDebugEnabled()) { logger.debug("migrateTo " + node); } Body bodyToMigrate = getBodyOnThis(); if (!(bodyToMigrate instanceof Migratable)) { throw new MigrationException( "This body cannot migrate. It doesn't implement Migratable interface"); } ((Migratable) bodyToMigrate).migrateTo(node); } /** * Migrates the given body to the same location as the active object given in parameter. * This method can be called from any object and does not perform the migration. * Instead it generates a migration request that is sent to the targeted body. * Two strategies are possible : * - the request is high priority and is processed before all existing requests * the body may have received (priority = true) * - the request is normal priority and is processed after all existing requests * the body may have received (priority = false) * The object given as destination must be an active object. * @param bodyToMigrate the body to migrate. * @param activeObject the active object indicating the destination of the migration. * @param priority a boolean indicating the priority of the migration request sent to the body. * @exception MigrationException if the migration fails */ public static void migrateTo(Body bodyToMigrate, Object activeObject, boolean priority) throws MigrationException { migrateTo(bodyToMigrate, getNodeFromURL(getNodeURLFromActiveObject(activeObject)), priority); } /** * Migrates the given body to the node caracterized by the given url. * This method can be called from any object and does not perform the migration. * Instead it generates a migration request that is sent to the targeted body. * Two strategies are possible : * - the request is high priority and is processed before all existing requests * the body may have received (priority = true) * - the request is normal priority and is processed after all existing requests * the body may have received (priority = false) * The object given as destination must be an active object. * @param bodyToMigrate the body to migrate. * @param nodeURL the url of an existing where to migrate to. * @param priority a boolean indicating the priority of the migration request sent to the body. * @exception MigrationException if the migration fails */ public static void migrateTo(Body bodyToMigrate, String nodeURL, boolean priority) throws MigrationException { ProActive.migrateTo(bodyToMigrate, getNodeFromURL(nodeURL), priority); } /** * Migrates the body <code>bodyToMigrate</code> to the given node. * This method can be called from any object and does not perform the migration. * Instead it generates a migration request that is sent to the targeted body. * Two strategies are possible : * - the request is high priority and is processed before all existing requests * the body may have received (priority = true) * - the request is normal priority and is processed after all existing requests * the body may have received (priority = false) * The object given as destination must be an active object. * @param bodyToMigrate the body to migrate. * @param node an existing node where to migrate to. * @param priority a boolean indicating the priority of the migration request sent to the body. * @exception MigrationException if the migration fails */ public static void migrateTo(Body bodyToMigrate, Node node, boolean priority) throws MigrationException { if (!(bodyToMigrate instanceof Migratable)) { throw new MigrationException( "This body cannot migrate. It doesn't implement Migratable interface"); } Object[] arguments = { node }; try { BodyRequest request = new BodyRequest(bodyToMigrate, "migrateTo", new Class[] { Node.class }, arguments, priority); request.send(bodyToMigrate); } catch (NoSuchMethodException e) { throw new MigrationException("Cannot find method migrateTo this body. Non sense since the body is instance of Migratable", e); } catch (java.io.IOException e) { throw new MigrationException("Cannot send the request to migrate", e); } } /** * Blocks the calling thread until one of the futures in the vector is available. * THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT. * @param futures vector of futures * @return index of the available future in the vector */ public static int waitForAny(java.util.Vector futures) { FuturePool fp = getBodyOnThis().getFuturePool(); synchronized (fp) { while (true) { java.util.Iterator it = futures.iterator(); int index = 0; while (it.hasNext()) { Object current = it.next(); if (!(isAwaited(current))) { return index; } index++; } fp.waitForReply(); } } } /** * Blocks the calling thread until all futures in the vector are available. * THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT. * @param futures vector of futures */ public static void waitForAll(java.util.Vector futures) { FuturePool fp = getBodyOnThis().getFuturePool(); synchronized (fp) { boolean oneIsMissing = true; while (oneIsMissing) { oneIsMissing = false; java.util.Iterator it = futures.iterator(); while (it.hasNext()) { Object current = it.next(); if (isAwaited(current)) { oneIsMissing = true; } } if (oneIsMissing) { fp.waitForReply(); } } } } /** * Blocks the calling thread until the N-th of the futures in the vector is available. * THIS METHOD MUST BE CALLED FROM AN ACTIVE OBJECT. * @param futures vector of futures */ public static void waitForTheNth(java.util.Vector futures, int n) { FuturePool fp = getBodyOnThis().getFuturePool(); synchronized (fp) { Object current = futures.get(n); if (isAwaited(current)) { waitFor(current); } } } /** * Return false if the object <code>future</code> is available. * This method is recursive, i.e. if result of future is a future too, * <CODE>isAwaited</CODE> is called again on this result, and so on. */ public static boolean isAwaited(Object future) { // If the object is not reified, it cannot be a future if ((MOP.isReifiedObject(future)) == false) { return false; } else { org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy(); // If it is reified but its proxy is not of type future, we cannot wait if (!(theProxy instanceof Future)) { return false; } else { if (((Future) theProxy).isAwaited()) { return true; } else { return isAwaited(((Future) theProxy).getResult()); } } } } /** * Return the object contains by the future (ie its target). * If parameter is not a future, it is returned. * A wait-by-necessity occurs if future is not available. * This method is recursive, i.e. if result of future is a future too, * <CODE>getFutureValue</CODE> is called again on this result, and so on. */ public static Object getFutureValue(Object future) { // If the object is not reified, it cannot be a future if ((MOP.isReifiedObject(future)) == false) { return future; } else { org.objectweb.proactive.core.mop.Proxy theProxy = ((StubObject) future).getProxy(); // If it is reified but its proxy is not of type future, we cannot wait if (!(theProxy instanceof Future)) { return future; } else { Object o = ((Future) theProxy).getResult(); return getFutureValue(o); } } } /** * Enable the automatic continuation mechanism for this active object. */ public static void enableAC(Object obj) throws java.io.IOException { // Check if obj is really a reified object if (!(MOP.isReifiedObject(obj))) { throw new ProActiveRuntimeException("The given object " + obj + " is not a reified object"); } // Find the appropriate remoteBody org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy(); if (myProxy == null) { throw new ProActiveRuntimeException( "Cannot find a Proxy on the stub object: " + obj); } BodyProxy myBodyProxy = (BodyProxy) myProxy; UniversalBody body = myBodyProxy.getBody().getRemoteAdapter(); body.enableAC(); } /** * Disable the automatic continuation mechanism for this active object. */ public static void disableAC(Object obj) throws java.io.IOException { // Check if obj is really a reified object if (!(MOP.isReifiedObject(obj))) { throw new ProActiveRuntimeException("The given object " + obj + " is not a reified object"); } // Find the appropriate remoteBody org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy(); if (myProxy == null) { throw new ProActiveRuntimeException( "Cannot find a Proxy on the stub object: " + obj); } BodyProxy myBodyProxy = (BodyProxy) myProxy; UniversalBody body = myBodyProxy.getBody().getRemoteAdapter(); body.disableAC(); } /** * Set an immmediate execution for the active object obj, ie request of name methodName * will be executed by the calling thread, and not add in the request queue. * BE CAREFULL : for the first release of this method, do not make use of getCurrentThreadBody nor * getStubOnThis in the method defined by methodName !! */ public static void setImmediateService(Object obj, String methodName) throws java.io.IOException { // Check if obj is really a reified object if (!(MOP.isReifiedObject(obj))) { throw new ProActiveRuntimeException("The given object " + obj + " is not a reified object"); } // Find the appropriate remoteBody org.objectweb.proactive.core.mop.Proxy myProxy = ((StubObject) obj).getProxy(); if (myProxy == null) { throw new ProActiveRuntimeException( "Cannot find a Proxy on the stub object: " + obj); } BodyProxy myBodyProxy = (BodyProxy) myProxy; UniversalBody body = myBodyProxy.getBody().getRemoteAdapter(); body.setImmediateService(methodName); } /** * @return the jobId associated with the object calling this method */ public static String getJobId() { return ProActive.getBodyOnThis().getJobID(); } /** * Search an appropriate handler for a given non functional exception. * The search starts in the highest level and continue in lower levels. When no * handler is available in one level, the search steps down into the hierarchy. * @param ex Exception for which we search a handler. * @param target An object which contains its own level. * @return A reliable handler or null if no handler is available */ public static Handler searchExceptionHandler(NonFunctionalException ex, Object target) { // Temporary handler Handler handler = null; // Try to get a handler from object level (active object = body or proxy) if (target != null) { // Try to get an handler from code level if (codeLevel != null) { if ((handler = searchExceptionHandler(ex.getClass(), (HashMap) codeLevel.get( new Integer(target.hashCode())), Handler.ID_Code)) != null) { return handler; } } // target is local body (i.e. active object level) ? if (target instanceof ActiveBody) { if (logger.isDebugEnabled()) { logger.debug("*** SEARCHING HANDLER IN LOCAL BODY"); } try { UniversalBody body = ((BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) target).getProxy()).getBody(); HashMap map = ((UniversalBody) body).getHandlersLevel(); if ((handler = searchExceptionHandler(ex.getClass(), map, Handler.ID_Body)) != null) { return handler; } } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR : " + e.getMessage()); } } // target is remote body (i.e. active object level) ? } else if (target instanceof RemoteBodyAdapter) { if (logger.isDebugEnabled()) { logger.debug("*** SEARCHING HANDLER IN REMOTE BODY"); } try { UniversalBody body = ((BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) target).getProxy()).getBody(); HashMap map = ((UniversalBody) body).getRemoteAdapter() .getHandlersLevel(); if ((handler = searchExceptionHandler(ex.getClass(), map, Handler.ID_Body)) != null) { return handler; } } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR : " + e.getMessage()); } } // target is a proxy (i.e. a ref. to a body) ? } else if (target instanceof AbstractProxy) { if (logger.isDebugEnabled()) { logger.debug("*** SEARCHING HANDLER IN PROXY"); } try { HashMap map = ((AbstractProxy) target).getHandlersLevel(); if ((handler = searchExceptionHandler(ex.getClass(), map, Handler.ID_Proxy)) != null) { return handler; } } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR : " + e.getMessage()); } } } } // Try to get an handler from VM level if ((handler = searchExceptionHandler(ex.getClass(), VMLevel, Handler.ID_VM)) != null) { return handler; } // At the end, get an handler from default level or return null return searchExceptionHandler(ex.getClass(), defaultLevel, Handler.ID_Default); } /** * Search an appropriate handler for a given non functional exception. * We first search in the highest level a handler for the real class of the exception. If the search fails, we try * with mother classes. When no handler is available in this level, we go down into the hierarchy of levels. * @param NFEClass Class of the non-functional exception for which a handler is searched. * @param level The level where handlers are searched * @param levelID Identificator of the level * @return A reliable handler or null if no handler is available */ public static Handler searchExceptionHandler(Class NFEClass, HashMap level, int levelID) { // Test level capacity if ((level == null) || level.isEmpty()) { return null; } // Retrieve an handler in the given level Handler handler = null; while ((handler == null) && (NFEClass.getName().compareTo(ProActiveException.class.getName()) != 0)) { // Information if (logger.isDebugEnabled()) { logger.debug("*** SEARCHING HANDLER FOR " + NFEClass.getName() + " IN LEVEL " + levelID); } // Research algorithm if (level.containsKey(NFEClass)) { try { handler = (Handler) Class.forName(((Class) level.get( NFEClass)).getName()).newInstance(); } catch (Exception e) { if (e instanceof ClassNotFoundException) { if (logger.isDebugEnabled()) { logger.debug("*** HANDLER FOR " + NFEClass.getName() + " IS INVALID"); } break; } else { e.printStackTrace(); } } } else { NFEClass = NFEClass.getSuperclass(); } } // We return the handler return handler; } /** * Add one handler of Non Functional Exception (nfe) to a specific level. * Similar handlers are overwritten except those at default level. * @param handler A class of handler associated with a class of non functional exception. * @param exception A class of non functional exception. It is a subclass of <code>NonFunctionalException</code>. * @param levelID An identificator for the level where the handler is added. * @param target An object which contains its own level. It is null if <code>level</code> is default or VM level. */ public static void setExceptionHandler(Class handler, Class exception, int levelID, Object target) { // Information if (logger.isDebugEnabled()) { logger.debug("*** SETTING " + handler.getName() + " FOR " + exception.getName() + " AT " + levelID + " LEVEL"); } // To minimize overall cost, level are created during the association of the first handler switch (levelID) { case (Handler.ID_Default): if (defaultLevel.get(exception) == null) { defaultLevel.put(exception, handler); } break; case (Handler.ID_VM): if (VMLevel == null) { VMLevel = new HashMap(); } VMLevel.put(exception, handler); break; case (Handler.ID_Body): // The target object must be a body if (target != null) { // Get the body of the target object UniversalBody body = ((BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) target).getProxy()).getBody(); try { if (body instanceof ActiveBody) { // Local body if (logger.isDebugEnabled()) { logger.debug("*** SET " + handler.getName() + " IN LOCAL BODY"); } body.setExceptionHandler(handler, exception); } else if (body instanceof RemoteBodyAdapter) { // Remote body if (logger.isDebugEnabled()) { logger.debug("*** SET " + handler.getName() + " HANDLER IN REMOTE BODY"); } body.getRemoteAdapter().setExceptionHandler(handler, exception); } } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR while SETTING handler " + handler.getName() + " in BODY LEVEL"); } } } else { if (logger.isDebugEnabled()) { logger.debug( "*** ERROR: CANNOT ADD HANDLER TO NULL BODY OBJECT"); } } break; case (Handler.ID_Proxy): // The target object must be a proxy if (((target != null) && target instanceof AbstractProxy)) { try { ((AbstractProxy) target).setExceptionHandler(handler, exception); } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR while SETTING handler " + handler.getName() + " in PROXY LEVEL"); } } } else { if (logger.isDebugEnabled()) { logger.debug( "*** ERROR: CANNOT ADD HANDLER TO NULL PROXY OBJECT"); } } break; case (Handler.ID_Future): break; case (Handler.ID_Code): if (target != null) { if (codeLevel == null) { codeLevel = new HashMap(); } // Try to get the hashmap associated to this object if (codeLevel.containsKey(new Integer(target.hashCode()))) { ((HashMap) codeLevel.get(new Integer(target.hashCode()))).put(exception, handler); } else { codeLevel.put(new Integer(target.hashCode()), new HashMap()); ((HashMap) codeLevel.get(new Integer(target.hashCode()))).put(exception, handler); } } else { if (logger.isDebugEnabled()) { logger.debug( "*** ERROR: CANNOT ADD TEMP. HANDLER TO NULL OBJECT"); } } break; } } /** * Remove a handler associated to a class of non functional exceptions. * @param exception A class of non functional exception which does not require the given handler anymore. * @param levelID An identificator for the level where the handler is removed. * @param target An object which contains its own level. It is null if <code>level</code> is default or VM level. */ public static Handler unsetExceptionHandler(Class exception, int levelID, Object target) { // We keep a trace of the removed handler Class handlerClass = null; Handler handler = null; // The correct level is identified switch (levelID) { // Default level must not be modified ! case (Handler.ID_Default): if (logger.isDebugEnabled()) { logger.debug( "*** ERROR: REMOVING HANDLER from DEFAULT LEVEL is FORBIDDEN !"); } return null; case (Handler.ID_VM): if (VMLevel != null) { handlerClass = (Class) VMLevel.remove(exception); } break; case (Handler.ID_Body): // The target must be a body if (((target != null) && target instanceof UniversalBody)) { // Get the body of target (remote) object UniversalBody body = ((BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) target).getProxy()).getBody(); try { if (body instanceof ActiveBody) { body.unsetExceptionHandler(exception); } else if (body instanceof RemoteBodyAdapter) { body.getRemoteAdapter().unsetExceptionHandler(exception); } } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR while UNSETTING handler for " + exception.getName() + " in BODY LEVEL"); } } } break; case (Handler.ID_Proxy): // The target must be a proxy if (((target != null) && target instanceof AbstractProxy)) { // Create a request to associate handler to the distant body try { handler = ((AbstractProxy) target).unsetExceptionHandler(exception); return handler; } catch (ProActiveException e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR while UNSETTING handler for " + exception.getName() + " in PROXY LEVEL"); } } } break; case (Handler.ID_Future): break; case (Handler.ID_Code): if ((target != null) && (codeLevel != null)) { if (codeLevel.containsKey(new Integer(target.hashCode()))) { handlerClass = (Class) ((HashMap) codeLevel.get(new Integer( target.hashCode()))).remove(exception); } } break; } // Instantiation of the removed handler if (handlerClass != null) { try { handler = (Handler) handlerClass.newInstance(); if (logger.isDebugEnabled()) { logger.debug("*** REMOVE [" + handler.getClass().getName() + "] FOR [" + exception.getName() + "] AT LEVEL " + levelID); } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("*** ERROR during class [" + handlerClass.getName() + "] instantiation"); } } } return handler; } private static String getNodeURLFromActiveObject(Object o) throws MigrationException { //first we check if the parameter is an active object, if (!org.objectweb.proactive.core.mop.MOP.isReifiedObject(o)) { throw new MigrationException( "The parameter is not an active object"); } //now we get a reference on the remoteBody of this guy BodyProxy destProxy = (BodyProxy) ((org.objectweb.proactive.core.mop.StubObject) o).getProxy(); return destProxy.getBody().getNodeURL(); } private static Node getNodeFromURL(String url) throws MigrationException { try { return NodeFactory.getNode(url); } catch (NodeException e) { throw new MigrationException("The node of given URL " + url + " cannot be localized", e); } } // STUB CREATION private static StubObject getStubForBody(Body body) { try { return createStubObject(body.getReifiedObject(), new Object[] { body }, body.getReifiedObject().getClass().getName()); } catch (MOPException e) { throw new ProActiveRuntimeException( "Cannot create Stub for this Body e=" + e); } } private static Object createStubObject(String className, UniversalBody body) throws MOPException { return createStubObject(className, null, new Object[] { body }); } private static Object createStubObject(String className, Object[] constructorParameters, Node node, Active activity, MetaObjectFactory factory) throws MOPException { return createStubObject(className, constructorParameters, new Object[] { node, activity, factory, ProActive.getJobId() }); } private static Object createStubObject(String className, Object[] constructorParameters, Object[] proxyParameters) throws MOPException { try { return MOP.newInstance(className, constructorParameters, Constants.DEFAULT_BODY_PROXY_CLASS_NAME, proxyParameters); } catch (ClassNotFoundException e) { throw new ConstructionOfProxyObjectFailedException( "Class can't be found e=" + e); } } private static Object createStubObject(Object target, String nameOfTargetType, Node node, Active activity, MetaObjectFactory factory) throws MOPException { return createStubObject(target, new Object[] { node, activity, factory, ProActive.getJobId() }, nameOfTargetType); } private static StubObject createStubObject(Object object, Object[] proxyParameters, String nameOfTargetType) throws MOPException { try { return (StubObject) MOP.turnReified(nameOfTargetType, Constants.DEFAULT_BODY_PROXY_CLASS_NAME, proxyParameters, object); } catch (ClassNotFoundException e) { throw new ConstructionOfProxyObjectFailedException( "Class can't be found e=" + e); } } }
package org.robockets.stronghold.robot; import org.robockets.buttonmanager.ButtonManager; import org.robockets.buttonmanager.buttons.ActionButton; import org.robockets.stronghold.robot.highgoalshooter.FireShooter; import org.robockets.stronghold.robot.highgoalshooter.MoveHood; import org.robockets.stronghold.robot.highgoalshooter.MoveShootingWheel; import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable; import org.robockets.stronghold.robot.intake.IntakeBall; import org.robockets.stronghold.robot.intake.IntakeSide; import org.robockets.stronghold.robot.intake.SetVerticalIntake; import org.robockets.stronghold.robot.intake.SpinIntake; import edu.wpi.first.wpilibj.Joystick; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { public static Joystick joystick = new Joystick(0); public static Joystick towerJoystick1 = new Joystick(1); public static Joystick towerJoystick2 = new Joystick(2); public OI () { ButtonManager.addJoystick(joystick); ButtonManager.addJoystick(towerJoystick1); ButtonManager.addJoystick(towerJoystick2); ButtonManager.addButton(new ActionButton(1, 1, new FireShooter(), false)); ButtonManager.addButton(new ActionButton(1, 2, new MoveHood(-15, 0), true)); ButtonManager.addButton(new ActionButton(1, 3, new MoveHood(15, 0), true)); ButtonManager.addButton(new ActionButton(1, 4, new MoveTurnTable(-30, 0), true)); ButtonManager.addButton(new ActionButton(1, 5, new MoveTurnTable(30, 0), true)); ButtonManager.addButton(new ActionButton(1, 11, new MoveShootingWheel(1200), true)); ButtonManager.addButton(new ActionButton(1, 10, new MoveShootingWheel(0), true)); ButtonManager.addButton(new ActionButton(2, 2, new SetVerticalIntake(Direction.DOWN, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(2, 3, new SetVerticalIntake(Direction.UP, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(2, 4, new SpinIntake(Direction.FORWARD, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(2, 5, new SpinIntake(Direction.BACKWARD, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(2, 11, new IntakeBall(IntakeSide.FRONT), false)); /*ButtonManager.addButton(new ActionButton(0, XboxOne.LEFT_BUMPER.getButtonNumber(), new MoveHood(0.5, 0), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.RIGHT_BUMPER.getButtonNumber(), new MoveHood(-0.5, 0), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.Y.getButtonNumber(), new MoveTurnTable(0.5), true)); ButtonManager.addButton(new ActionButton(1, 0, new MoveTurnTable(-0.5), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.A.getButtonNumber(), new FireShooter(), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.LEFT_BUMPER.getButtonNumber(), new ManualVerticalIntake(Direction.UP, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.RIGHT_BUMPER.getButtonNumber(), new ManualVerticalIntake(Direction.DOWN, 0, IntakeSide.BACK), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.A.getButtonNumber(), new ManualVerticalIntake(Direction.DOWN, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.B.getButtonNumber(), new ManualVerticalIntake(Direction.UP, 0, IntakeSide.BACK), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.LEFT_BUMPER.getButtonNumber(), new ManualSpinIntake(Direction.FORWARD, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.RIGHT_BUMPER.getButtonNumber(), new ManualSpinIntake(Direction.BACKWARD, 0, IntakeSide.BACK), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.A.getButtonNumber(), new ManualSpinIntake(Direction.BACKWARD, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.B.getButtonNumber(), new ManualSpinIntake(Direction.FORWARD, 0, IntakeSide.BACK), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.X.getButtonNumber(), new IntakesUp(), false)); ButtonManager.addButton(new ActionButton(0, XboxOne.A.getButtonNumber(), new ManualVerticalIntake(Direction.DOWN, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(0, XboxOne.Y.getButtonNumber(), new ManualVerticalIntake(Direction.UP, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(0, 1, new ManualSpinIntake(0.5, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(0, 1, new ManualSpinIntake(-0.5, 0, IntakeSide.FRONT), true)); ButtonManager.addButton(new ActionButton(1, XboxOne.A.getButtonNumber(), new TurnRelative(90), false)); ButtonManager.addButton(new ActionButton(1, XboxOne.X.getButtonNumber(), new TurnRelative(180), false)); ButtonManager.addButton(new ActionButton(1, XboxOne.B.getButtonNumber(), new TurnRelative(270), false));*/ } }
package org.mozartoz.truffle.runtime; import java.util.function.Consumer; import com.oracle.truffle.api.dsl.Fallback; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.Node; import org.mozartoz.truffle.nodes.DerefNode; @ExportLibrary(RecordLibrary.class) public class OzCons extends OzValue { public static final long HEAD = 1L; public static final long TAIL = 2L; private static final Object CONS_ARITY_LIST = Arity.CONS_ARITY.asOzList(); final Object head; final Object tail; public OzCons(Object head, Object tail) { this.head = head; this.tail = tail; } public Object getHead() { return head; } public Object getTail() { return tail; } public void forEach(DerefNode derefConsNode, Consumer<Object> block) { Object list = this; while (list instanceof OzCons) { OzCons cons = (OzCons) list; block.accept(cons.getHead()); list = derefConsNode.executeDeref(cons.getTail()); } assert list == "nil"; } public int length(DerefNode derefConsNode) { int length = 0; Object list = this; while (list instanceof OzCons) { OzCons cons = (OzCons) list; length++; list = derefConsNode.executeDeref(cons.getTail()); } assert list == "nil"; return length; } @ExportMessage boolean isRecord() { return true; } @ExportMessage Object label() { return "|"; } @ExportMessage Arity arity() { return Arity.CONS_ARITY; } @ExportMessage Object arityList() { return CONS_ARITY_LIST; } @ExportMessage static class HasFeature { @Specialization(guards = "feature == HEAD") static boolean getHead(OzCons cons, long feature) { return true; } @Specialization(guards = "feature == TAIL") static boolean getTail(OzCons cons, long feature) { return true; } @Fallback static boolean getOther(OzCons cons, Object feature) { return false; } } @ExportMessage static class Read { @Specialization(guards = "feature == HEAD") static Object getHead(OzCons cons, long feature, Node node) { return cons.getHead(); } @Specialization(guards = "feature == TAIL") static Object getTail(OzCons cons, long feature, Node node) { return cons.getTail(); } @Fallback static Object getOther(OzCons cons, Object feature, Node node) { throw Errors.noFieldError(node, cons, feature); } } @ExportMessage static class ReadOrDefault { @Specialization(guards = "feature == HEAD") static Object getHead(OzCons cons, long feature, Object defaultValue) { return cons.getHead(); } @Specialization(guards = "feature == TAIL") static Object getTail(OzCons cons, long feature, Object defaultValue) { return cons.getTail(); } @Fallback static Object getOther(OzCons cons, Object feature, Object defaultValue) { return defaultValue; } } @Override public int hashCode() { throw new UnsupportedOperationException("OzCons has structural equality"); } @Override public boolean equals(Object obj) { throw new UnsupportedOperationException("OzCons has structural equality"); } private static final DerefNode UNCACHED_DEREF_NODE = DerefNode.create(); @Override public String toString() { StringBuilder builder = new StringBuilder(); Object list = this; while (list instanceof OzCons) { OzCons cons = (OzCons) list; builder.append(cons.getHead()); builder.append('|'); list = UNCACHED_DEREF_NODE.executeDeref(cons.getTail()); } builder.append(list); return builder.toString(); } }
package picoded.servletUtils; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import picoded.servlet.*; import picoded.webUtils.*; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; import org.apache.http.*; import org.apache.http.cookie.*; import org.apache.http.entity.*; import org.apache.http.client.*; import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import org.apache.http.impl.cookie.*; import org.apache.http.protocol.*; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.util.EntityUtils; import org.apache.http.client.protocol.*; import org.apache.http.message.BasicNameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; public class ProxyServlet extends CorePage { /// Serialization UID. protected static final long serialVersionUID = 1L; /// Key for redirect location header. protected static final String LOCATION_HEADER = "Location"; /// Key for content type header. protected static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; /// Key for content length header. protected static final String CONTENT_LENGTH_HEADER_NAME = "Content-Length"; /// Key for host header protected static final String HOST_HEADER_NAME = "Host"; /// The directory to use to temporarily store uploaded files protected static final File UPLOAD_TEMP_DIRECTORY = new File(System.getProperty("java.io.tmpdir")); // Proxy host params /// The host paramter to proxy request to protected String proxyHost = "127.0.0.1"; /// The port on the proxy host to wihch we are proxying requests. Default value is 80. protected int proxyPort = 80; /// The (optional) path on the proxy host to wihch we are proxying requests. Default value is "". protected String proxyPath = ""; /// The maximum size for uploaded files in bytes. Default value is 100MB. protected int maxFileUploadSize = 100 * 1024 * 1024; // Proxy host params PUT/GET public String getProxyHostAndPort() { if(getProxyPort() == 80) { return getProxyHost(); } else { return getProxyHost() + ":" + getProxyPort(); } } public String getProxyHost() { return proxyHost; } public void setProxyHost(String stringProxyHostNew) { proxyHost = stringProxyHostNew; } public int getProxyPort() { return proxyPort; } public void setProxyPort(int intProxyPortNew) { proxyPort = intProxyPortNew; } public String getProxyPath() { return proxyPath; } public void setProxyPath(String stringProxyPathNew) { proxyPath = stringProxyPathNew; } public int getMaxFileUploadSize() { return maxFileUploadSize; } public void setMaxFileUploadSize(int intMaxFileUploadSizeNew) { maxFileUploadSize = intMaxFileUploadSizeNew; } // Utility functions for Request / Response /// Gets and returns the target proxy URL given the httpServletReqeust protected String getProxyURL(HttpServletRequest httpServletRequest) { // Set the protocol to HTTP String stringProxyURL = "http://" + getProxyHostAndPort(); // Check if we are proxying to a path other that the document root if(!getProxyPath().equalsIgnoreCase("")){ stringProxyURL += getProxyPath(); } // Handle the path given to the servlet stringProxyURL += httpServletRequest.getPathInfo(); // Handle the query string if(httpServletRequest.getQueryString() != null) { stringProxyURL += "?" + httpServletRequest.getQueryString(); } return stringProxyURL; } // Loading of proxy host config values from web.xml (if applicable) /// Initialize the <code>ProxyServlet</code> /// @param servletConfig The Servlet configuration passed in by the servlet conatiner @Override public void initSetup( CorePage original, ServletConfig servletConfig) throws ServletException { super.initSetup(original, servletConfig); ProxyServlet ori = (ProxyServlet)original; // Load original values? proxyHost = ori.proxyHost; proxyPort = ori.proxyPort; proxyPath = ori.proxyPath; maxFileUploadSize = ori.maxFileUploadSize; // Get the proxy host String newProxyHost = servletConfig.getInitParameter("proxyHost"); if (newProxyHost != null && (newProxyHost = newProxyHost.trim()).length() > 0 ) { setProxyHost( newProxyHost ); } // Get the proxy port if specified String newProxyPort = servletConfig.getInitParameter("proxyPort"); if (newProxyPort != null && (newProxyPort = newProxyHost.trim()).length() > 0 ) { setProxyPort( Integer.parseInt(newProxyPort) ); } // Get the proxy path if specified String newProxyPath = servletConfig.getInitParameter("proxyPath"); if (newProxyPath != null && (newProxyPath = newProxyPath.trim()).length() > 0 ) { setProxyPath( newProxyPath ); } // Get the maximum file upload size if specified String newMaxFileUploadSize = servletConfig.getInitParameter("maxFileUploadSize"); if(newMaxFileUploadSize != null && (newMaxFileUploadSize = newMaxFileUploadSize.trim()).length() > 0) { setMaxFileUploadSize( Integer.parseInt(newMaxFileUploadSize) ); } } /// Takes a servelt request, and populate the proxy request parameters / headers @SuppressWarnings("unchecked") protected void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpUriRequest httpMethodProxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while(enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = enumerationOfHeaderNames.nextElement(); if(stringHeaderName.equalsIgnoreCase(CONTENT_LENGTH_HEADER_NAME)) { continue; } // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the client Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName); while(enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if(stringHeaderName.equalsIgnoreCase(HOST_HEADER_NAME)){ stringHeaderValue = getProxyHostAndPort(); } // Set the same header on the proxy request httpMethodProxyRequest.setHeader(stringHeaderName, stringHeaderValue); } } } protected void executeProxyRequest( HttpUriRequest httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException { try { // Create a default HttpClient with Disabled automated stuff HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().disableAuthCaching().build(); HttpResponse response = httpClient.execute(httpMethodProxyRequest); StatusLine statusLine = response.getStatusLine(); int intProxyResponseCode = statusLine.getStatusCode(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES // 300 && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED //304 ) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = response.getFirstHeader(LOCATION_HEADER).getValue(); if(stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if(httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation.replace(getProxyHostAndPort() + getProxyPath(), stringMyHostName)); return; } else if(intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = response.getAllHeaders(); for(Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamProxyResponse = response.getEntity().getContent(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ( ( intNextByte = bufferedInputStream.read() ) != -1 ) { outputStreamClientResponse.write(intNextByte); outputStreamClientResponse.flush(); } outputStreamClientResponse.flush(); } catch(Exception e) { throw new ServletException(e); } } // Core page overrides /// Performs an output request, with special handling of POST / PUT @Override public boolean outputRequest(Map<String,Object> templateData, PrintWriter output) throws ServletException { return proxyCorePageRequest(this); } /// Performs a proxy redirect using the given CorePage instance public boolean proxyCorePageRequest(CorePage page) throws ServletException { HttpRequestType rType = page.getHttpRequestType(); HttpServletRequest sReq = page.getHttpServletRequest(); HttpServletResponse sRes = page.getHttpServletResponse(); // Create the respective request URL based on requestType and URL HttpUriRequest methodToProxyRequest = RequestHttpUtils.apache_HttpUriRequest_fromRequestType(rType, getProxyURL(sReq)); // Forward the request headers setProxyRequestHeaders(sReq, methodToProxyRequest); // Handles post or put if( rType == HttpRequestType.TYPE_POST || rType == HttpRequestType.TYPE_PUT ) { if(ServletFileUpload.isMultipartContent( sReq )) { handleMultipartPost( (HttpEntityEnclosingRequestBase)methodToProxyRequest, sReq); } else { // handleStandardPost( (HttpEntityEnclosingRequestBase)methodToProxyRequest, sReq); String reqLength = sReq.getHeader(CONTENT_LENGTH_HEADER_NAME); if( reqLength.equals("0") ) { // does nothing if req is 0 } else { // Gets as raw input stream, and passes it try { ((HttpEntityEnclosingRequestBase)methodToProxyRequest).setEntity( new InputStreamEntity(sReq.getInputStream()) ); } catch(IOException e) { throw new ServletException(e); } } } } // Execute the proxy request executeProxyRequest(methodToProxyRequest, sReq, sRes); return true; } // Upload data handling protected void handleStandardPost( HttpEntityEnclosingRequestBase postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { try { // Get the client POST data as a Map Map<String, String[]> mapPostParameters = httpServletRequest.getParameterMap(); // Create a List to hold the NameValuePairs to be passed to the PostMethod List<NameValuePair> listNameValuePairs = RequestHttpUtils.parameterMapToList(mapPostParameters); // Set the proxy request POST data postMethodProxyRequest.setEntity( new UrlEncodedFormEntity(listNameValuePairs) ); // listNameValuePairs.toArray(new NameValuePair[] { }) ?? } catch (Exception e) { throw new ServletException(e); } } @SuppressWarnings("unchecked") protected void handleMultipartPost( HttpEntityEnclosingRequestBase postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(getMaxFileUploadSize()); diskFileItemFactory.setRepository(UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts MultipartEntityBuilder multipartRequestEntity = MultipartEntityBuilder.create(); // Iterate the multipart items list for(FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { multipartRequestEntity.addTextBody( fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); } else { // The item is a file upload, so we create a FilePart multipartRequestEntity.addBinaryBody( fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getInputStream() //The file itself ); } } HttpEntity multipartRequestEntity_final = multipartRequestEntity.build(); postMethodProxyRequest.setEntity(multipartRequestEntity_final); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setHeader(CONTENT_TYPE_HEADER_NAME, multipartRequestEntity_final.getContentType().getValue() ); } catch (Exception fileUploadException) { throw new ServletException(fileUploadException); } } }
package properties.competition; import static structure.impl.other.Quantification.FORALL; import java.util.Collection; import properties.Property; import properties.PropertyMaker; import properties.papers.HasNextQEA; import structure.intf.Assignment; import structure.intf.Binding; import structure.intf.Guard; import structure.intf.QEA; import creation.QEABuilder; public class QEAJava implements PropertyMaker { @Override public QEA make(Property property) { switch (property) { case QEA_JAVA_ONE: return makeOne(); case QEA_JAVA_TWO: return makeTwo(); case QEA_JAVA_THREE: return makeThree(); case QEA_JAVA_FOUR: return makeFour(); } return null; } public QEA makeOne() { QEA qea = new HasNextQEA(); qea.setName("QEA_JAVA_ONE"); return qea; } public QEA makeTwo() { QEABuilder q = new QEABuilder("QEA_JAVA_TWO"); int ITERATOR = 1; int NEXT = 2; final int i = -1; final int s = 1; final int c = 2; q.addQuantification(FORALL, i); q.startTransition(1); q.eventName(ITERATOR); q.addVarArg(c); q.addVarArg(i); q.addAssignment(new Assignment("x_" + s + " = x_ " + c + ".size()") { @Override public int[] vars() { return new int[] { s, c }; } @Override public Binding apply(Binding binding, boolean copy) { Collection cVal = (Collection) binding.getForced(c); Binding result = copy ? binding.copy() : binding; result.setValue(s, cVal.size()); return result; } }); q.endTransition(2); q.startTransition(2); q.eventName(NEXT); q.addVarArg(i); q.addGuard(Guard.isGreaterThanConstant(s, 0)); q.addAssignment(Assignment.decrement(s)); q.endTransition(2); q.addFinalStates(1, 2); q.setSkipStates(1); QEA qea = q.make(); qea.record_event_name("iterator", 1); qea.record_event_name("next", 2); return qea; } public QEA makeThree() { QEABuilder q = new QEABuilder("QEA_JAVA_THREE"); int ADD = 1; int OBSERVE = 2; int REMOVE = 3; final int s = -1; final int o = -2; final int h = 1; q.addQuantification(FORALL, s); q.addQuantification(FORALL, o); q.startTransition(1); q.eventName(ADD); q.addVarArg(s); q.addVarArg(o); q.addAssignment(new Assignment("h = o.hashCode") { @Override public int[] vars() { return new int[] { h, o }; } @Override public Binding apply(Binding binding, boolean copy) { Object oVal = binding.getForced(o); Binding result = copy ? binding.copy() : binding; result.setValue(h, oVal.hashCode()); return result; } }); q.endTransition(2); Guard gHashCode = new Guard("h == o.hashCode()") { @Override public int[] vars() { return new int[] { h, o }; } @Override public boolean usesQvars() { return true; } @Override public boolean check(Binding binding, int qvar, Object firstQval) { return check(binding); // Assuming binding is FullBindingImpl } @Override public boolean check(Binding binding) { int hVal = binding.getForcedAsInteger(h); Object oVal = binding.getForced(o); return hVal == oVal.hashCode(); } }; q.startTransition(2); q.eventName(OBSERVE); q.addVarArg(s); q.addVarArg(o); q.addGuard(gHashCode); q.endTransition(2); q.startTransition(2); q.eventName(REMOVE); q.addVarArg(s); q.addVarArg(o); q.addGuard(gHashCode); q.endTransition(1); q.startTransition(2); q.eventName(ADD); q.addVarArg(s); q.addVarArg(o); q.addGuard(gHashCode); q.endTransition(2); q.addFinalStates(1, 2); QEA qea = q.make(); qea.record_event_name("add", 1); qea.record_event_name("observe", 2); qea.record_event_name("remove", 3); return qea; } public QEA makeFour() { QEABuilder q = new QEABuilder("QEA_JAVA_FOUR"); int LOCK = 1; int UNLOCK = 2; final int l1 = -1; final int l2 = -2; q.addQuantification(FORALL, l1); q.addQuantification(FORALL, l2, Guard.isNotEqual(l1, l2)); q.addTransition(1, LOCK, new int[] { l1 }, 2); q.addTransition(2, UNLOCK, new int[] { l1 }, 1); q.addTransition(2, LOCK, new int[] { l2 }, 3); q.addTransition(3, LOCK, new int[] { l2 }, 4); q.addTransition(4, UNLOCK, new int[] { l2 }, 3); q.addTransition(4, LOCK, new int[] { l1 }, 5); q.addFinalStates(1, 2, 3, 4); q.setSkipStates(1, 2, 3, 4, 5); QEA qea = q.make(); qea.record_event_name("lock", 1); qea.record_event_name("unlock", 2); return qea; } }
package com.lmax.disruptor; import java.util.concurrent.TimeUnit; import static com.lmax.disruptor.Util.ceilingNextPowerOfTwo; /** * Ring based store of reusable entries containing the data representing an {@link Entry} being exchanged between producers and consumers. * * @param <T> Entry implementation storing the data for sharing during exchange or parallel coordination of an event. */ @SuppressWarnings("unchecked") public final class RingBuffer<T extends Entry> { /** Set to -1 as sequence starting point */ public static final long INITIAL_CURSOR_VALUE = -1; private final Object[] entries; private final int ringModMask; private final CommitCallback claimNextCallback = new ClaimNextCommitCallback(); private final CommitCallback claimSequenceCallback = new SetSequenceCommitCallback(); private final ClaimStrategy claimStrategy; private final WaitStrategy waitStrategy; private volatile long cursor = INITIAL_CURSOR_VALUE; /** * Construct a RingBuffer with the full option set. * * @param entryFactory to create {@link Entry}s for filling the RingBuffer * @param size of the RingBuffer that will be rounded up to the next power of 2 * @param claimStrategyOption threading strategy for producers claiming {@link Entry}s in the ring. * @param waitStrategyOption waiting strategy employed by consumers waiting on {@link Entry}s becoming available. */ public RingBuffer(final EntryFactory<T> entryFactory, final int size, final ClaimStrategy.Option claimStrategyOption, final WaitStrategy.Option waitStrategyOption) { int sizeAsPowerOfTwo = ceilingNextPowerOfTwo(size); ringModMask = sizeAsPowerOfTwo - 1; entries = new Object[sizeAsPowerOfTwo]; claimStrategy = claimStrategyOption.newInstance(); waitStrategy = waitStrategyOption.newInstance(); fill(entryFactory); } /** * Construct a RingBuffer with default strategies of: * {@link ClaimStrategy.Option#MULTI_THREADED} and {@link WaitStrategy.Option#BLOCKING} * * @param entryFactory to create {@link Entry}s for filling the RingBuffer * @param size of the RingBuffer that will be rounded up to the next power of 2 */ public RingBuffer(final EntryFactory<T> entryFactory, final int size) { this(entryFactory, size, ClaimStrategy.Option.MULTI_THREADED, WaitStrategy.Option.BLOCKING); } /** * Create a {@link Barrier} that gates on the RingBuffer and a list of {@link EntryConsumer}s * * @param entryConsumers this barrier will track * @return the barrier gated as required */ public Barrier<T> createBarrier(final EntryConsumer... entryConsumers) { return new RingBufferBarrier<T>(this, waitStrategy, entryConsumers); } /** * Create a {@link Claimer} on this RingBuffer that tracks dependent {@link EntryConsumer}s. * * The bufferReserve should be at least the number of producing threads. * * @param bufferReserve size of of the buffer to be reserved. * @param entryConsumers to be tracked to prevent wrapping. * @return a {@link Claimer} with the above configuration. */ public Claimer<T> createClaimer(final int bufferReserve, final EntryConsumer... entryConsumers) { return new RingBufferClaimer<T>(this, bufferReserve, entryConsumers); } /** * Get the entry for a given sequence from the RingBuffer * * @param sequence for the entry. * @return entry matching the sequence. */ public T getEntry(final long sequence) { return (T)entries[(int)sequence & ringModMask]; } /** * The capacity of the RingBuffer to hold entries. * * @return the size of the RingBuffer. */ public int getCapacity() { return entries.length; } /** * Get the current sequence that producers have committed to the RingBuffer. * * @return the current committed sequence. */ public long getCursor() { return cursor; } private void fill(final EntryFactory<T> entryEntryFactory) { for (int i = 0; i < entries.length; i++) { entries[i] = entryEntryFactory.create(); } } private T claimNext() { long sequence = claimStrategy.getAndIncrement(); T entry = (T)entries[(int)sequence & ringModMask]; entry.setSequence(sequence, claimNextCallback); return entry; } private T claimSequence(final long sequence) { T entry = (T)entries[(int)sequence & ringModMask]; entry.setSequence(sequence, claimSequenceCallback); return entry; } /** * Callback to be used when claiming {@link Entry}s in sequence and cursor is catching up with claim * for notifying the the consumers of progress. This will busy spin on the commit until previous * producers have committed lower sequence entries. */ private final class ClaimNextCommitCallback implements CommitCallback { public void commit(final long sequence) { claimStrategy.waitForCursor(sequence - 1L, RingBuffer.this); cursor = sequence; waitStrategy.notifyConsumers(); } } /** * Callback to be used when claiming {@link Entry}s and the cursor is explicitly set by the producer when you are sure only one * producer exists. */ private final class SetSequenceCommitCallback implements CommitCallback { public void commit(final long sequence) { claimStrategy.setSequence(sequence + 1L); cursor = sequence; waitStrategy.notifyConsumers(); } } /** * Barrier handed out for gating consumers of the RingBuffer and dependent {@link EntryConsumer}(s) */ private static final class RingBufferBarrier<T extends Entry> implements Barrier<T> { private final RingBuffer<? extends T> ringBuffer; private final EntryConsumer[] entryConsumers; private final WaitStrategy waitStrategy; public RingBufferBarrier(final RingBuffer<? extends T> ringBuffer, final WaitStrategy waitStrategy, final EntryConsumer... entryConsumers) { this.ringBuffer = ringBuffer; this.waitStrategy = waitStrategy; this.entryConsumers = entryConsumers; } @Override public RingBuffer<? extends T> getRingBuffer() { return ringBuffer; } @Override public T getEntry(final long sequence) { return ringBuffer.getEntry(sequence); } @Override public long getAvailableSequence() { long minimum = ringBuffer.getCursor(); for (EntryConsumer entryConsumer : entryConsumers) { long sequence = entryConsumer.getSequence(); minimum = minimum < sequence ? minimum : sequence; } return minimum; } @Override public long waitFor(final long sequence) throws AlertException, InterruptedException { long availableSequence = waitStrategy.waitFor(ringBuffer, sequence); if (0 != entryConsumers.length) { while ((availableSequence = getAvailableSequence()) < sequence) { waitStrategy.checkForAlert(); } } return availableSequence; } @Override public long waitFor(final long sequence, final long timeout, final TimeUnit units) throws InterruptedException, AlertException { long availableSequence = waitStrategy.waitFor(ringBuffer, sequence, timeout, units); if (0 != entryConsumers.length) { while ((availableSequence = getAvailableSequence()) < sequence) { waitStrategy.checkForAlert(); } } return availableSequence; } @Override public void alert() { waitStrategy.alert(); } } /** * Claimer that uses a thread yielding strategy when trying to claim a {@link Entry} in the {@link RingBuffer}. * * @param <T> {@link Entry} implementation stored in the {@link RingBuffer} */ private final class RingBufferClaimer<T extends Entry> implements Claimer<T> { private final RingBuffer<? extends T> ringBuffer; private final int bufferReserve; private final EntryConsumer[] entryConsumers; public RingBufferClaimer(final RingBuffer<? extends T> ringBuffer, final int bufferReserve, final EntryConsumer... entryConsumers) { this.bufferReserve = bufferReserve; this.ringBuffer = ringBuffer; this.entryConsumers = entryConsumers; } @Override public T claimNext() { final long threshold = ringBuffer.getCapacity() - getBufferReserve(); while (ringBuffer.getCursor() - getConsumedSequence() >= threshold) { Thread.yield(); } return ringBuffer.claimNext(); } @Override public T claimSequence(final long sequence) { final long threshold = ringBuffer.getCapacity() - getBufferReserve(); while (sequence - getConsumedSequence() >= threshold) { Thread.yield(); } return ringBuffer.claimSequence(sequence); } @Override public RingBuffer<? extends T> getRingBuffer() { return ringBuffer; } @Override public long getConsumedSequence() { long minimum = ringBuffer.getCursor(); for (EntryConsumer consumer : entryConsumers) { long sequence = consumer.getSequence(); minimum = minimum < sequence ? minimum : sequence; } return minimum; } @Override public int getBufferReserve() { return bufferReserve; } } /** * Callback into {@link RingBuffer} to signal that the producer has populated the {@link Entry} and it is now ready for use. */ interface CommitCallback { /** * Callback to signal {@link Entry} is ready for consumption. * * @param sequence of the {@link Entry} that is ready for consumption. */ public void commit(long sequence); } }
package net.fortuna.ical4j.model; import java.util.Arrays; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import junit.framework.TestCase; import net.fortuna.ical4j.model.parameter.Value; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Ben Fortuna */ public class RecurTest extends TestCase { private static Log log = LogFactory.getLog(RecurTest.class); public void testGetDates() { Recur recur = new Recur(Recur.DAILY, 10); recur.setInterval(2); log.info(recur); Calendar cal = Calendar.getInstance(); Date start = new Date(cal.getTime().getTime()); cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10); Date end = new Date(cal.getTime().getTime()); log.info(recur.getDates(start, end, Value.DATE_TIME)); recur.setUntil(new Date(cal.getTime().getTime())); log.info(recur); log.info(recur.getDates(start, end, Value.DATE_TIME)); recur.setFrequency(Recur.WEEKLY); recur.getDayList().add(WeekDay.MO); log.info(recur); DateList dates = recur.getDates(start, end, Value.DATE); log.info(dates); assertTrue("Date list exceeds COUNT limit", dates.size() <= 10); } /** * Test BYDAY rules. */ public void testGetDatesByDay() { Recur recur = new Recur(Recur.DAILY, 10); recur.setInterval(1); recur.getDayList().add(WeekDay.MO); recur.getDayList().add(WeekDay.TU); recur.getDayList().add(WeekDay.WE); recur.getDayList().add(WeekDay.TH); recur.getDayList().add(WeekDay.FR); log.info(recur); Calendar cal = Calendar.getInstance(); Date start = new Date(cal.getTime().getTime()); cal.add(Calendar.DAY_OF_WEEK_IN_MONTH, 10); Date end = new Date(cal.getTime().getTime()); DateList dates = recur.getDates(start, end, Value.DATE_TIME); log.info(dates); assertTrue("Date list exceeds COUNT limit", dates.size() <= 10); } public void testGetDatesWithBase() { /* * Here is an example of evaluating multiple BYxxx rule parts. * * DTSTART;TZID=US-Eastern:19970105T083000 * RRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=1;BYDAY=SU;BYHOUR=8,9; * BYMINUTE=30 */ Calendar testCal = Calendar.getInstance(); testCal.set(Calendar.YEAR, 1997); testCal.set(Calendar.MONTH, 1); testCal.set(Calendar.DAY_OF_MONTH, 5); testCal.set(Calendar.HOUR, 8); testCal.set(Calendar.MINUTE, 30); testCal.set(Calendar.SECOND, 0); Recur recur = new Recur(Recur.YEARLY, -1); recur.setInterval(2); recur.getMonthList().add(new Integer(1)); recur.getDayList().add(WeekDay.SU); recur.getHourList().add(new Integer(8)); recur.getHourList().add(new Integer(9)); recur.getMinuteList().add(new Integer(30)); Calendar cal = Calendar.getInstance(); Date start = new Date(cal.getTime().getTime()); cal.add(Calendar.YEAR, 2); Date end = new Date(cal.getTime().getTime()); log.info(recur); DateList dates = recur.getDates(new Date(testCal.getTime()), start, end, Value.DATE_TIME); log.info(dates); } public void testSublistNegative() { List list = new LinkedList(); list.add("1"); list.add("2"); list.add("3"); assertSublistEquals(list, list, 0); assertSublistEquals(asList("3"), list, -1); assertSublistEquals(asList("2"), list, -2); assertSublistEquals(asList("1"), list, -3); assertSublistEquals(list, list, -4); } public void testSublistPositive() { List list = new LinkedList(); list.add("1"); list.add("2"); list.add("3"); assertSublistEquals(list, list, 0); assertSublistEquals(asList("1"), list, 1); assertSublistEquals(asList("2"), list, 2); assertSublistEquals(asList("3"), list, 3); assertSublistEquals(list, list, 4); } private void assertSublistEquals(List expected, List list, int offset) { List sublist = new LinkedList(); Recur.sublist(list, offset, sublist); assertEquals(expected, sublist); } private List asList(Object o) { List list = new LinkedList(); list.add(o); return list; } public void testSetPosNegative() throws Exception { Date[] dates = new Date[] { new Date(1), new Date(2), new Date(3) }; Date[] expected = new Date[] { new Date(3), new Date(2) }; assertSetPosApplied(expected, dates, "BYSETPOS=-1,-2"); } public void testSetPosPositve() throws Exception { Date[] dates = new Date[] { new Date(1), new Date(2), new Date(3) }; Date[] expected = new Date[] { new Date(2), new Date(3) }; assertSetPosApplied(expected, dates, "BYSETPOS=2,3"); } public void testSetPosOutOfBounds() throws Exception { Date[] dates = new Date[] { new Date(1) }; Date[] expected = new Date[] {}; assertSetPosApplied(expected, dates, "BYSETPOS=-2,2"); } private void assertSetPosApplied(Date[] expected, Date[] dates, String rule) throws Exception { Recur recur = new Recur(rule); DateList expectedList = asDateList(expected); assertEquals(expectedList, recur.applySetPosRules(asDateList(dates))); } private DateList asDateList(Date[] dates) { DateList dateList = new DateList(Value.DATE); dateList.addAll(Arrays.asList(dates)); return dateList; } /** * This test creates a rule outside of the specified boundaries to * confirm that the returned date list is empty. * <pre> * Weekly on Tuesday and Thursday for 5 weeks: * * DTSTART;TZID=US-Eastern:19970902T090000 * RRULE:FREQ=WEEKLY;UNTIL=19971007T000000Z;WKST=SU;BYDAY=TU,TH * or * * RRULE:FREQ=WEEKLY;COUNT=10;WKST=SU;BYDAY=TU,TH * * ==> (1997 9:00 AM EDT)September 2,4,9,11,16,18,23,25,30;October 2 * </pre> */ public final void testBoundaryProcessing() { Recur recur = new Recur(Recur.WEEKLY, 10); recur.getDayList().add(WeekDay.TU); recur.getDayList().add(WeekDay.TH); log.info(recur); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 1997); cal.set(Calendar.MONTH, Calendar.SEPTEMBER); cal.set(Calendar.DAY_OF_MONTH, 2); cal.set(Calendar.HOUR_OF_DAY, 9); cal.clear(Calendar.MINUTE); cal.clear(Calendar.SECOND); Date seed = new DateTime(cal.getTime()); cal = Calendar.getInstance(); Date start = new DateTime(cal.getTime()); cal.add(Calendar.YEAR, 2); Date end = new DateTime(cal.getTime()); DateList dates = recur.getDates(seed, start, end, Value.DATE_TIME); log.info(dates); assertTrue(dates.isEmpty()); } /** * This test confirms SETPOS rules are working correctly. * <pre> * The BYSETPOS rule part specifies a COMMA character (US-ASCII decimal * 44) separated list of values which corresponds to the nth occurrence * within the set of events specified by the rule. Valid values are 1 to * 366 or -366 to -1. It MUST only be used in conjunction with another * BYxxx rule part. For example "the last work day of the month" could * be represented as: * * RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1 * </pre> */ public final void testSetPosProcessing() { Recur recur = new Recur(Recur.MONTHLY, -1); recur.getDayList().add(WeekDay.MO); recur.getDayList().add(WeekDay.TU); recur.getDayList().add(WeekDay.WE); recur.getDayList().add(WeekDay.TH); recur.getDayList().add(WeekDay.FR); recur.getSetPosList().add(new Integer(-1)); log.info(recur); Calendar cal = Calendar.getInstance(); Date start = new DateTime(cal.getTime()); cal.add(Calendar.YEAR, 2); Date end = new DateTime(cal.getTime()); DateList dates = recur.getDates(start, end, Value.DATE_TIME); log.info(dates); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tonegod.gui.controls.text; import com.jme3.font.BitmapFont; import com.jme3.font.BitmapText; import com.jme3.font.LineWrapMode; import com.jme3.font.Rectangle; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Vector2f; import com.jme3.math.Vector4f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.jme3.scene.control.Control; import java.util.ArrayList; import java.util.List; import tonegod.gui.core.Element; import tonegod.gui.core.ElementManager; import tonegod.gui.core.Screen; import tonegod.gui.style.StyleManager.CursorType; import tonegod.gui.core.utils.BitmapTextUtil; import tonegod.gui.core.utils.UIDUtil; import tonegod.gui.effects.Effect; import tonegod.gui.listeners.KeyboardListener; import tonegod.gui.listeners.MouseButtonListener; import tonegod.gui.listeners.MouseFocusListener; import tonegod.gui.listeners.TabFocusListener; /** * * @author t0neg0d */ public class TextField extends Element implements Control, KeyboardListener, TabFocusListener, MouseFocusListener, MouseButtonListener { public static enum Type { DEFAULT, ALPHA, ALPHA_NOSPACE, NUMERIC, ALPHANUMERIC, ALPHANUMERIC_NOSPACE, EXCLUDE_SPECIAL, EXCLUDE_CUSTOM, INCLUDE_CUSTOM }; private String validateAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "; private String validateAlphaNoSpace = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private String validateNumeric = "0123456789.-"; private String validateSpecChar = "`~!@ private String validateCustom = ""; private String testString = "Gg|/X"; private Element caret; private Material caretMat; protected int caretIndex = 0, head = 0, tail = 0; protected int rangeHead = -1, rangeTail = -1; protected int visibleHead = -1, visibleTail = -1; protected List<String> textFieldText = new ArrayList(); protected String finalText = "", visibleText = "", textRangeText = ""; protected BitmapText widthTest; private boolean hasTabFocus = false; protected float caretX = 0; private Type type = Type.DEFAULT; protected boolean ctrl = false, shift = false, alt = false, meta = false; private boolean isEnabled = true; private boolean forceUpperCase = false, forceLowerCase = false; private int maxLength = 0; private String nextChar; private boolean valid; private boolean copy = true, paste = true; private float firstClick = 0, secondClick = 0, compareClick = 0; private float firstClickDiff = 0, secondClickDiff = 0; private boolean doubleClick = false, tripleClick = false; private int clickCount = 0; private boolean isPressed = false; /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element */ public TextField(ElementManager screen, Vector2f position) { this(screen, UIDUtil.getUID(), position, screen.getStyle("TextField").getVector2f("defaultSize"), screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public TextField(ElementManager screen, Vector2f position, Vector2f dimensions) { this(screen, UIDUtil.getUID(), position, dimensions, screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the TextField */ public TextField(ElementManager screen, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { this(screen, UIDUtil.getUID(), position, dimensions, resizeBorders, defaultImg); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element */ public TextField(ElementManager screen, String UID, Vector2f position) { this(screen, UID, position, screen.getStyle("TextField").getVector2f("defaultSize"), screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element */ public TextField(ElementManager screen, String UID, Vector2f position, Vector2f dimensions) { this(screen, UID, position, dimensions, screen.getStyle("TextField").getVector4f("resizeBorders"), screen.getStyle("TextField").getString("defaultImg") ); } /** * Creates a new instance of the TextField control * * @param screen The screen control the Element is to be added to * @param UID A unique String identifier for the Element * @param position A Vector2f containing the x/y position of the Element * @param dimensions A Vector2f containing the width/height dimensions of the Element * @param resizeBorders A Vector4f containg the border information used when resizing the default image (x = N, y = W, z = E, w = S) * @param defaultImg The default image to use for the Slider's track */ public TextField(ElementManager screen, String UID, Vector2f position, Vector2f dimensions, Vector4f resizeBorders, String defaultImg) { super(screen, UID, position, dimensions, resizeBorders, defaultImg); this.setScaleEW(true); this.setScaleNS(false); this.setDocking(Docking.NW); compareClick = screen.getApplication().getTimer().getTimeInSeconds(); float padding = screen.getStyle("TextField").getFloat("textPadding"); this.setFontSize(screen.getStyle("TextField").getFloat("fontSize")); this.setTextPadding(padding); this.setTextWrap(LineWrapMode.valueOf(screen.getStyle("TextField").getString("textWrap"))); this.setTextAlign(BitmapFont.Align.valueOf(screen.getStyle("TextField").getString("textAlign"))); this.setTextVAlign(BitmapFont.VAlign.valueOf(screen.getStyle("TextField").getString("textVAlign"))); this.setMinDimensions(dimensions.clone()); caret = new Element(screen, UID + ":Caret", new Vector2f(padding,padding), new Vector2f(dimensions.x-(padding*2), dimensions.y-(padding*2)), new Vector4f(0,0,0,0), null); caretMat = caret.getMaterial().clone(); caretMat.setBoolean("IsTextField", true); caretMat.setTexture("ColorMap", null); caretMat.setColor("Color", getFontColor()); caret.setLocalMaterial(caretMat); caret.setIgnoreMouse(true); caret.setScaleEW(true); caret.setScaleNS(false); caret.setDocking(Docking.SW); setTextFieldFontColor(screen.getStyle("TextField").getColorRGBA("fontColor")); this.addChild(caret); this.updateText(""); populateEffects("TextField"); } // Validation /** * Sets the TextField.Type of the text field. This can be used to enfoce rules on the inputted text * @param type Type */ public void setType(Type type) { this.type = type; } /** * Returns the current Type of the TextField * @return Type */ public Type getType() { return this.type; } /** * Sets a custom validation rule for the TextField. * @param grabBag String A list of character to either allow or diallow as input */ public void setCustomValidation(String grabBag) { validateCustom = grabBag; } /** * Attempts to parse an int from the inputted text of the TextField * @return int * @throws NumberFormatException */ public int parseInt() throws NumberFormatException { return Integer.parseInt(getText()); } /** * Attempts to parse a float from the inputted text of the TextField * @return float * @throws NumberFormatException */ public float parseFloat() throws NumberFormatException { return Float.parseFloat(getText()); } /** * Attempts to parse a short from the inputted text of the TextField * @return short * @throws NumberFormatException */ public short parseShort() throws NumberFormatException { return Short.parseShort(getText()); } /** * Attempts to parse a double from the inputted text of the TextField * @return double * @throws NumberFormatException */ public double parseDouble() throws NumberFormatException { return Double.parseDouble(getText()); } /** * Attempts to parse a long from the inputted text of the TextField * @return long * @throws NumberFormatException */ public long parseLong() throws NumberFormatException { return Long.parseLong(getText()); } // Interaction @Override public void onKeyPress(KeyInputEvent evt) { if (evt.getKeyCode() == KeyInput.KEY_F1 || evt.getKeyCode() == KeyInput.KEY_F2 || evt.getKeyCode() == KeyInput.KEY_F3 || evt.getKeyCode() == KeyInput.KEY_F4 || evt.getKeyCode() == KeyInput.KEY_F5 || evt.getKeyCode() == KeyInput.KEY_F6 || evt.getKeyCode() == KeyInput.KEY_F7 || evt.getKeyCode() == KeyInput.KEY_F8 || evt.getKeyCode() == KeyInput.KEY_F9 || evt.getKeyCode() == KeyInput.KEY_CAPITAL || evt.getKeyCode() == KeyInput.KEY_ESCAPE || evt.getKeyCode() == KeyInput.KEY_TAB) { } else if (evt.getKeyCode() == KeyInput.KEY_LCONTROL || evt.getKeyCode() == KeyInput.KEY_RCONTROL) { ctrl = true; } else if (evt.getKeyCode() == KeyInput.KEY_LSHIFT || evt.getKeyCode() == KeyInput.KEY_RSHIFT) { shift = true; } else if (evt.getKeyCode() == KeyInput.KEY_LMENU || evt.getKeyCode() == KeyInput.KEY_RMENU) { alt = true; } else if (evt.getKeyCode() == KeyInput.KEY_LMETA || evt.getKeyCode() == KeyInput.KEY_RMETA) { meta = true; } else if (evt.getKeyCode() == KeyInput.KEY_RETURN) { } else if (evt.getKeyCode() == KeyInput.KEY_DELETE) { if (rangeHead != -1 && rangeTail != -1) editTextRangeText(""); else { if (caretIndex < finalText.length()) textFieldText.remove(caretIndex); } } else if (evt.getKeyCode() == KeyInput.KEY_BACK) { if (rangeHead != -1 && rangeTail != -1) { editTextRangeText(""); } else { if (caretIndex > 0) { textFieldText.remove(caretIndex-1); caretIndex } } } else if (evt.getKeyCode() == KeyInput.KEY_LEFT) { if (!shift) resetTextRange(); if (caretIndex > -1) { if (Screen.isMac()) { if (meta) { caretIndex = 0; getVisibleText(); if (shift) setTextRangeEnd(caretIndex); else { resetTextRange(); setTextRangeStart(caretIndex); } return; } } if ((Screen.isMac() && !alt) || (Screen.isWindows() && !ctrl) || (Screen.isUnix() && !ctrl) || (Screen.isSolaris() && !ctrl)) caretIndex else { int cIndex = caretIndex; if (cIndex > 0) if (finalText.charAt(cIndex-1) == ' ') cIndex int index = 0; if (cIndex > 0) index = finalText.substring(0,cIndex).lastIndexOf(' ')+1; if (index < 0) index = 0; caretIndex = index; } if (caretIndex < 0) caretIndex = 0; if (!shift) setTextRangeStart(caretIndex); } } else if (evt.getKeyCode() == KeyInput.KEY_RIGHT) { if (!shift) resetTextRange(); if (caretIndex <= textFieldText.size()) { if (Screen.isMac()) { if (meta) { caretIndex = textFieldText.size(); getVisibleText(); if (shift) setTextRangeEnd(caretIndex); else { resetTextRange(); setTextRangeStart(caretIndex); } return; } } if ((Screen.isMac() && !alt) || (Screen.isWindows() && !ctrl) || (Screen.isUnix() && !ctrl) || (Screen.isSolaris() && !ctrl)) caretIndex++; else { int cIndex = caretIndex; if (cIndex < finalText.length()) if (finalText.charAt(cIndex) == ' ') cIndex++; int index; if (cIndex < finalText.length()) { index = finalText.substring(cIndex, finalText.length()).indexOf(' '); if (index == -1) index = finalText.length(); else index += cIndex; } else { index = finalText.length(); } caretIndex = index; } if (caretIndex > finalText.length()) caretIndex = finalText.length(); if (!shift) { if (caretIndex < textFieldText.size()) setTextRangeStart(caretIndex); else setTextRangeStart(textFieldText.size()); } } } else if (evt.getKeyCode() == KeyInput.KEY_END || evt.getKeyCode() == KeyInput.KEY_NEXT || evt.getKeyCode() == KeyInput.KEY_DOWN) { caretIndex = textFieldText.size(); getVisibleText(); if (shift) setTextRangeEnd(caretIndex); else { resetTextRange(); setTextRangeStart(caretIndex); } } else if (evt.getKeyCode() == KeyInput.KEY_HOME || evt.getKeyCode() == KeyInput.KEY_PRIOR || evt.getKeyCode() == KeyInput.KEY_UP) { caretIndex = 0; getVisibleText(); if (shift) setTextRangeEnd(caretIndex); else { resetTextRange(); setTextRangeStart(caretIndex); } } else { if (ctrl) { if (evt.getKeyCode() == KeyInput.KEY_C) { if (copy) screen.setClipboardText(textRangeText); } else if (evt.getKeyCode() == KeyInput.KEY_V) { if (paste) this.pasteTextInto(); } } else { if (isEnabled) { if (rangeHead != -1 && rangeTail != -1) { editTextRangeText(""); } if (!shift) resetTextRange(); nextChar = String.valueOf(evt.getKeyChar()); if (forceUpperCase) nextChar = nextChar.toUpperCase(); else if (forceLowerCase) nextChar = nextChar.toLowerCase(); valid = true; if (maxLength > 0) { if (getText().length() >= maxLength) valid =false; } if (valid) { if (type == Type.DEFAULT) { textFieldText.add(caretIndex, nextChar); caretIndex++; } else if (type == Type.ALPHA) { if (validateAlpha.indexOf(nextChar) != -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.ALPHA_NOSPACE) { if (validateAlpha.indexOf(nextChar) != -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.NUMERIC) { if (validateNumeric.indexOf(nextChar) != -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.ALPHANUMERIC) { if (validateAlpha.indexOf(nextChar) != -1 || validateNumeric.indexOf(nextChar) != -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.ALPHANUMERIC_NOSPACE) { if (validateAlphaNoSpace.indexOf(nextChar) != -1 || validateNumeric.indexOf(nextChar) != -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.EXCLUDE_SPECIAL) { if (validateSpecChar.indexOf(nextChar) == -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.EXCLUDE_CUSTOM) { if (validateCustom.indexOf(nextChar) == -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } else if (type == Type.INCLUDE_CUSTOM) { if (validateCustom.indexOf(nextChar) != -1) { textFieldText.add(caretIndex, nextChar); caretIndex++; } } } if (!shift) { if (caretIndex < textFieldText.size()) setTextRangeStart(caretIndex); else setTextRangeStart(textFieldText.size()); } } } } this.updateText(getVisibleText()); if (shift && (evt.getKeyCode() == KeyInput.KEY_LEFT || evt.getKeyCode() == KeyInput.KEY_RIGHT)) setTextRangeEnd(caretIndex); centerTextVertically(); controlKeyPressHook(evt, getText()); evt.setConsumed(); } /** * An overridable hook for the onKeyPress event of the TextField * @param evt KeyInputEvent * @param text String */ public void controlKeyPressHook(KeyInputEvent evt, String text) { } @Override public void onKeyRelease(KeyInputEvent evt) { if (evt.getKeyCode() == KeyInput.KEY_LCONTROL || evt.getKeyCode() == KeyInput.KEY_RCONTROL) { ctrl = false; } else if (evt.getKeyCode() == KeyInput.KEY_LSHIFT || evt.getKeyCode() == KeyInput.KEY_RSHIFT) { shift = false; } else if (evt.getKeyCode() == KeyInput.KEY_LMENU || evt.getKeyCode() == KeyInput.KEY_RMENU) { alt = false; } else if (evt.getKeyCode() == KeyInput.KEY_LMETA || evt.getKeyCode() == KeyInput.KEY_RMETA) { meta = false; } evt.setConsumed(); } /** * Internal use - NEVER USE THIS!! */ protected void getTextFieldText() { String ret = ""; int index = 0; for (String s : textFieldText) { ret += s; index++; } finalText = ret; } /** * This method now forwards to setText. Feel free to use setText directly. * @param text String The text to set for the TextField */ @Deprecated public void setTextFieldText(String text) { setText(text); } @Override public void setText(String s) { caretIndex = 0; textFieldText.clear(); for (int i = 0; i < s.length(); i++) { textFieldText.add(caretIndex, String.valueOf(s.charAt(i))); caretIndex++; } this.updateText(getVisibleText()); setCaretPositionToEnd(); centerTextVertically(); } @Override public final void setFontSize(float fontSize) { this.fontSize = fontSize; if (textElement != null) { textElement.setSize(fontSize); } } @Override public String getText() { String ret = ""; int index = 0; for (String s : textFieldText) { ret += s; index++; } return ret; } /** * Returns the visible portion of the TextField's text * @return String */ protected String getVisibleText() { getTextFieldText(); widthTest = new BitmapText(font, false); widthTest.setBox(null); widthTest.setSize(getFontSize()); int index1 = 0, index2; widthTest.setText(finalText); if (head == -1 || tail == -1 || widthTest.getLineWidth() < getWidth()) { head = 0; tail = finalText.length(); if (head != tail && head != -1 && tail != -1) visibleText = finalText.substring(head, tail); else visibleText = ""; } else if (caretIndex < head) { head = caretIndex; index2 = caretIndex; if (index2 == caretIndex && caretIndex != textFieldText.size()) { index2 = caretIndex+1; widthTest.setText(finalText.substring(caretIndex, index2)); while(widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) { if (index2 == textFieldText.size()) break; widthTest.setText(finalText.substring(caretIndex, index2+1)); if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) { index2++; } } } if (index2 != textFieldText.size()) index2++; tail = index2; if (head != tail && head != -1 && tail != -1) visibleText = finalText.substring(head, tail); else visibleText = ""; } else if (caretIndex > tail) { tail = caretIndex; index2 = caretIndex; if (index2 == caretIndex && caretIndex != 0) { index2 = caretIndex-1; widthTest.setText(finalText.substring(index2, caretIndex)); while(widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) { if (index2 == 0) break; widthTest.setText(finalText.substring(index2-1, caretIndex)); if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) { index2 } } } head = index2; if (head != tail && head != -1 && tail != -1) visibleText = finalText.substring(head, caretIndex); else visibleText = ""; } else { index2 = tail; if (index2 > finalText.length()) index2 = finalText.length(); if (tail != head) { widthTest.setText(finalText.substring(head, index2)); if (widthTest.getLineWidth() > getWidth()-(getTextPadding()*2)) { while(widthTest.getLineWidth() > getWidth()-(getTextPadding()*2)) { if (index2 == head) break; widthTest.setText(finalText.substring(head, index2-1)); if (widthTest.getLineWidth() > getWidth()-(getTextPadding()*2)) { index2 } } } else if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) { while(widthTest.getLineWidth() < getWidth()-(getTextPadding()*2) && index2 < finalText.length()) { if (index2 == head) break; widthTest.setText(finalText.substring(head, index2+1)); if (widthTest.getLineWidth() < getWidth()-(getTextPadding()*2)) { index2++; } } } } tail = index2; if (head != tail && head != -1 && tail != -1) visibleText = finalText.substring(head, tail); else visibleText = ""; } String testString = ""; widthTest.setText("."); float fixWidth = widthTest.getLineWidth(); boolean useFix = false; if (!finalText.equals("")) { try { testString = finalText.substring(head, caretIndex); if (testString.charAt(testString.length()-1) == ' ') { testString += "."; useFix = true; } } catch (Exception ex) { } } widthTest.setText(testString); float nextCaretX = widthTest.getLineWidth(); if (useFix) nextCaretX -= fixWidth; caretX = nextCaretX; setCaretPosition(getAbsoluteX()+caretX); return visibleText; } private void setCaretPositionToIndex() { widthTest.setText("."); float fixWidth = widthTest.getLineWidth(); boolean useFix = false; if (!finalText.equals("")) { String testString = finalText.substring(head, caretIndex); try { if (testString.charAt(testString.length()-1) == ' ') { testString += "."; useFix = true; } } catch (Exception ex) { } widthTest.setText(testString); float nextCaretX = widthTest.getLineWidth(); if (useFix) nextCaretX -= fixWidth; caretX = nextCaretX; setCaretPosition(getAbsoluteX()+caretX); } } /** * For internal use - do not call this method * @param caretX float */ protected void setCaretPosition(float caretX) { if (textElement != null) { if (hasTabFocus) { caret.getMaterial().setFloat("CaretX", caretX+getTextPadding()); caret.getMaterial().setFloat("LastUpdate", app.getTimer().getTimeInSeconds()); } } } /** * For internal use - do not call this method * @param x float */ private void setCaretPositionByX(float x) { int index1 = visibleText.length(); if (visibleText.length() > 0) { widthTest.setSize(getFontSize()); widthTest.setText(visibleText.substring(0, index1)); while(caret.getAbsoluteX()+widthTest.getLineWidth() > (x+getTextPadding())) { index1 widthTest.setText(visibleText.substring(0, index1)); } caretX = widthTest.getLineWidth(); } caretIndex = head+index1; setCaretPosition(getAbsoluteX()+caretX); if (!shift) { resetTextRange(); setTextRangeStart(caretIndex); } else { setTextRangeEnd(caretIndex); } } private void setCaretPositionByXNoRange(float x) { int index1 = visibleText.length(); if (visibleText.length() > 0) { String testString = ""; widthTest.setText("."); float fixWidth = widthTest.getLineWidth(); boolean useFix = false; widthTest.setSize(getFontSize()); widthTest.setText(visibleText.substring(0, index1)); while(caret.getAbsoluteX()+widthTest.getLineWidth() > (x+getTextPadding())) { if (index1 > 0) { index1 testString = visibleText.substring(0, index1); widthTest.setText(testString); } else { break; } } try { testString = finalText.substring(head, caretIndex); if (testString.charAt(testString.length()-1) == ' ') { testString += "."; useFix = true; } } catch (Exception ex) { } widthTest.setText(testString); float nextCaretX = widthTest.getLineWidth(); if (useFix) nextCaretX -= fixWidth; caretX = nextCaretX; } caretIndex = head+index1; setCaretPosition(getAbsoluteX()+caretX); } /** * Sets the caret position to the end of the TextField's text */ public void setCaretPositionToEnd() { int index1 = visibleText.length(); if (visibleText.length() > 0) { widthTest.setText(visibleText.substring(0, index1)); caretX = widthTest.getLineWidth(); } caretIndex = head+index1; setCaretPosition(getAbsoluteX()+caretX); resetTextRange(); } private void pasteTextInto() { String text = screen.getClipboardText(); editTextRangeText(text); } /** * Sets the ColorRGBA value used for text & caret * @param fontColor ColorRGBA */ public final void setTextFieldFontColor(ColorRGBA fontColor) { setFontColor(fontColor); caretMat.setColor("Color", fontColor); } /** * Enables/disables the TextField * @param isEnabled boolean */ public void setIsEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } /** * Returns if the TextField is currently enabled/disabled * @return boolean */ public boolean getIsEnabled() { return this.isEnabled; } /** * Enables/disables the use of the Copy text feature * @param copy boolean */ public void setAllowCopy(boolean copy) { this.copy = copy; } /** * Returns if the Copy feature is enabled/disabled * @return copy */ public boolean getAllowCopy() { return this.copy; } /** * Eanbles/disables use of the Paste text feature * @param paste boolean */ public void setAllowPaste(boolean paste) { this.paste = paste; } /** * Returns if the Paste feature is enabled/disabled * @return paste */ public boolean getAllowPaste() { return this.paste; } /** * Enables/disables both the Copy and Paste feature * @param copyAndPaste boolean */ public void setAllowCopyAndPaste(boolean copyAndPaste) { this.copy = copyAndPaste; this.paste = copyAndPaste; } /** * Forces all text input to uppercase * @param forceUpperCase boolean */ public void setForceUpperCase(boolean forceUpperCase) { this.forceUpperCase = forceUpperCase; this.forceLowerCase = false; } /** * Returns if the TextField is set to force uppercase * @return boolean */ public boolean getForceUpperCase() { return this.forceUpperCase; } /** * Forces all text input to lowercase * @return boolean */ public void setForceLowerCase(boolean forceLowerCase) { this.forceLowerCase = forceLowerCase; this.forceUpperCase = false; } /** * Returns if the TextField is set to force lowercase * @return boolean */ public boolean getForceLowerCase() { return this.forceLowerCase; } /** * Set the maximum character limit for the TextField. 0 = unlimited * @param maxLength int */ public void setMaxLength(int maxLength) { this.maxLength = maxLength; } /** * Returns the maximum limit of character allowed for this TextField * @return int */ public int getMaxLength() { return this.maxLength; } @Override public void setTabFocus() { hasTabFocus = true; setTextRangeStart(caretIndex); if (isEnabled) caret.getMaterial().setBoolean("HasTabFocus", true); screen.setKeyboardElement(this); controlTextFieldSetTabFocusHook(); Effect effect = getEffect(Effect.EffectEvent.TabFocus); if (effect != null) { effect.setColor(ColorRGBA.DarkGray); screen.getEffectManager().applyEffect(effect); } if (isEnabled && !this.controls.contains(this)) { addControl(this); } } @Override public void resetTabFocus() { hasTabFocus = false; shift = false; ctrl = false; alt = false; caret.getMaterial().setBoolean("HasTabFocus", false); screen.setKeyboardElement(null); controlTextFieldResetTabFocusHook(); Effect effect = getEffect(Effect.EffectEvent.LoseTabFocus); if (effect != null) { effect.setColor(ColorRGBA.White); screen.getEffectManager().applyEffect(effect); } if (isEnabled && this.controls.contains(this)) { removeControl(this); } } /** * Overridable hook for receive tab focus event */ public void controlTextFieldSetTabFocusHook() { } /** * Overridable hook for lose tab focus event */ public void controlTextFieldResetTabFocusHook() { } @Override public void onGetFocus(MouseMotionEvent evt) { if (getIsEnabled()) screen.setCursor(CursorType.TEXT); setHasFocus(true); } @Override public void onLoseFocus(MouseMotionEvent evt) { if (getIsEnabled()) screen.setCursor(CursorType.POINTER); setHasFocus(false); } public final void updateText(String text) { this.text = text; if (textElement == null) { textElement = new BitmapText(font, false); textElement.setBox(new Rectangle(0,0,getDimensions().x,getDimensions().y)); // textElement = new TextElement(screen, Vector2f.ZERO); centerTextVertically(); } textElement.setLineWrapMode(textWrap); textElement.setAlignment(textAlign); textElement.setVerticalAlignment(textVAlign); textElement.setSize(fontSize); textElement.setColor(fontColor); textElement.setText(text); updateTextElement(); if (textElement.getParent() == null) { this.attachChild(textElement); } centerTextVertically(); } private void centerTextVertically() { float height = BitmapTextUtil.getTextLineHeight(this, testString); float nextY = height-FastMath.floor(getHeight()); nextY /= 2; nextY = (float)FastMath.ceil(nextY)+1; setTextPosition(getTextPosition().x, -nextY); } @Override public void onMouseLeftPressed(MouseButtonEvent evt) { if (this.isEnabled) { float time = screen.getApplication().getTimer().getTimeInSeconds(); if (time-compareClick > .2f) resetClickCounter(); compareClick = time; isPressed = true; clickCount++; switch (clickCount) { case 1: firstClick = time; resetTextRange(); setCaretPositionByXNoRange(evt.getX()); if (caretIndex >= 0) this.setTextRangeStart(caretIndex); else this.setTextRangeStart(0); break; case 2: secondClick = time; firstClickDiff = time-firstClick; if (firstClickDiff <= 0.2f) { doubleClick = true; } else { resetClickCounter(); } break; case 3: secondClickDiff = time-secondClick; if (secondClickDiff <= 0.2f) { tripleClick = true; } resetClickCounter(); break; default: resetClickCounter(); } } } private void resetClickCounter() { clickCount = 0; firstClick = 0; secondClick = 0; firstClickDiff = 0; secondClickDiff = 0; } @Override public void onMouseLeftReleased(MouseButtonEvent evt) { if (isEnabled) { if (isPressed) { isPressed = false; if (doubleClick) { selectTextRangeDoubleClick(); doubleClick = false; } else if (tripleClick) { selectTextRangeTripleClick(); tripleClick = false; } else { setCaretPositionByXNoRange(evt.getX()); if (caretIndex >= 0) this.setTextRangeEnd(caretIndex); else this.setTextRangeEnd(0); } } } } @Override public void onMouseRightPressed(MouseButtonEvent evt) { } @Override public void onMouseRightReleased(MouseButtonEvent evt) { } private void stillPressedInterval() { if (screen.getMouseXY().x > getAbsoluteWidth() && caretIndex < finalText.length()) caretIndex++; else if (screen.getMouseXY().x < getAbsoluteX() && caretIndex > 0) caretIndex updateText(getVisibleText()); setCaretPositionByXNoRange(screen.getMouseXY().x); if (caretIndex >= 0) this.setTextRangeEnd(caretIndex); else this.setTextRangeEnd(0); } // Text Range methods /** * Sets the current text range to all text within the TextField */ public void selectTextRangeAll() { setTextRangeStart(0); setTextRangeEnd(finalText.length()); caretIndex = finalText.length(); getVisibleText(); } /** * Resets the current text range */ public void selectTextRangeNone() { this.resetTextRange(); } /** * Sets the current text range to the first instance of the provided string, if found * @param s The String to search for */ public void selectTextRangeBySubstring(String s) { int head = finalText.indexOf(s); if (head != -1) { setTextRangeStart(head); int tail = head+s.length(); setTextRangeEnd(tail); caretIndex = tail; getVisibleText(); } } /** * Sets the selected text range to head-tail or tail-head depending on the provided indexes. * Selects nothing if either of the provided indexes are out of range * @param head The start or end index of the desired text range * @param tail The end or start index of the desired text range */ public void selectTextRangeByIndex(int head, int tail) { int nHead = head; int nTail = tail; if (head > tail) { nHead = tail; nTail = head; } if (nHead < 0) nHead = 0; if (nTail > finalText.length()) nTail = finalText.length(); this.setTextRangeStart(nHead); this.setTextRangeEnd(nTail); caretIndex = nTail; getVisibleText(); } private void selectTextRangeDoubleClick() { if (!finalText.equals("")) { int end; if (finalText.substring(caretIndex, finalText.length()).indexOf(' ') != -1) end = caretIndex+finalText.substring(caretIndex, finalText.length()).indexOf(' '); else end = caretIndex+finalText.substring(caretIndex, finalText.length()).length(); int start = finalText.substring(0,caretIndex).lastIndexOf(' ')+1; if (start == -1) start = 0; setTextRangeStart(start); caretIndex = end; updateText(getVisibleText()); setTextRangeEnd(end); } } private void selectTextRangeTripleClick() { if (!finalText.equals("")) { caretIndex = finalText.length(); updateText(getVisibleText()); setTextRangeStart(0); setTextRangeEnd(finalText.length()); } } private void setTextRangeStart(int head) { if (!visibleText.equals("")) { rangeHead = head; } } private void setTextRangeEnd(int tail) { if (!visibleText.equals("") && rangeHead != -1) { widthTest.setSize(getFontSize()); widthTest.setText("."); float diff = widthTest.getLineWidth(); float rangeX; if (rangeHead-this.head <= 0) { widthTest.setText(""); rangeX = widthTest.getLineWidth(); } else if(rangeHead-this.head < visibleText.length()) { widthTest.setText(visibleText.substring(0, rangeHead-this.head)); float width = widthTest.getLineWidth(); if (widthTest.getText().length() > 0) { if (widthTest.getText().charAt(widthTest.getText().length()-1) == ' ') { widthTest.setText(widthTest.getText() + "."); width = widthTest.getLineWidth()-diff; } } rangeX = width; } else { widthTest.setText(visibleText); rangeX = widthTest.getLineWidth(); } if (rangeHead >= this.head) rangeX = getAbsoluteX()+rangeX+getTextPadding(); else rangeX = getTextPadding(); rangeTail = tail; if (tail-this.head <= 0) widthTest.setText(""); else if (tail-this.head < visibleText.length()) widthTest.setText(visibleText.substring(0, tail-this.head)); else widthTest.setText(visibleText); textRangeText = (rangeHead < rangeTail) ? finalText.substring(rangeHead, rangeTail) : finalText.substring(rangeTail, rangeHead); float rangeW = getTextPadding(); if (rangeTail <= this.tail) { float width = widthTest.getLineWidth(); if (widthTest.getText().length() > 0) { if (widthTest.getText().charAt(widthTest.getText().length()-1) == ' ') { widthTest.setText(widthTest.getText() + "."); width = widthTest.getLineWidth()-diff; } } rangeW = getAbsoluteX()+width+getTextPadding(); } if (rangeHead > rangeTail) { caret.getMaterial().setFloat("TextRangeStart", rangeW); caret.getMaterial().setFloat("TextRangeEnd", rangeX); } else { caret.getMaterial().setFloat("TextRangeStart", rangeX); caret.getMaterial().setFloat("TextRangeEnd", rangeW); } caret.getMaterial().setBoolean("ShowTextRange", true); } } private void resetTextRange() { textRangeText = ""; rangeHead = -1; rangeTail = -1; caret.getMaterial().setFloat("TextRangeStart", 0); caret.getMaterial().setFloat("TextRangeEnd", 0); caret.getMaterial().setBoolean("ShowTextRange", false); } private void editTextRangeText(String insertText) { int head, tail; if (rangeHead != -1 && rangeTail != -1) { head = rangeHead; tail = rangeTail; if (head < 0) head = 0; else if (head > finalText.length()) head = finalText.length(); if (tail < 0) tail = 0; else if (tail > finalText.length()) tail = finalText.length(); resetTextRange(); } else { head = caretIndex-1; if (head == -1) head = 0; tail = caretIndex; } String newText; int tempIndex; if (tail > head) { newText = finalText.substring(0,head) + insertText + finalText.substring(tail, finalText.length()); tempIndex = head+insertText.length(); } else { newText = finalText.substring(0,tail) + insertText + finalText.substring(head, finalText.length()); tempIndex = tail+insertText.length(); } try { newText = newText.replace("\r", ""); } catch (Exception ex) { } try { newText = newText.replace("\n", ""); } catch (Exception ex) { } if (this.type != Type.DEFAULT) { String grabBag = ""; switch (type) { case EXCLUDE_CUSTOM: grabBag = validateCustom; break; case EXCLUDE_SPECIAL: grabBag = validateSpecChar; break; case ALPHA: grabBag = validateAlpha; break; case ALPHA_NOSPACE: grabBag = validateAlphaNoSpace; break; case NUMERIC: grabBag = validateNumeric; break; case ALPHANUMERIC: grabBag = validateAlpha + validateNumeric; break; case ALPHANUMERIC_NOSPACE: grabBag = validateAlphaNoSpace + validateNumeric; break; } if (this.type == Type.EXCLUDE_CUSTOM || this.type == Type.EXCLUDE_SPECIAL) { for (int i = 0; i < grabBag.length(); i++) { try { String ret = newText.replace(String.valueOf(grabBag.charAt(i)), ""); if (ret != null) newText = ret; } catch (Exception ex) { } } } else { String ret = newText; for (int i = 0; i < newText.length(); i++) { try { int index = grabBag.indexOf(String.valueOf(newText.charAt(i))); if (index == -1) { String temp = ret.replace(String.valueOf(String.valueOf(newText.charAt(i))), ""); if (temp != null) ret = temp; } } catch (Exception ex) { } } if (!ret.equals("")) newText = ret; } tempIndex = newText.length(); } if (maxLength != 0 && newText.length() > maxLength) { newText = newText.substring(0, maxLength); tempIndex = maxLength; } int testIndex = (head > tail) ? tail : head; setText(newText); caretIndex = testIndex; } // Control methods @Override public Control cloneForSpatial(Spatial spatial) { return this; } @Override public void setSpatial(Spatial spatial) { } @Override public void update(float tpf) { if (isPressed) { stillPressedInterval(); } } @Override public void render(RenderManager rm, ViewPort vp) { } }
package uk.ac.kent.dover.fastGraph; import org.cytoscape.gedevo.GedevoNativeUtil; import uk.ac.kent.dover.fastGraph.ExactMotifFinder.IsoHolder; import uk.ac.kent.dover.fastGraph.Gui.LauncherGUI; import uk.ac.kent.dover.fastGraph.Gui.MotifTask; import uk.ac.kent.dover.fastGraph.comparators.AlwaysTrueEdgeComparator; import uk.ac.kent.dover.fastGraph.comparators.AlwaysTrueNodeComparator; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; /** * Main class from which all the other functionality is called. * * @author Rob Baker * */ public class Launcher { public static final String startingWorkingDirectory = System.getProperty("user.dir"); public final String DATA_URL = "https: /** * Main method * * If no parameters given, loads GUI interface. Otherwise: * * Takes in a variety of parameters which are detailed in LauncherCmd, or by running with the -h parameter. * * @param args The command line instructions given * @throws Exception Only used when testing direct access to FastGraph */ public static void main(String[] args) throws Exception{ Debugger.enabled = false; new Launcher(args); } /** * Constructor to avoid every method being static * * @param args The command line instructions given * @throws Exception Only used when testing direct access to FastGraph */ public Launcher(String[] args) throws Exception{ //System.out.println("Launched!"); //System.out.println(Arrays.toString(args)); //System.out.println(args.length); GedevoNativeUtil.initNativeLibs(); //if there are no arguments given, then load the GUI. Otherwise, load the command line interface if (args.length == 0) { new LauncherGUI(this); //FastGraph.main(args); //will replace this with loading GUI instead } else { new LauncherCmd(this, args); //FastGraph.main(args); //will replace this with some actual handling of arguments } } /** * Loads a graph from buffers. Called by both Launcher modes * * @param directory The directory to load the buffers from * @param fileBaseName The name of the buffers * @return The FastGraph loaded * @throws IOException Thrown if the buffers cannot be loaded */ public FastGraph loadFromBuffers(String directory, String fileBaseName) throws IOException { return FastGraph.loadBuffersGraphFactory(directory, fileBaseName); } /** * Calls the conversion method to convert an Adjacency List to Buffers * * @param nodeCount The number of nodes in the graph * @param edgeCount The number of edges in the graph * @param directory The directory to load the list from * @param fileName The file name of the list * @param direct Is the graph directed * @throws Exception If the file cannot be loaded, or in the wrong format, or the buffers cannot be saved */ public void convertGraphToBuffers(int nodeCount, int edgeCount, String directory, String fileName, boolean direct) throws Exception { FastGraph g1 = FastGraph.adjacencyListGraphFactory(nodeCount, edgeCount, directory, fileName, direct); g1.saveBuffers(null,fileName); } /** * Calls the method to find all motifs with the parameters given * * @param mt The MotifTask to handle GUI updates * @param directory The directory of the graph to be loaded * @param fileBaseName The name of the graph to be loaded * @param minNum The minimum size of motifs * @param maxNum The maximum size of motifs * @param saveAll If every example is to be saved * @throws IOException If the files cannot be loaded */ public void findMotifs(MotifTask mt, String directory, String fileBaseName, int minNum, int maxNum, boolean saveAll) throws IOException { double sizeDiff = maxNum - minNum; double step = 100/(sizeDiff+4); mt.publish(0, "Loading Buffers", 0, ""); mt.setSmallIndeterminate(true); FastGraph g2 = FastGraph.loadBuffersGraphFactory(directory, fileBaseName); mt.setSmallIndeterminate(false); ExactMotifFinder emf = new ExactMotifFinder(g2,mt, saveAll); mt.publish((int) step, "Building Reference Set", 0, ""); emf.findAllMotifs(10,minNum,maxNum); mt.publish((int) (100-(2*step)), "Building Main Set", 0, ""); emf.findAllMotifs(0,minNum,maxNum); mt.publish((int) (100-step), "Comparing Motif Sets", 0, ""); emf.compareMotifDatas(minNum,maxNum); //emf.compareAndExportResults(referenceBuckets, realBuckets); //emf.outputHashBuckets(referenceBuckets); Debugger.outputTime("Time total motif detection"); mt.publish(100, "Complete", 0, ""); } /** * Calls the method to find all subgraphs * * @param targetGraph The graph to search in * @param patternGraph The subgraph to find */ public void findSubgraphMappings(FastGraph targetGraph, FastGraph patternGraph) { //AlwaysTrueNodeComparator atnc = new AlwaysTrueNodeComparator(targetGraph, patternGraph); //AlwaysTrueEdgeComparator atec = new AlwaysTrueEdgeComparator(targetGraph, patternGraph); ExactSubgraphIsomorphism esi = new ExactSubgraphIsomorphism(targetGraph, patternGraph, null, null); boolean result = esi.subGraphIsomorphismFinder(); System.out.println("result:" + result); System.out.println(esi.getFoundMappings()); esi = null; } }
package uk.co.placona.helloWorld; public class HelloWorld { public String sayHello() { return "Hello World"; } }
package uk.org.cinquin.mutinack; import static contrib.uk.org.lidalia.slf4jext.Level.TRACE; import static uk.org.cinquin.mutinack.MutationType.INSERTION; import static uk.org.cinquin.mutinack.MutationType.SUBSTITUTION; import static uk.org.cinquin.mutinack.MutationType.WILDTYPE; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.DISAGREEMENT; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.MISSING_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.N_READS_PER_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.QUALITY_AT_POSITION; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.FRACTION_WRONG_PAIRS_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_DPLX_Q_IGNORING_DISAG; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_Q_FOR_ALL_DUPLEXES; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_CANDIDATE_PHRED; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_PHRED_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.NO_DUPLEXES; import static uk.org.cinquin.mutinack.misc_util.DebugLogControl.NONTRIVIAL_ASSERTIONS; import static uk.org.cinquin.mutinack.misc_util.Util.basesEqual; import static uk.org.cinquin.mutinack.qualities.Quality.ATROCIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.DUBIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.GOOD; import static uk.org.cinquin.mutinack.qualities.Quality.MINIMUM; import static uk.org.cinquin.mutinack.qualities.Quality.POOR; import static uk.org.cinquin.mutinack.qualities.Quality.max; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.list.primitive.MutableFloatList; import org.eclipse.collections.api.multimap.set.MutableSetMultimap; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.MutableSet; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList; import org.eclipse.collections.impl.set.mutable.UnifiedSet; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import contrib.net.sf.picard.reference.ReferenceSequence; import contrib.net.sf.samtools.CigarOperator; import contrib.net.sf.samtools.SAMRecord; import contrib.net.sf.samtools.SamPairUtil; import contrib.net.sf.samtools.SamPairUtil.PairOrientation; import contrib.net.sf.samtools.util.StringUtil; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; import gnu.trove.list.array.TByteArrayList; import gnu.trove.map.TByteObjectMap; import gnu.trove.map.hash.TByteObjectHashMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.set.hash.TCustomHashSet; import gnu.trove.set.hash.THashSet; import uk.org.cinquin.mutinack.candidate_sequences.CandidateBuilder; import uk.org.cinquin.mutinack.candidate_sequences.CandidateCounter; import uk.org.cinquin.mutinack.candidate_sequences.CandidateDeletion; import uk.org.cinquin.mutinack.candidate_sequences.CandidateSequence; import uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay; import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock; import uk.org.cinquin.mutinack.candidate_sequences.PositionAssay; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.ComparablePair; import uk.org.cinquin.mutinack.misc_util.DebugLogControl; import uk.org.cinquin.mutinack.misc_util.Handle; import uk.org.cinquin.mutinack.misc_util.Pair; import uk.org.cinquin.mutinack.misc_util.SettableDouble; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.collections.HashingStrategies; import uk.org.cinquin.mutinack.misc_util.collections.InterningSet; import uk.org.cinquin.mutinack.misc_util.exceptions.AssertionFailedException; import uk.org.cinquin.mutinack.output.LocationExaminationResults; import uk.org.cinquin.mutinack.qualities.DetailedPositionQualities; import uk.org.cinquin.mutinack.qualities.DetailedQualities; import uk.org.cinquin.mutinack.qualities.Quality; import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter; import uk.org.cinquin.mutinack.statistics.Histogram; public final class SubAnalyzer { private static final Logger logger = LoggerFactory.getLogger(SubAnalyzer.class); public final @NonNull Mutinack analyzer; @NonNull Parameters param; @NonNull AnalysisStats stats;//Will in fact be null until set in SubAnalyzerPhaser but that's OK final @NonNull SettableInteger lastProcessablePosition = new SettableInteger(-1); final @NonNull THashMap<SequenceLocation, THashSet<CandidateSequence>> candidateSequences = new THashMap<>(1_000); int truncateProcessingAt = Integer.MAX_VALUE; int startProcessingAt = 0; MutableList<@NonNull DuplexRead> analyzedDuplexes; float[] averageClipping; int averageClippingOffset = Integer.MAX_VALUE; final @NonNull THashMap<String, @NonNull ExtendedSAMRecord> extSAMCache = new THashMap<>(10_000, 0.5f); private final AtomicInteger threadCount = new AtomicInteger(); @NonNull Map<@NonNull ExtendedSAMRecord, @NonNull SAMRecord> readsToWrite = new THashMap<>(); private final Random random; private static final @NonNull Set<DuplexAssay> assaysToIgnoreForDisagreementQuality = Collections.unmodifiableSet(EnumSet.copyOf(Collections.singletonList(DISAGREEMENT))), assaysToIgnoreForDuplexNStrands = Collections.unmodifiableSet(EnumSet.copyOf(Arrays.asList(N_READS_PER_STRAND, MISSING_STRAND))); static final @NonNull TByteObjectMap<@NonNull String> byteMap; static { byteMap = new TByteObjectHashMap<>(); byteMap.put((byte) 'A', "A"); byteMap.put((byte) 'a', "A"); byteMap.put((byte) 'T', "T"); byteMap.put((byte) 't', "T"); byteMap.put((byte) 'G', "G"); byteMap.put((byte) 'g', "G"); byteMap.put((byte) 'C', "C"); byteMap.put((byte) 'c', "C"); byteMap.put((byte) 'N', "N"); byteMap.put((byte) 'n', "N"); } static final @NonNull TByteObjectMap<byte @NonNull[]> byteArrayMap; static { byteArrayMap = new TByteObjectHashMap<>(); byteArrayMap.put((byte) 'A', new byte[] {'A'}); byteArrayMap.put((byte) 'a', new byte[] {'a'}); byteArrayMap.put((byte) 'T', new byte[] {'T'}); byteArrayMap.put((byte) 't', new byte[] {'t'}); byteArrayMap.put((byte) 'G', new byte[] {'G'}); byteArrayMap.put((byte) 'g', new byte[] {'g'}); byteArrayMap.put((byte) 'C', new byte[] {'C'}); byteArrayMap.put((byte) 'c', new byte[] {'c'}); byteArrayMap.put((byte) 'N', new byte[] {'N'}); byteArrayMap.put((byte) 'n', new byte[] {'n'}); } private volatile boolean writing = false; synchronized void queueOutputRead(@NonNull ExtendedSAMRecord e, @NonNull SAMRecord r, boolean mayAlreadyBeQueued) { Assert.isFalse(writing); final SAMRecord previous; if ((previous = readsToWrite.put(e, r)) != null && !mayAlreadyBeQueued) { throw new IllegalStateException("Read " + e.getFullName() + " already queued for writing; new: " + r.toString() + "; previous: " + previous.toString()); } } void writeOutputReads() { writing = true; try { synchronized(analyzer.outputAlignmentWriter) { for (SAMRecord samRecord: readsToWrite.values()) { Objects.requireNonNull(analyzer.outputAlignmentWriter).addAlignment(samRecord); } } readsToWrite.clear(); } finally { writing = false; } } @SuppressWarnings("null")//Stats not initialized straight away SubAnalyzer(@NonNull Mutinack analyzer) { this.analyzer = analyzer; this.param = analyzer.param; useHashMap = param.alignmentPositionMismatchAllowed == 0; random = new Random(param.randomSeed); } private boolean meetsQ2Thresholds(@NonNull ExtendedSAMRecord extendedRec) { return !extendedRec.formsWrongPair() && extendedRec.getnClipped() <= param.maxAverageBasesClipped && extendedRec.getMappingQuality() >= param.minMappingQualityQ2 && Math.abs(extendedRec.getInsertSize()) <= param.maxInsertSize; } /** * Make sure that concurring reads get associated with a unique candidate. * We should *not* insert candidates directly into candidateSequences. * Get interning as a small, beneficial side effect. * @param candidate * @param location * @return */ private @NonNull CandidateSequence insertCandidateAtPosition(@NonNull CandidateSequence candidate, @NonNull SequenceLocation location) { //No need for synchronization since we should not be //concurrently inserting two candidates at the same position THashSet<CandidateSequence> candidates = candidateSequences.computeIfAbsent(location, k -> new THashSet<>(2)); CandidateSequence candidateMapValue = candidates.get(candidate); if (candidateMapValue == null) { boolean added = candidates.add(candidate); Assert.isTrue(added); } else { candidateMapValue.mergeWith(candidate); candidate = candidateMapValue; } return candidate; } /** * Load all reads currently referred to by candidate sequences and group them into DuplexReads * @param toPosition * @param fromPosition */ void load(int fromPosition, int toPosition) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { if (toPosition < fromPosition) { throw new IllegalArgumentException("Going from " + fromPosition + " to " + toPosition); } final List<@NonNull DuplexRead> resultDuplexes = new ArrayList<>(3_000); loadAll(fromPosition, toPosition, resultDuplexes); analyzedDuplexes = Lists.mutable.withAll(resultDuplexes); } finally { if (NONTRIVIAL_ASSERTIONS) { threadCount.decrementAndGet(); } } } void checkAllDone() { if (!candidateSequences.isEmpty()) { final SettableInteger nLeftBehind = new SettableInteger(-1); candidateSequences.forEach((k,v) -> { Assert.isTrue(v.isEmpty() || (v.iterator().next().getLocation().equals(k)), "Mismatched locations"); String s = v.stream(). filter(c -> c.getLocation().position > truncateProcessingAt + param.maxInsertSize && c.getLocation().position < startProcessingAt - param.maxInsertSize). flatMap(v0 -> v0.getNonMutableConcurringReads().keySet().stream()). map(read -> { if (nLeftBehind.incrementAndGet() == 0) { logger.error("Sequences left behind before " + truncateProcessingAt); } return Integer.toString(read.getAlignmentStart()) + '-' + Integer.toString(read.getAlignmentEnd()); }) .collect(Collectors.joining("; ")); if (!s.equals("")) { logger.error(s); } }); Assert.isFalse(nLeftBehind.get() > 0); } } private final boolean useHashMap; private @NonNull DuplexKeeper getDuplexKeeper(boolean fallBackOnIntervalTree) { final @NonNull DuplexKeeper result; if (MutinackGroup.forceKeeperType != null) { switch(MutinackGroup.forceKeeperType) { case "DuplexHashMapKeeper": if (useHashMap) { result = new DuplexHashMapKeeper(); } else { result = new DuplexArrayListKeeper(5_000); } break; //case "DuplexITKeeper": // result = new DuplexITKeeper(); // break; case "DuplexArrayListKeeper": result = new DuplexArrayListKeeper(5_000); break; default: throw new AssertionFailedException(); } } else { if (useHashMap) { result = new DuplexHashMapKeeper(); } else /*if (fallBackOnIntervalTree) { result = new DuplexITKeeper(); } else */{ result = new DuplexArrayListKeeper(5_000); } } return result; } /** * Group reads into duplexes. * @param toPosition * @param fromPosition * @param finalResult */ private void loadAll( final int fromPosition, final int toPosition, final @NonNull List<DuplexRead> finalResult) { /** * Use a custom hash map type to keep track of duplexes when * alignmentPositionMismatchAllowed is 0. * This provides by far the highest performance. * When alignmentPositionMismatchAllowed is greater than 0, use * either an interval tree or a plain list. The use of an interval * tree instead of a plain list provides a speed benefit only when * there is large number of local duplexes, so switch dynamically * based on that number. The threshold was optimized empirically * and at a gross level. */ final boolean fallBackOnIntervalTree = extSAMCache.size() > 5_000; @NonNull DuplexKeeper duplexKeeper = getDuplexKeeper(fallBackOnIntervalTree); InterningSet<SequenceLocation> sequenceLocationCache = new InterningSet<>(500); final AlignmentExtremetiesDistance ed = new AlignmentExtremetiesDistance( analyzer.groupSettings, param); final SettableInteger nReadsExcludedFromDuplexes = new SettableInteger(0); final TObjectProcedure<@NonNull ExtendedSAMRecord> callLoadRead = rExtended -> { loadRead(rExtended, duplexKeeper, ed, sequenceLocationCache, nReadsExcludedFromDuplexes); return true; }; if (param.jiggle) { List<@NonNull ExtendedSAMRecord> reorderedReads = new ArrayList<>(extSAMCache.values()); Collections.shuffle(reorderedReads, random); reorderedReads.forEach(e -> callLoadRead.execute(e)); } else { extSAMCache.forEachValue(callLoadRead); } sequenceLocationCache.clear();//Not strictly necessary, but might as well release the //memory now if (param.randomizeStrand) { duplexKeeper.forEach(dr -> dr.randomizeStrands(random)); } duplexKeeper.forEach(DuplexRead::computeGlobalProperties); Pair<DuplexRead, DuplexRead> pair; if (param.enableCostlyAssertions && (pair = DuplexRead.checkNoEqualDuplexes(duplexKeeper.getIterable())) != null) { throw new AssertionFailedException("Equal duplexes: " + pair.fst + " and " + pair.snd); } if (param.enableCostlyAssertions) { Assert.isTrue(checkReadsOccurOnceInDuplexes(extSAMCache.values(), duplexKeeper.getIterable(), nReadsExcludedFromDuplexes.get())); } //Group duplexes that have alignment positions that differ by at most //param.alignmentPositionMismatchAllowed //and left/right consensus that differ by at most //param.nVariableBarcodeMismatchesAllowed final DuplexKeeper cleanedUpDuplexes = param.nVariableBarcodeMismatchesAllowed > 0 ? DuplexRead.groupDuplexes( duplexKeeper, duplex -> duplex.computeConsensus(false, param.variableBarcodeLength), () -> getDuplexKeeper(fallBackOnIntervalTree), param, stats, 0) : duplexKeeper; if (param.nVariableBarcodeMismatchesAllowed == 0) { cleanedUpDuplexes.forEach(d -> d.computeConsensus(true, param.variableBarcodeLength)); } //Group duplexes by alignment start (or equivalent) TIntObjectHashMap<List<DuplexRead>> duplexPositions = new TIntObjectHashMap<> (1_000, 0.5f, -999); cleanedUpDuplexes.forEach(dr -> { List<DuplexRead> list = duplexPositions.computeIfAbsent(dr.position0, (Supplier<List<DuplexRead>>) ArrayList::new); list.add(dr); }); if (param.variableBarcodeLength == 0) { final double @NonNull[] insertSizeProb = Objects.requireNonNull(analyzer.insertSizeProbSmooth); duplexPositions.forEachValue(list -> { for (DuplexRead dr: list) { double sizeP = insertSizeProb[ Math.min(insertSizeProb.length - 1, dr.maxInsertSize)]; Assert.isTrue(Double.isNaN(sizeP) || sizeP >= 0, () -> "Insert size problem: " + Arrays.toString(insertSizeProb)); dr.probAtLeastOneCollision = 1 - Math.pow(1 - sizeP, list.size()); } return true; }); } cleanedUpDuplexes.forEach(duplexRead -> duplexRead.analyzeForStats(param, stats)); cleanedUpDuplexes.forEach(finalResult::add); averageClippingOffset = fromPosition; final int arrayLength = toPosition - fromPosition + 1; averageClipping = new float[arrayLength]; int[] duplexNumber = new int[arrayLength]; cleanedUpDuplexes.forEach(duplexRead -> { int start = duplexRead.getUnclippedAlignmentStart() - fromPosition; int stop = duplexRead.getUnclippedAlignmentEnd() - fromPosition; start = Math.min(Math.max(0, start), toPosition - fromPosition); stop = Math.min(Math.max(0, stop), toPosition - fromPosition); for (int i = start; i <= stop; i++) { averageClipping[i] += duplexRead.averageNClipped; duplexNumber[i]++; } }); for (int i = 0; i < averageClipping.length; i++) { int n = duplexNumber[i]; if (n == 0) { Assert.isTrue(averageClipping[i] == 0); } else { averageClipping[i] /= n; } } }//End loadAll private void loadRead(@NonNull ExtendedSAMRecord rExtended, @NonNull DuplexKeeper duplexKeeper, AlignmentExtremetiesDistance ed, InterningSet<SequenceLocation> sequenceLocationCache, SettableInteger nReadsExcludedFromDuplexes) { final @NonNull SequenceLocation location = rExtended.getLocation(); final byte @NonNull[] barcode = rExtended.variableBarcode; final byte @NonNull[] mateBarcode = rExtended.getMateVariableBarcode(); final @NonNull SAMRecord r = rExtended.record; if (rExtended.getMate() == null) { stats.nMateOutOfReach.add(location, 1); } if (r.getMateUnmappedFlag()) { //It is not trivial to tell whether the mate is unmapped because //e.g. it did not sequence properly, or because all of the reads //from the duplex just do not map to the genome. To avoid //artificially inflating local duplex number, do not allow the //read to contribute to computed duplexes. Note that the rest of //the duplex-handling code could technically handle an unmapped //mate, and that the read will still be able to contribute to //local statistics such as average clipping. nReadsExcludedFromDuplexes.incrementAndGet(); return; } boolean foundDuplexRead = false; final boolean matchToLeft = rExtended.duplexLeft(); ed.set(rExtended); for (final DuplexRead duplexRead: duplexKeeper.getOverlapping(ed.temp)) { //stats.nVariableBarcodeCandidateExaminations.increment(location); ed.set(duplexRead); if (ed.getMaxDistance() > param.alignmentPositionMismatchAllowed) { continue; } final boolean barcodeMatch; //During first pass, do not allow any barcode mismatches if (matchToLeft) { barcodeMatch = basesEqual(duplexRead.leftBarcode, barcode, param.acceptNInBarCode) && basesEqual(duplexRead.rightBarcode, mateBarcode, param.acceptNInBarCode); } else { barcodeMatch = basesEqual(duplexRead.leftBarcode, mateBarcode, param.acceptNInBarCode) && basesEqual(duplexRead.rightBarcode, barcode, param.acceptNInBarCode); } if (barcodeMatch) { if (r.getInferredInsertSize() >= 0) { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.topStrandRecords.contains(rExtended)); } duplexRead.topStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.bottomStrandRecords.contains(rExtended)); } duplexRead.bottomStrandRecords.add(rExtended); } } else { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.bottomStrandRecords.contains(rExtended)); } duplexRead.bottomStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplexRead.topStrandRecords.contains(rExtended)); } duplexRead.topStrandRecords.add(rExtended); } } if (param.enableCostlyAssertions) { Assert.noException(duplexRead::assertAllBarcodesEqual); } rExtended.duplexRead = duplexRead; //stats.nVariableBarcodeMatchAfterPositionCheck.increment(location); foundDuplexRead = true; break; } else {//left and/or right barcodes do not match /* leftEqual = basesEqual(duplexRead.leftBarcode, barcode, true, 1); rightEqual = basesEqual(duplexRead.rightBarcode, barcode, true, 1); if (leftEqual || rightEqual) { stats.nVariableBarcodesCloseMisses.increment(location); }*/ } }//End loop over duplexReads if (!foundDuplexRead) { final DuplexRead duplexRead = matchToLeft ? new DuplexRead(analyzer.groupSettings, barcode, mateBarcode, !r.getReadNegativeStrandFlag(), r.getReadNegativeStrandFlag()) : new DuplexRead(analyzer.groupSettings, mateBarcode, barcode, r.getReadNegativeStrandFlag(), !r.getReadNegativeStrandFlag()); if (matchToLeft) { duplexRead.setPositions( rExtended.getOffsetUnclippedStart(), rExtended.getMateOffsetUnclippedEnd()); } else { duplexRead.setPositions( rExtended.getMateOffsetUnclippedStart(), rExtended.getOffsetUnclippedEnd()); } duplexKeeper.add(duplexRead); duplexRead.roughLocation = location; rExtended.duplexRead = duplexRead; if (!matchToLeft) { if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (!r.getFirstOfPairFlag()) { duplexRead.topStrandRecords.add(rExtended); } else { duplexRead.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplexRead::assertAllBarcodesEqual); } duplexRead.rightAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getOffsetUnclippedStart())); duplexRead.rightAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getOffsetUnclippedEnd())); duplexRead.leftAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getMateOffsetUnclippedStart())); duplexRead.leftAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), rExtended.getReferenceName(), rExtended.getMateOffsetUnclippedEnd())); } else {//Read on positive strand if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size? stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (r.getFirstOfPairFlag()) { duplexRead.topStrandRecords.add(rExtended); } else { duplexRead.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplexRead::assertAllBarcodesEqual); } duplexRead.leftAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getOffsetUnclippedStart())); duplexRead.leftAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getOffsetUnclippedEnd())); duplexRead.rightAlignmentStart = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getMateOffsetUnclippedStart())); duplexRead.rightAlignmentEnd = sequenceLocationCache.intern( new SequenceLocation(rExtended.getReferenceIndex(), r.getReferenceName(), rExtended.getMateOffsetUnclippedEnd())); } Assert.isFalse( duplexRead.leftAlignmentEnd.compareTo(duplexRead.leftAlignmentStart) < 0, (Supplier<Object>) duplexRead.leftAlignmentStart::toString, (Supplier<Object>) duplexRead.leftAlignmentEnd::toString, (Supplier<Object>) duplexRead::toString, (Supplier<Object>) rExtended::getFullName, "Misordered duplex: %s -- %s %s %s"); }//End new duplex creation } private static boolean checkReadsOccurOnceInDuplexes( Collection<@NonNull ExtendedSAMRecord> reads, @NonNull Iterable<DuplexRead> duplexes, int nReadsExcludedFromDuplexes) { ExtendedSAMRecord lostRead = null; int nUnfoundReads = 0; for (final @NonNull ExtendedSAMRecord rExtended: reads) { boolean found = false; for (DuplexRead dr: duplexes) { if (dr.topStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } if (dr.bottomStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } } if (!found) { nUnfoundReads++; lostRead = rExtended; } } if (nUnfoundReads != nReadsExcludedFromDuplexes) { throw new AssertionFailedException("Lost " + nUnfoundReads + " but expected " + nReadsExcludedFromDuplexes + "; see perhaps " + lostRead); } return true; } @NonNull LocationExaminationResults examineLocation(final @NonNull SequenceLocation location) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { return examineLocation0(location); } finally { threadCount.decrementAndGet(); } } @SuppressWarnings({"null", "ReferenceEquality"}) /** * This method is *NOT* thread-safe (it modifies DuplexReads associated with location retrieved * from field candidateSequences) * @param location * @return */ @NonNull private LocationExaminationResults examineLocation0(final @NonNull SequenceLocation location) { final LocationExaminationResults result = new LocationExaminationResults(); final THashSet<CandidateSequence> candidateSet0 = candidateSequences.get(location); if (candidateSet0 == null) { stats.nPosUncovered.increment(location); result.analyzedCandidateSequences = Sets.immutable.empty(); return result; } final ImmutableSet<CandidateSequence> candidateSet = // DebugLogControl.COSTLY_ASSERTIONS ? // Collections.unmodifiableSet(candidateSet0) Sets.immutable.ofAll(candidateSet0); //Retrieve relevant duplex reads //It is necessary not to duplicate the duplex reads, hence the use of a set //Identity should be good enough (and is faster) because no two different duplex read //objects we use in this method should be equal according to the equals() method //(although when grouping duplexes we don't check equality for the inner ends of //the reads since they depend on read length) final TCustomHashSet<DuplexRead> duplexReads = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); candidateSet.forEach(candidate -> { candidate.getQuality().reset(); candidate.getDuplexes().clear();//Should have no effect candidate.restoreConcurringReads(); final Set<DuplexRead> candidateDuplexReads = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); candidate.getNonMutableConcurringReads().forEachEntry((r, c) -> { @Nullable DuplexRead d = r.duplexRead; if (d != null) { candidateDuplexReads.add(d); } else { //throw new AssertionFailedException("Read without a duplex :" + r); } return true; }); duplexReads.addAll(candidateDuplexReads); }); //Allocate here to avoid repeated allocation in DuplexRead::examineAtLoc final CandidateCounter topCounter = new CandidateCounter(candidateSet, location); final CandidateCounter bottomCounter = new CandidateCounter(candidateSet, location); int[] insertSizes = new int [duplexReads.size()]; SettableDouble averageCollisionProbS = new SettableDouble(0d); SettableInteger index = new SettableInteger(0); duplexReads.forEach(duplexRead -> { Assert.isFalse(duplexRead.invalid); Assert.isTrue(duplexRead.averageNClipped >= 0); Assert.isTrue(param.variableBarcodeLength > 0 || Double.isNaN(duplexRead.probAtLeastOneCollision) || duplexRead.probAtLeastOneCollision >= 0); duplexRead.examineAtLoc( location, result, candidateSet, assaysToIgnoreForDisagreementQuality, topCounter, bottomCounter, analyzer, param, stats); if (index.get() < insertSizes.length) { //Check in case array size was capped (for future use; it is //never capped currently) insertSizes[index.get()] = duplexRead.maxInsertSize; index.incrementAndGet(); } averageCollisionProbS.addAndGet(duplexRead.probAtLeastOneCollision); if (param.variableBarcodeLength == 0 && !duplexRead.missingStrand) { stats.duplexCollisionProbabilityWhen2Strands.insert((int) (1_000f * duplexRead.probAtLeastOneCollision)); } }); if (param.enableCostlyAssertions) { Assert.noException(() -> checkDuplexAndCandidates(duplexReads, candidateSet)); } if (index.get() > 0) { Arrays.parallelSort(insertSizes, 0, index.get()); result.duplexInsertSize10thP = insertSizes[(int) (index.get() * 0.1f)]; result.duplexInsertSize90thP = insertSizes[(int) (index.get() * 0.9f)]; } double averageCollisionProb = averageCollisionProbS.get(); averageCollisionProb /= duplexReads.size(); if (param.variableBarcodeLength == 0) { stats.duplexCollisionProbability.insert((int) (1_000d * averageCollisionProb)); } result.probAtLeastOneCollision = averageCollisionProb; final DetailedQualities<PositionAssay> positionQualities = new DetailedPositionQualities(); if (averageClipping[location.position - averageClippingOffset] > param.maxAverageClippingOfAllCoveringDuplexes) { positionQualities.addUnique( MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS, DUBIOUS); } if (param.enableCostlyAssertions) { Assert.noException(() -> duplexReads.forEach(duplexRead -> { for (int i = duplexRead.topStrandRecords.size() - 1; i >= 0; --i) { ExtendedSAMRecord r = duplexRead.topStrandRecords.get(i); if (r.duplexRead != duplexRead) { throw new AssertionFailedException(); } if (duplexRead.bottomStrandRecords.contains(r)) { throw new AssertionFailedException(); } } for (int i = duplexRead.bottomStrandRecords.size() - 1; i >= 0; --i) { ExtendedSAMRecord r = duplexRead.bottomStrandRecords.get(i); if (r.duplexRead != duplexRead) { throw new AssertionFailedException(); } if (duplexRead.topStrandRecords.contains(r)) { throw new AssertionFailedException(); } } return true; })); } final int totalReadsAtPosition = (int) candidateSet.sumOfInt( c -> c.getNonMutableConcurringReads().size()); final TByteArrayList allPhredQualitiesAtPosition = new TByteArrayList(500); final SettableInteger nWrongPairsAtPosition = new SettableInteger(0); final SettableInteger nPairsAtPosition = new SettableInteger(0); candidateSet.forEach(candidate -> { candidate.addPhredScoresToList(allPhredQualitiesAtPosition); nPairsAtPosition.addAndGet(candidate.getNonMutableConcurringReads().size()); SettableInteger count = new SettableInteger(0); candidate.getNonMutableConcurringReads().forEachKey(r -> { if (r.formsWrongPair()) { count.incrementAndGet(); } return true; }); candidate.setnWrongPairs(count.get()); nWrongPairsAtPosition.addAndGet(candidate.getnWrongPairs()); }); final int nPhredQualities = allPhredQualitiesAtPosition.size(); allPhredQualitiesAtPosition.sort(); final byte positionMedianPhred = nPhredQualities == 0 ? 127 : allPhredQualitiesAtPosition.get(nPhredQualities / 2); if (positionMedianPhred < param.minMedianPhredScoreAtPosition) { positionQualities.addUnique(MEDIAN_PHRED_AT_POS, DUBIOUS); stats.nMedianPhredAtPositionTooLow.increment(location); } stats.medianPositionPhredQuality.insert(positionMedianPhred); if (nWrongPairsAtPosition.get() / ((float) nPairsAtPosition.get()) > param.maxFractionWrongPairsAtPosition) { positionQualities.addUnique(FRACTION_WRONG_PAIRS_AT_POS, DUBIOUS); stats.nFractionWrongPairsAtPositionTooHigh.increment(location); } Quality maxQuality; int totalGoodDuplexes, totalGoodOrDubiousDuplexes, totalGoodDuplexesIgnoringDisag, totalAllDuplexes; Handle<Byte> wildtypeBase = new Handle<>((byte) 'X'); candidateSet.forEach(candidate -> { candidate.getQuality().addAllUnique(positionQualities); processCandidateQualityStep1(candidate, location, result, positionMedianPhred, positionQualities); if (candidate.getMutationType().isWildtype()) { wildtypeBase.set(candidate.getWildtypeSequence()); } }); boolean leave = false; final boolean qualityOKBeforeTopAllele = Quality.nullableMax(positionQualities.getValue(true), GOOD).atLeast(GOOD); Quality topAlleleQuality = null; do { maxQuality = MINIMUM; totalAllDuplexes = 0; totalGoodDuplexes = 0; totalGoodOrDubiousDuplexes = 0; totalGoodDuplexesIgnoringDisag = 0; for (CandidateSequence candidate: candidateSet) { if (leave) { candidate.getQuality().addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, DUBIOUS); } @NonNull MutableSetMultimap<Quality, DuplexRead> map = candidate.getDuplexes(). groupBy(dr -> dr.localAndGlobalQuality.getValue()); if (param.enableCostlyAssertions) { map.forEachKeyMultiValues((k, v) -> Assert.isTrue(Util.getDuplicates(v).isEmpty())); Assert.isTrue(map.multiValuesView().collectInt(v -> v.size()).sum() == candidate.getDuplexes().size()); } @Nullable MutableSet<DuplexRead> gd = map.get(GOOD); candidate.setnGoodDuplexes(gd == null ? 0 : gd.size()); @Nullable MutableSet<DuplexRead> db = map.get(DUBIOUS); candidate.setnGoodOrDubiousDuplexes(candidate.getnGoodDuplexes() + (db == null ? 0 : db.size())); candidate.setnGoodDuplexesIgnoringDisag(candidate.getDuplexes(). count(dr -> dr.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDisagreementQuality).atLeast(GOOD))); maxQuality = max(candidate.getQuality().getValue(), maxQuality); totalAllDuplexes += candidate.getnDuplexes(); totalGoodDuplexes += candidate.getnGoodDuplexes(); totalGoodOrDubiousDuplexes += candidate.getnGoodOrDubiousDuplexes(); totalGoodDuplexesIgnoringDisag += candidate.getnGoodDuplexesIgnoringDisag(); processCandidateQualityStep2(candidate, location, result, positionMedianPhred, positionQualities); } if (leave) { break; } else { result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; topAlleleQuality = getAlleleFrequencyQuality(candidateSet, result); if (topAlleleQuality == null) { break; } Assert.isTrue(topAlleleQuality == DUBIOUS); positionQualities.addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, topAlleleQuality); leave = true;//Just one more iteration continue; } } while(Boolean.valueOf(null));//Assert never reached if (qualityOKBeforeTopAllele) { registerDuplexMinFracTopCandidate(param, duplexReads, topAlleleQuality == null ? stats.minTopCandFreqQ2PosTopAlleleFreqOK : stats.minTopCandFreqQ2PosTopAlleleFreqKO, location); } if (positionQualities.getValue(true) != null && positionQualities.getValue(true).lowerThan(GOOD)) { result.disagreements.clear(); } else { if (param.maxMutFreqForDisag < 1f) { final int finalTotalGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.disagreements.forEachKey(disag -> { Mutation m = disag.getSnd(); if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } m = disag.getFst(); if (m != null && m.mutationType != WILDTYPE) { if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } } return true; }); } stats.nPosDuplexCandidatesForDisagreementQ2.acceptSkip0(location, result.disagQ2Coverage); stats.nPosDuplexCandidatesForDisagreementQ1.acceptSkip0(location, result.disagOneStrandedCoverage); if (param.computeRawMismatches) { candidateSet.forEach(c -> c.getRawMismatchesQ2().forEach(result.rawMismatchesQ2::add)); candidateSet.forEach(c -> c.getRawInsertionsQ2().forEach(result.rawInsertionsQ2::add)); candidateSet.forEach(c -> c.getRawDeletionsQ2().forEach(result.rawDeletionsQ2::add)); } } for (CandidateSequence candidate: candidateSet) { candidate.setTotalAllDuplexes(totalAllDuplexes); candidate.setTotalGoodDuplexes(totalGoodDuplexes); candidate.setTotalGoodOrDubiousDuplexes(totalGoodOrDubiousDuplexes); candidate.setTotalReadsAtPosition(totalReadsAtPosition); } result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.nGoodDuplexes = totalGoodDuplexes; result.nGoodDuplexesIgnoringDisag = totalGoodDuplexesIgnoringDisag; stats.Q1Q2DuplexCoverage.insert(result.nGoodOrDubiousDuplexes); stats.Q2DuplexCoverage.insert(result.nGoodDuplexes); if (result.nGoodOrDubiousDuplexes == 0) { stats.missingStrandsWhenNoUsableDuplex.insert(result.nMissingStrands); stats.strandCoverageImbalanceWhenNoUsableDuplex.insert(result.strandCoverageImbalance); } if (maxQuality.atMost(POOR)) { stats.nPosQualityPoor.increment(location); switch (wildtypeBase.get()) { case 'A' : stats.nPosQualityPoorA.increment(location); break; case 'T' : stats.nPosQualityPoorT.increment(location); break; case 'G' : stats.nPosQualityPoorG.increment(location); break; case 'C' : stats.nPosQualityPoorC.increment(location); break; case 'X' : case 'N' : break;//Ignore because we do not have a record of wildtype sequence default : throw new AssertionFailedException(); } } else if (maxQuality == DUBIOUS) { stats.nPosQualityQ1.increment(location); } else if (maxQuality == GOOD) { stats.nPosQualityQ2.increment(location); } else { throw new AssertionFailedException(); } result.analyzedCandidateSequences = candidateSet; return result; }//End examineLocation private static void registerDuplexMinFracTopCandidate(Parameters param, TCustomHashSet<DuplexRead> duplexReads, Histogram hist, SequenceLocation location) { duplexReads.forEach(dr -> { Assert.isFalse(dr.totalNRecords == -1); if (dr.totalNRecords < 2 || dr.minFracTopCandidate == Float.MAX_VALUE) { return true; } hist.insert((int) (dr.minFracTopCandidate * 10)); return true; }); } private boolean lowMutFreq(Mutation mut, ImmutableSet<CandidateSequence> candidateSet, int nGOrDDuplexes) { Objects.requireNonNull(mut); Handle<Boolean> result = new Handle<>(true); candidateSet.detect((CandidateSequence c) -> { Mutation cMut = c.getMutation(); if (cMut.equals(mut)) { if (c.getnGoodOrDubiousDuplexes() > param.maxMutFreqForDisag * nGOrDDuplexes) { result.set(false); } return true; } return false; }); return result.get(); } private static float divideWithNanToZero(float f1, float f2) { return f2 == 0f ? 0 : f1 / f2; } private @Nullable Quality getAlleleFrequencyQuality( ImmutableSet<CandidateSequence> candidateSet, LocationExaminationResults result) { MutableFloatList frequencyList = candidateSet.collectFloat(c -> divideWithNanToZero(c.getnGoodOrDubiousDuplexes(), result.nGoodOrDubiousDuplexes), new FloatArrayList(Math.max(2, candidateSet.size()))).//Need second argument to collectInt //to avoid collecting into a set sortThis(); result.alleleFrequencies = frequencyList; while (frequencyList.size() < 2) { frequencyList.addAtIndex(0, Float.NaN); } float topAlleleFrequency = frequencyList.getLast(); if (!(topAlleleFrequency >= param.minTopAlleleFreqQ2 && topAlleleFrequency <= param.maxTopAlleleFreqQ2)) { return DUBIOUS; } return null; } @SuppressWarnings("null") private void processCandidateQualityStep1( final CandidateSequence candidate, final @NonNull SequenceLocation location, final LocationExaminationResults result, final byte positionMedianPhred, final @NonNull DetailedQualities<PositionAssay> positionQualities) { candidate.setMedianPhredAtPosition(positionMedianPhred); final byte candidateMedianPhred = candidate.getMedianPhredScore();//Will be -1 for insertions and deletions if (candidateMedianPhred != -1 && candidateMedianPhred < param.minCandidateMedianPhredScore) { candidate.getQuality().addUnique(MEDIAN_CANDIDATE_PHRED, DUBIOUS); } //TODO Should report min rather than average collision probability? candidate.setProbCollision((float) result.probAtLeastOneCollision); candidate.setInsertSizeAtPos10thP(result.duplexInsertSize10thP); candidate.setInsertSizeAtPos90thP(result.duplexInsertSize90thP); final MutableSet<DuplexRead> candidateDuplexes = Sets.mutable.empty(); candidate.getNonMutableConcurringReads().forEachKey(r -> { DuplexRead dr = r.duplexRead; if (dr != null) { Assert.isFalse(dr.invalid); candidateDuplexes.add(dr); } return true; }); candidate.setDuplexes(candidateDuplexes); candidate.setnDuplexes(candidateDuplexes.size()); if (candidate.getnDuplexes() == 0) { candidate.getQuality().addUnique(NO_DUPLEXES, ATROCIOUS); } if (param.verbosity > 2) { candidate.getIssues().clear();//This *must* be done to avoid interference //between parameter sets, in parameter exploration runs candidateDuplexes.forEach(d -> { candidate.getIssues().put(d, d.localAndGlobalQuality.toLong()); }); } final Quality posQMin = positionQualities.getValue(true); Handle<Quality> maxDuplexQHandle = new Handle<>(ATROCIOUS); candidateDuplexes.each(dr -> { if (posQMin != null) { dr.localAndGlobalQuality.addUnique(QUALITY_AT_POSITION, posQMin); } maxDuplexQHandle.set(Quality.max(maxDuplexQHandle.get(), dr.localAndGlobalQuality.getValue())); }); final @NonNull Quality maxDuplexQ = maxDuplexQHandle.get(); switch(param.candidateQ2Criterion) { case "1Q2Duplex": candidate.getQuality().addUnique(MAX_Q_FOR_ALL_DUPLEXES, maxDuplexQ); break; case "NQ1Duplexes": SettableInteger countQ1Duplexes = new SettableInteger(0); candidateDuplexes.forEach(d -> { if (d.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDuplexNStrands). atLeast(GOOD)) { countQ1Duplexes.incrementAndGet(); } }); if (countQ1Duplexes.get() >= param.minQ1Duplexes) { candidate.getQuality().addUnique(PositionAssay.N_Q1_DUPLEXES, GOOD); } break; default: throw new AssertionFailedException(); } if (PositionAssay.COMPUTE_MAX_DPLX_Q_IGNORING_DISAG) { candidateDuplexes.stream(). map(dr -> dr.localAndGlobalQuality.getValueIgnoring(assaysToIgnoreForDisagreementQuality, true)). max(Quality::compareTo).ifPresent(q -> candidate.getQuality().addUnique(MAX_DPLX_Q_IGNORING_DISAG, q)); } candidate.resetLigSiteDistances(); if (maxDuplexQ.atLeast(DUBIOUS)) { candidateDuplexes.forEach(dr -> { if (dr.localAndGlobalQuality.getValue().atLeast(maxDuplexQ)) { candidate.acceptLigSiteDistance(dr.getMaxDistanceToLigSite()); } }); } } private void processCandidateQualityStep2( final CandidateSequence candidate, final @NonNull SequenceLocation location, final LocationExaminationResults result, final byte positionMedianPhred, final @NonNull DetailedQualities<PositionAssay> positionQualities ) { if (!param.rnaSeq) { candidate.getNonMutableConcurringReads().forEachKey(r -> { final int refPosition = location.position; final int readPosition = r.referencePositionToReadPosition(refPosition); if (!r.formsWrongPair()) { final int distance = r.tooCloseToBarcode(readPosition, 0); if (Math.abs(distance) > 160) { throw new AssertionFailedException("Distance problem with candidate " + candidate + " read at read position " + readPosition + " and refPosition " + refPosition + ' ' + r.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance); } if (distance >= 0) { stats.singleAnalyzerQ2CandidateDistanceToLigationSite.insert(distance); } else { stats.Q2CandidateDistanceToLigationSiteN.insert(-distance); } } return true; }); } if (candidate.getMutationType().isWildtype()) { candidate.setSupplementalMessage(null); } else if (candidate.getQuality().getNonNullValue().greaterThan(POOR)) { final StringBuilder supplementalMessage = new StringBuilder(); final Map<String, Integer> stringCounts = new HashMap<>(100); candidate.getNonMutableConcurringReads().forEachKey(er -> { String other = er.record.getMateReferenceName(); if (!er.record.getReferenceName().equals(other)) { String s = other + ':' + er.getMateAlignmentStart(); Integer found = stringCounts.get(s); if (found == null){ stringCounts.put(s, 1); } else { stringCounts.put(s, found + 1); } } return true; }); final Optional<String> mates = stringCounts.entrySet().stream().map(entry -> entry.getKey() + ((entry.getValue() == 1) ? "" : (" (" + entry.getValue() + " repeats)")) + "; "). sorted().reduce(String::concat); final String hasMateOnOtherChromosome = mates.isPresent() ? mates.get() : ""; final IntSummaryStatistics insertSizeStats = candidate.getNonMutableConcurringReads().keySet().stream(). mapToInt(er -> Math.abs(er.getInsertSize())).summaryStatistics(); final int localMaxInsertSize = insertSizeStats.getMax(); final int localMinInsertSize = insertSizeStats.getMin(); candidate.setMinInsertSize(localMinInsertSize); candidate.setMaxInsertSize(localMaxInsertSize); if (localMaxInsertSize < param.minInsertSize || localMinInsertSize > param.maxInsertSize) { candidate.getQuality().add(PositionAssay.INSERT_SIZE, DUBIOUS); } final boolean has0PredictedInsertSize = localMinInsertSize == 0; final NumberFormat nf = DoubleAdderFormatter.nf.get(); @SuppressWarnings("null") final boolean hasNoMate = candidate.getNonMutableConcurringReads().forEachKey( er -> er.record.getMateReferenceName() != null); if (localMaxInsertSize > param.maxInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMaxInsertSize)).append("; "); } if (localMinInsertSize < param.minInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMinInsertSize)).append("; "); } candidate.setAverageMappingQuality((int) candidate.getNonMutableConcurringReads().keySet().stream(). mapToInt(r -> r.record.getMappingQuality()).summaryStatistics().getAverage()); if (!"".equals(hasMateOnOtherChromosome)) { supplementalMessage.append("pair elements map to other chromosomes: " + hasMateOnOtherChromosome).append("; "); } if (hasNoMate) { supplementalMessage.append("at least one read has no mate; "); } if ("".equals(hasMateOnOtherChromosome) && !hasNoMate && has0PredictedInsertSize) { supplementalMessage.append("at least one insert has 0 predicted size; "); } if (candidate.getnWrongPairs() > 0) { supplementalMessage.append(candidate.getnWrongPairs() + " wrong pairs; "); } candidate.setSupplementalMessage(supplementalMessage); } } @SuppressWarnings("ReferenceEquality") private static Runnable checkDuplexAndCandidates(Set<DuplexRead> duplexReads, ImmutableSet<CandidateSequence> candidateSet) { for (DuplexRead duplexRead: duplexReads) { duplexRead.allDuplexRecords.each(r -> { if (r.duplexRead != duplexRead) { throw new AssertionFailedException("Read " + r + " associated with duplexes " + r.duplexRead + " and " + duplexRead); } }); } candidateSet.each(c -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); Set<DuplexRead> duplexesSupportingC = new UnifiedSet<>(30); c.getNonMutableConcurringReads().forEachKey(r -> { DuplexRead d = r.duplexRead; if (d != null) { Assert.isFalse(d.invalid); duplexesSupportingC.add(d); } return true; });//Collect *unique* duplexes candidateSet.each(c2 -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); if (c2 == c) { return; } if (c2.equals(c)) { throw new AssertionFailedException(); } c2.getNonMutableConcurringReads().keySet().forEach(r -> { if (r.isOpticalDuplicate()) { return; } DuplexRead d = r.duplexRead; if (d != null && duplexesSupportingC.contains(d)) { boolean disowned = !d.allDuplexRecords.contains(r); throw new AssertionFailedException(disowned + " Duplex " + d + " associated with candidates " + c + " and " + c2); } }); }); }); return null; } private boolean checkConstantBarcode(byte[] bases, boolean allowN, int nAllowableMismatches) { if (nAllowableMismatches == 0 && !allowN) { return bases == analyzer.constantBarcode;//OK because of interning } int nMismatches = 0; for (int i = 0; i < analyzer.constantBarcode.length; i++) { if (!basesEqual(analyzer.constantBarcode[i], bases[i], allowN)) { nMismatches ++; if (nMismatches > nAllowableMismatches) return false; } } return true; } @SuppressWarnings("null") ExtendedSAMRecord getExtended(@NonNull SAMRecord record, @NonNull SequenceLocation location) { final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false); return extSAMCache.computeIfAbsent(readFullName, s -> new ExtendedSAMRecord(record, readFullName, analyzer.groupSettings, analyzer, location, extSAMCache)); } /** * * @return the furthest position in the contig covered by the read */ int processRead( final @NonNull SequenceLocation location, final @NonNull InterningSet<SequenceLocation> locationInterningSet, final @NonNull ExtendedSAMRecord extendedRec, final @NonNull ReferenceSequence ref) { Assert.isFalse(extendedRec.processed, "Double processing of record %s"/*, extendedRec.getFullName()*/); extendedRec.processed = true; final SAMRecord rec = extendedRec.record; final byte[] readBases = rec.getReadBases(); final byte[] refBases = ref.getBases(); final byte[] baseQualities = rec.getBaseQualities(); final int effectiveReadLength = extendedRec.effectiveLength; if (effectiveReadLength == 0) { return -1; } final CandidateBuilder readLocalCandidates = new CandidateBuilder(rec.getReadNegativeStrandFlag(), param.enableCostlyAssertions ? null : (k, v) -> insertCandidateAtPosition(v, k)); final int insertSize = extendedRec.getInsertSize(); final int insertSizeAbs = Math.abs(insertSize); if (insertSizeAbs > param.maxInsertSize) { stats.nReadsInsertSizeAboveMaximum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } if (insertSizeAbs < param.minInsertSize) { stats.nReadsInsertSizeBelowMinimum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } final PairOrientation pairOrientation; if (rec.getReadPairedFlag() && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) && ((pairOrientation = SamPairUtil.getPairOrientation(rec)) == PairOrientation.TANDEM || pairOrientation == PairOrientation.RF)) { if (pairOrientation == PairOrientation.TANDEM) { stats.nReadsPairTandem.increment(location); } else if (pairOrientation == PairOrientation.RF) { stats.nReadsPairRF.increment(location); } if (param.ignoreTandemRFPairs) { return -1; } } final boolean readOnNegativeStrand = rec.getReadNegativeStrandFlag(); if (!checkConstantBarcode(extendedRec.constantBarcode, false, param.nConstantBarcodeMismatchesAllowed)) { if (checkConstantBarcode(extendedRec.constantBarcode, true, param.nConstantBarcodeMismatchesAllowed)) { if (readOnNegativeStrand) stats.nConstantBarcodeDodgyNStrand.increment(location); else stats.nConstantBarcodeDodgy.increment(location); if (!param.acceptNInBarCode) return -1; } else { stats.nConstantBarcodeMissing.increment(location); return -1; } } stats.nReadsConstantBarcodeOK.increment(location); if (extendedRec.medianPhred < param.minReadMedianPhredScore) { stats.nReadMedianPhredBelowThreshold.accept(location); return -1; } stats.mappingQualityKeptRecords.insert(rec.getMappingQuality()); SettableInteger refEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger readEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger returnValue = new SettableInteger(-1); if (insertSize == 0) { stats.nReadsInsertNoSize.increment(location); if (param.ignoreZeroInsertSizeReads) { return -1; } } for (ExtendedAlignmentBlock block: extendedRec.getAlignmentBlocks()) { processAlignmentBlock(location, locationInterningSet, readLocalCandidates, ref, !param.rnaSeq, block, extendedRec, rec, insertSize, readOnNegativeStrand, readBases, refBases, baseQualities, effectiveReadLength, refEndOfPreviousAlignment, readEndOfPreviousAlignment, returnValue); } if (param.enableCostlyAssertions) { readLocalCandidates.build().forEach((k, v) -> insertCandidateAtPosition(v, k)); } return returnValue.get(); } private void processAlignmentBlock(@NonNull SequenceLocation location, InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ReferenceSequence ref, final boolean notRnaSeq, final ExtendedAlignmentBlock block, final @NonNull ExtendedSAMRecord extendedRec, final SAMRecord rec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] refBases, final byte[] baseQualities, final int effectiveReadLength, final SettableInteger refEndOfPreviousAlignment0, final SettableInteger readEndOfPreviousAlignment0, final SettableInteger returnValue) { int refPosition = block.getReferenceStart() - 1; int readPosition = block.getReadStart() - 1; final int nBlockBases = block.getLength(); final int refEndOfPreviousAlignment = refEndOfPreviousAlignment0.get(); final int readEndOfPreviousAlignment = readEndOfPreviousAlignment0.get(); returnValue.set(Math.max(returnValue.get(), refPosition + nBlockBases)); /** * When adding an insertion candidate, make sure that a wildtype or * mismatch candidate is also inserted at the same position, even * if it normally would not have been (for example because of low Phred * quality). This should avoid awkward comparisons between e.g. an * insertion candidate and a combo insertion + wildtype candidate. */ boolean forceCandidateInsertion = false; if (refEndOfPreviousAlignment != -1) { final boolean insertion = refPosition == refEndOfPreviousAlignment + 1; final boolean tooLate = (readOnNegativeStrand ? (insertion ? readPosition <= param.ignoreLastNBases : readPosition < param.ignoreLastNBases) : readPosition > rec.getReadLength() - param.ignoreLastNBases) && notRnaSeq; if (tooLate) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring indel too close to end " + readPosition + (readOnNegativeStrand ? " neg strand " : " pos strand ") + readPosition + ' ' + (rec.getReadLength() - 1) + ' ' + extendedRec.getFullName()); } stats.nCandidateIndelAfterLastNBases.increment(location); } else { if (insertion) { stats.nCandidateInsertions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion at position " + readPosition + " for read " + rec.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + insertSize + ')'); } forceCandidateInsertion = processInsertion( readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec, insertSize, readOnNegativeStrand, readBases, baseQualities, effectiveReadLength); } else if (refPosition < refEndOfPreviousAlignment + 1) { throw new AssertionFailedException("Alignment block misordering"); } else { processDeletion(location, ref, block, readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec, insertSize, readOnNegativeStrand, readBases, refBases, baseQualities, effectiveReadLength); }//End of deletion case }//End of case with accepted indel }//End of case where there was a previous alignment block refEndOfPreviousAlignment0.set(refPosition + (nBlockBases - 1)); readEndOfPreviousAlignment0.set(readPosition + (nBlockBases - 1)); for (int i = 0; i < nBlockBases; i++, readPosition++, refPosition++) { if (i == 1) { forceCandidateInsertion = false; } Handle<Boolean> insertCandidateAtRegularPosition = new Handle<>(true); final SequenceLocation locationPH = i < nBlockBases - 1 ? //No insertion or deletion; make a note of it SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refPosition, true) : null; location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refPosition); if (baseQualities[readPosition] < param.minBasePhredScoreQ1) { stats.nBasesBelowPhredScore.increment(location); if (forceCandidateInsertion) { insertCandidateAtRegularPosition.set(false); } else { continue; } } if (refPosition > refBases.length - 1) { logger.warn("Ignoring base mapped at " + refPosition + ", beyond the end of " + ref.getName()); continue; } stats.nCandidateSubstitutionsConsidered.increment(location); if (readBases[readPosition] != StringUtil.toUpperCase(refBases[refPosition]) /*Mismatch*/) { final boolean tooLate = readOnNegativeStrand ? readPosition < param.ignoreLastNBases : readPosition > (rec.getReadLength() - 1) - param.ignoreLastNBases; int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); boolean goodToInsert = distance < 0 && !tooLate; if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition.get()) { stats.rejectedSubstDistanceToLigationSite.insert(-distance); stats.nCandidateSubstitutionsBeforeFirstNBases.increment(location); } } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to barcode for read " + rec.getReadName()); } insertCandidateAtRegularPosition.set(false); } else if (tooLate && insertCandidateAtRegularPosition.get()) { stats.nCandidateSubstitutionsAfterLastNBases.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to read end for read " + rec.getReadName()); } insertCandidateAtRegularPosition.set(false); } if (goodToInsert || forceCandidateInsertion) { processSubstitution( location, locationPH, readPosition, refPosition, readLocalCandidates, extendedRec, insertSize, readOnNegativeStrand, readBases, refBases, baseQualities, effectiveReadLength, forceCandidateInsertion, insertCandidateAtRegularPosition); }//End of mismatched read case } else { processWildtypeBase( location, locationPH, readPosition, refPosition, readLocalCandidates, extendedRec, readOnNegativeStrand, readBases, refBases, baseQualities, effectiveReadLength, forceCandidateInsertion, insertCandidateAtRegularPosition); }//End of wildtype case }//End of loop over alignment bases } private void processWildtypeBase( final @NonNull SequenceLocation location, final @Nullable SequenceLocation locationPH, final int readPosition, final int refPosition, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] refBases, final byte[] baseQualities, final int effectiveReadLength, final boolean forceCandidateInsertion, final Handle<Boolean> insertCandidateAtRegularPosition) { //Wildtype read int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition.get()) { stats.wtRejectedDistanceToLigationSite.insert(-distance); } } if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } } else { if (!extendedRec.formsWrongPair() && distance < -150) { throw new AssertionFailedException("Distance problem 1 at read position " + readPosition + " and refPosition " + refPosition + ' ' + extendedRec.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance + ""); } distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (!extendedRec.formsWrongPair() && insertCandidateAtRegularPosition.get()) { stats.wtAcceptedBaseDistanceToLigationSite.insert(-distance); } } if (((!readOnNegativeStrand && readPosition > readBases.length - 1 - param.ignoreLastNBases) || (readOnNegativeStrand && readPosition < param.ignoreLastNBases))) { if (insertCandidateAtRegularPosition.get()) { stats.nCandidateWildtypeAfterLastNBases.increment(location); } if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } } CandidateSequence candidate = new CandidateSequence(this, WILDTYPE, null, location, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(-distance); } candidate.setWildtypeSequence(StringUtil.toUpperCase(refBases[refPosition])); candidate.addBasePhredScore(baseQualities[readPosition]); if (extendedRec.basePhredScores.put(location, baseQualities[readPosition]) != ExtendedSAMRecord.PHRED_NO_ENTRY) { logger.warn("Recording Phred score multiple times at same position " + location); } if (insertCandidateAtRegularPosition.get()) { candidate = readLocalCandidates.add(candidate, location); candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(-distance); } candidate2.setWildtypeSequence(StringUtil.toUpperCase(refBases[refPosition])); candidate2 = readLocalCandidates.add(candidate2, locationPH); candidate2 = null; } } private void processSubstitution( final @NonNull SequenceLocation location, final @Nullable SequenceLocation locationPH, final int readPosition, final int refPosition, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] refBases, final byte[] baseQualities, final int effectiveReadLength, final boolean forceCandidateInsertion, final Handle<Boolean> insertCandidateAtRegularPosition) { int distance = 0; if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Substitution at position " + readPosition + " for read " + extendedRec.record.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + insertSize + ')'); } final byte wildType = StringUtil.toUpperCase(refBases[refPosition]); final byte mutation = StringUtil.toUpperCase(readBases[readPosition]); switch (mutation) { case 'A': stats.nCandidateSubstitutionsToA.increment(location); break; case 'T': stats.nCandidateSubstitutionsToT.increment(location); break; case 'G': stats.nCandidateSubstitutionsToG.increment(location); break; case 'C': stats.nCandidateSubstitutionsToC.increment(location); break; case 'N': stats.nNs.increment(location); if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } break; default: throw new AssertionFailedException("Unexpected letter: " + StringUtil.toUpperCase(readBases[readPosition])); } distance = -extendedRec.tooCloseToBarcode(readPosition, 0); final byte[] mutSequence = byteArrayMap.get(readBases[readPosition]); CandidateSequence candidate = new CandidateSequence(this, SUBSTITUTION, mutSequence, location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidate.setInsertSize(insertSize); candidate.setInsertSizeNoBarcodeAccounting(false); candidate.setPositionInRead(readPosition); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); candidate.setWildtypeSequence(wildType); candidate.addBasePhredScore(baseQualities[readPosition]); extendedRec.nReferenceDisagreements++; if (extendedRec.basePhredScores.put(location, baseQualities[readPosition]) != ExtendedSAMRecord.PHRED_NO_ENTRY) { logger.warn("Recording Phred score multiple times at same position " + location); } if (param.computeRawMismatches && insertCandidateAtRegularPosition.get()) { final ComparablePair<String, String> mutationPair = readOnNegativeStrand ? new ComparablePair<>(byteMap.get(Mutation.complement(wildType)), byteMap.get(Mutation.complement(mutation))) : new ComparablePair<>(byteMap.get(wildType), byteMap.get(mutation)); stats.rawMismatchesQ1.accept(location, mutationPair); if (meetsQ2Thresholds(extendedRec) && baseQualities[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { candidate.getMutableRawMismatchesQ2().add(mutationPair); } } if (insertCandidateAtRegularPosition.get()) { candidate = readLocalCandidates.add(candidate, location); candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(distance); } candidate2.setWildtypeSequence(wildType); candidate2 = readLocalCandidates.add(candidate2, locationPH); candidate2 = null; } } private void processDeletion( final @NonNull SequenceLocation location, final @NonNull ReferenceSequence ref, final ExtendedAlignmentBlock block, final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, final InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] refBases, final byte[] baseQualities, final int effectiveReadLength) { //Deletion or skipped region ("N" in Cigar) if (refPosition > refBases.length - 1) { logger.warn("Ignoring rest of read after base mapped at " + refPosition + ", beyond the end of " + ref.getName()); return; } int distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, param.ignoreFirstNBasesQ1); int distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, param.ignoreFirstNBasesQ1); int distance = Math.min(distance0, distance1) + 1; final boolean isIntron = block.previousCigarOperator == CigarOperator.N; final boolean Q1reject = distance < 0; if (!isIntron && Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring deletion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); } else { distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, 0); distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, 0); distance = Math.min(distance0, distance1) + 1; if (!isIntron) stats.nCandidateDeletions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Deletion or intron at position " + readPosition + " for read " + extendedRec.record.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + insertSize + ')'); } final int deletionLength = refPosition - (refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation newLocation = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation deletionEnd = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), newLocation.position + deletionLength); final byte @Nullable[] deletedSequence = isIntron ? null : Arrays.copyOfRange(ref.getBases(), refEndOfPreviousAlignment + 1, refPosition); //Add hidden mutations to all locations covered by deletion //So disagreements between deletions that have only overlapping //spans are detected. if (!isIntron) { for (int i = 1; i < deletionLength; i++) { SequenceLocation location2 = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1 + i); CandidateSequence hiddenCandidate = new CandidateDeletion( this, deletedSequence, location2, extendedRec, Integer.MAX_VALUE, MutationType.DELETION, newLocation, deletionEnd); hiddenCandidate.setHidden(true); hiddenCandidate.setInsertSize(insertSize); hiddenCandidate.setInsertSizeNoBarcodeAccounting(false); hiddenCandidate.setPositionInRead(readPosition); hiddenCandidate.setReadEL(effectiveReadLength); hiddenCandidate.setReadName(extendedRec.getFullName()); hiddenCandidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); hiddenCandidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); hiddenCandidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); hiddenCandidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); hiddenCandidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); hiddenCandidate = readLocalCandidates.add(hiddenCandidate, location2); hiddenCandidate = null; } } CandidateSequence candidate = new CandidateDeletion(this, deletedSequence, newLocation, extendedRec, distance, isIntron ? MutationType.INTRON : MutationType.DELETION, newLocation, SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refPosition)); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidate.setInsertSize(insertSize); candidate.setInsertSizeNoBarcodeAccounting(false); candidate.setPositionInRead(readPosition); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); if (!isIntron) extendedRec.nReferenceDisagreements++; if (!isIntron && param.computeRawMismatches) { Objects.requireNonNull(deletedSequence); final ComparablePair<String, String> mutationPair = readOnNegativeStrand ? new ComparablePair<>(byteMap.get(Mutation.complement(deletedSequence[0])), new String(new Mutation(candidate).reverseComplement().mutationSequence).toUpperCase()) : new ComparablePair<>(byteMap.get(deletedSequence[0]), new String(deletedSequence).toUpperCase()); stats.rawDeletionsQ1.accept(newLocation, mutationPair); stats.rawDeletionLengthQ1.insert(deletedSequence.length); if (meetsQ2Thresholds(extendedRec) && baseQualities[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { candidate.getMutableRawDeletionsQ2().add(mutationPair); } } candidate = readLocalCandidates.add(candidate, newLocation); candidate = null; } } private boolean processInsertion( final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, final InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final int insertSize, final boolean readOnNegativeStrand, final byte[] readBases, final byte[] baseQualities, final int effectiveReadLength) { boolean forceCandidateInsertion = false; final @NonNull SequenceLocation location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment, true); int distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, param.ignoreFirstNBasesQ1); int distance1 = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); int distance = Math.max(distance0, distance1); distance = -distance + 1; final boolean Q1reject = distance < 0; if (Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring insertion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); } else { distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, 0); distance1 = extendedRec.tooCloseToBarcode(readPosition, 0); distance = Math.max(distance0, distance1); distance = -distance + 1; final byte [] insertedSequence = Arrays.copyOfRange(readBases, readEndOfPreviousAlignment + 1, readPosition); CandidateSequence candidate = new CandidateSequence( this, INSERTION, insertedSequence, location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidate.setInsertSize(insertSize); candidate.setPositionInRead(readPosition); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); candidate.setInsertSizeNoBarcodeAccounting(false); if (param.computeRawMismatches) { final byte wildType = readBases[readEndOfPreviousAlignment]; final ComparablePair<String, String> mutationPair = readOnNegativeStrand ? new ComparablePair<>(byteMap.get(Mutation.complement(wildType)), new String(new Mutation(candidate).reverseComplement().mutationSequence).toUpperCase()) : new ComparablePair<>(byteMap.get(wildType), new String(insertedSequence).toUpperCase()); stats.rawInsertionsQ1.accept(location, mutationPair); stats.rawInsertionLengthQ1.insert(insertedSequence.length); if (meetsQ2Thresholds(extendedRec) && baseQualities[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { candidate.getMutableRawInsertionsQ2().add(mutationPair); } } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion of " + new String(candidate.getSequence()) + " at ref " + refPosition + " and read position " + readPosition + " for read " + extendedRec.getFullName()); } candidate = readLocalCandidates.add(candidate, location); candidate = null; forceCandidateInsertion = true; if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Added candidate at " + location /*+ "; readLocalCandidates now " + readLocalCandidates.build()*/); } extendedRec.nReferenceDisagreements++; } return forceCandidateInsertion; } public @NonNull Mutinack getAnalyzer() { return analyzer; } }
package scheduling.three; import graph.Graph; import graph.VertexColoring; import java.util.BitSet; import java.util.LinkedList; import java.util.Queue; class ComponentSwapper { private Graph graph; private VertexColoring coloring; /** * Store colors as object field to avoid passing * huge amount of arguments to private methods. */ private int colorBig, colorSmall, colorOther; ComponentSwapper(VertexColoring coloring) { this.coloring = coloring; this.graph = coloring.getGraph(); } /** * Try to swap pairs of components X', Y' of induced graph G(X, Y) * where X has colorBig and Y has colorSmall as long as it is not * possible or desired amount of vertices has been moved to Y. * * @param colorBig color of bigger color class * @param colorSmall color of smaller color class * @param verticesToMove desired change of the coloring width * @return how much the width was decreased */ int swap(int colorBig, int colorSmall, int verticesToMove, LinkedList<Integer> compensator) { this.colorBig = colorBig; this.colorSmall = colorSmall; BitSet checked = new BitSet(graph.getVertices()); int currentColor, verticesMoved, verticesMovedTogether = 0; for (int i = 0; i < graph.getVertices() && 0 < verticesToMove; i++) { if (!checked.get(i) && 0 < verticesToMove) { checked.set(i); currentColor = coloring.get(i); if (currentColor == colorBig || currentColor == colorSmall) { verticesMoved = swapWithCompensating(i, checked, compensator, verticesToMove); verticesMovedTogether += verticesMoved; verticesToMove -= verticesMoved; } } } return verticesMovedTogether; } /** * Swap color classes of component of induced graph that * contains vertex of currentIndex. * If difference in sizes of color classes is too big * compensate it by moving vertices from compensator to smaller class. * * @param currentIndex of starting point of finding color classes * @param checked BitSet of vertices not in use * @param compensator list of vertices that can be used to compensate * @param verticesToMove desired maximum difference of size of color classes * @return how many vertices were moved */ private int swapWithCompensating(int currentIndex, BitSet checked, LinkedList<Integer> compensator, int verticesToMove) { LinkedList<Integer> bigComponent = new LinkedList<>(), smallComponent = new LinkedList<>(); findComponents(currentIndex, bigComponent, smallComponent, checked); int sizeDifference = bigComponent.size() - smallComponent.size(), verticesMoved = 0; if (0 < sizeDifference && sizeDifference <= verticesToMove + compensator.size()) { int toCompensate = sizeDifference - verticesToMove; toCompensate = 0 < toCompensate ? toCompensate : 0; verticesMoved = sizeDifference - toCompensate; changeColor(bigComponent, colorSmall); changeColor(smallComponent, colorBig); changeColor(compensator, colorBig, toCompensate); } return verticesMoved; } /** * Try to swap components between color classes * so that the sizes of all color classes will remain the same. * Use vertices from compensator to compensate difference * in sizes of color classes. * * @param colorBig color of bigger color class * @param colorSmall color of smaller color class * @param compensator list of vertices used to compensate */ void swapWithoutDecreasing(int colorBig, int colorSmall, LinkedList<Integer> compensator) { this.colorBig = colorBig; this.colorSmall = colorSmall; BitSet checked = new BitSet(graph.getVertices()); int currentColor; for (int i = 0; i < graph.getVertices(); i++) { if (!checked.get(i)) { currentColor = coloring.get(i); if (currentColor == colorBig || currentColor == colorSmall) { if (swapAndRestore(i, checked, compensator)) { return; } } } } } /** * Swap color classes of component of induced graph that * contains vertex of currentIndex and restore sizes of color * classes by moving vertices from compensator to smaller color class. * * @param currentIndex of starting point of finding color classes * @param checked BitSet of vertices not in use * @param compensator list of vertices that can be used to compensate * @return true if swapping took place */ private boolean swapAndRestore(int currentIndex, BitSet checked, LinkedList<Integer> compensator) { LinkedList<Integer> bigComponent = new LinkedList<>(), smallComponent = new LinkedList<>(); findComponents(currentIndex, bigComponent, smallComponent, checked); int sizeDifference = bigComponent.size() - smallComponent.size(); if (0 < sizeDifference && sizeDifference <= compensator.size()) { changeColor(bigComponent, colorSmall); changeColor(smallComponent, colorBig); changeColor(compensator, colorBig, sizeDifference); return true; } return false; } /** * Try to swap components between color classes * and move vertices in number of difference in sizes * of those components from compensator to the third * color class. * * @param colorBig color of bigger color class * @param colorSmall color of smaller color class * @param colorOther color of the third color class * @param compensator list of vertices used to compensate * @param verticesToMove desired change of the coloring width * @return how much the width was decreased */ int swapAndMoveUntilDecreased(int colorBig, int colorSmall, int colorOther, LinkedList<Integer> compensator, int verticesToMove) { this.colorBig = colorBig; this.colorSmall = colorSmall; this.colorOther = colorOther; //TODO otherCompensator for compensating common neighbours BitSet checked = new BitSet(graph.getVertices()); BooleanArray compensatorArray = vertexListToArray(compensator); LinkedList<Integer> bigComponent = new LinkedList<>(), smallComponent = new LinkedList<>(); int currentColor, verticesMovedTotal = 0, verticesMoved; for (int i = 0; i < graph.getVertices() && 0 < verticesToMove; i++) { if (!checked.get(i)) { checked.set(i); currentColor = coloring.get(i); if (currentColor == colorBig || currentColor == colorSmall) { findComponents(i, bigComponent, smallComponent, checked); verticesMoved = useComponentsToDecrease(bigComponent, smallComponent, compensatorArray, verticesToMove); verticesMovedTotal += verticesMoved; verticesToMove -= verticesMoved; bigComponent.clear(); smallComponent.clear(); } } } return verticesMovedTotal; } private int useComponentsToDecrease(LinkedList<Integer> bigComponent, LinkedList<Integer> smallComponent, BooleanArray compensator, int verticesToMove) { //TODO arguments LinkedList<Integer> small3Big = getFrom3To(smallComponent, colorBig); int decreasedBy = swapAndMoveToOther(bigComponent, smallComponent, small3Big, compensator, verticesToMove); if (0 < decreasedBy) { return decreasedBy; } decreasedBy = moveNeighbour(small3Big, compensator, verticesToMove); if (0 < decreasedBy) { return decreasedBy; } decreasedBy = moveCommonNeighbours(small3Big, compensator, verticesToMove); if (0 < decreasedBy) { return decreasedBy; } return reduceToPathsAndSwap(); } private int swapAndMoveToOther(LinkedList<Integer> bigComponent, LinkedList<Integer> smallComponent, LinkedList<Integer> toRemoveFromCompensator, BooleanArray compensator, int verticesToMove) { //TODO int sizeDifference = bigComponent.size() - smallComponent.size(); if (0 < sizeDifference && sizeDifference <= verticesToMove && sizeDifference <= compensator.getCount()) { if (sizeDifference <= compensator.getCount() - toRemoveFromCompensator.size()) { /* * Remove newly forbidden vertices * from compensator. */ for (Integer i : toRemoveFromCompensator) { compensator.set(i, false); } /* * Compensate swap that will take place * in a moment using updated compensator. */ changeColor(compensator, colorOther, sizeDifference); /* * Update compensator with vertices newly * added to small color class. */ for (Integer i : getFrom3To(bigComponent, colorSmall)) { compensator.set(i); } changeColor(bigComponent, colorSmall); changeColor(smallComponent, colorBig); } } return sizeDifference; } private int moveNeighbour(LinkedList<Integer> small3Big, BooleanArray compensator, int verticesToMove) { //TODO Graph graph = coloring.getGraph(); int verticesMoved = 0, neighboursInBig; for (Integer i : small3Big) { if (0 < verticesToMove) { for (Integer j: graph.getNeighbours(i)) { neighboursInBig = 0; for (Integer k: graph.getNeighbours(j)) { if (coloring.get(k) == colorSmall) { neighboursInBig++; } } if(neighboursInBig == 1) { coloring.set(i, colorOther); coloring.set(j, colorBig); compensator.set(i, false); verticesMoved++; verticesToMove break; } } } else { break; } } return verticesMoved; } private int moveCommonNeighbours(LinkedList<Integer> small3Big, BooleanArray compensator, int verticesToMove) { //TODO Graph graph = coloring.getGraph(); int verticesMoved = 0, other = 0; boolean isCommonNeighbour; for (Integer i : small3Big) { if (0 < verticesToMove) { for (Integer j: graph.getNeighbours(i)) { isCommonNeighbour = false; for (Integer k: graph.getNeighbours(j)) { if (X3Y.hasAllNeighboursInY(k, colorBig, coloring)) { isCommonNeighbour = true; other = k; break; } } if (isCommonNeighbour) { //TODO arguments if (moveCommonAndSpare(i, other, j)) { compensator.set(i, false); verticesMoved++; verticesToMove } break; } } } else { break; } } return verticesMoved; } private boolean moveCommonAndSpare(int x, int y, int z) { //TODO return false; } private int reduceToPathsAndSwap() { //TODO return 0; } /** * Find components within induced graph of * two given color starting from vertex with * current index. * * @param current index to start with * @param bigComponent container of indexes to fill * @param smallComponent container of indexes to fill */ private void findComponents(int current, LinkedList<Integer> bigComponent, LinkedList<Integer> smallComponent, BitSet checked) { Queue<Integer> queue = new LinkedList<>(); int currentColor, otherColor; queue.add(current); while (!queue.isEmpty()) { current = queue.poll(); currentColor = coloring.get(current); if (currentColor == colorBig) { otherColor = colorSmall; bigComponent.add(current); } else { otherColor = colorBig; smallComponent.add(current); } for (Integer neighbour : graph.getNeighbours(current)) { if (coloring.get(neighbour) == otherColor && !checked.get(neighbour)) { queue.add(neighbour); } checked.set(neighbour); } } } /** * Change n vertices from vertices list to * given color and remove them from list. * * @param vertices list of available vertices * @param color that vertices will now have * @param n number of vertices to be changed * @return number of vertices changed */ int changeColor(LinkedList<Integer> vertices, int color, int n) { int changed = 0; for (int i = 0; 0 < vertices.size() && changed < n; i++) { coloring.set(vertices.poll(), color); changed++; } return changed; } private void changeColor(LinkedList<Integer> vertices, int color) { changeColor(vertices, color, vertices.size()); } private int changeColorWithoutPolling(LinkedList<Integer> vertices, int color, int n) { int changed = 0; for (Integer i : vertices) { coloring.set(i, color); if(n <= ++changed) { break; } } return changed; } /** * Change n vertices that have 1 assigned in the bit set * to a given color. * * @param vertices bit set with 1 for all available vertices * @param color that vertices will now have * @param n number of vertices to change color */ private void changeColor(BitSet vertices, int color, int n) { for (int i = 0; i < vertices.size() && 0 < n; i++) { if (vertices.get(i)) { coloring.set(i, color); n } } } /** * Set all the bits representing vertices in list to 1. * * @param list of vertices to put in BitSet * @return BooleanArray representing list */ private BooleanArray vertexListToArray(LinkedList<Integer> list) { BooleanArray booleanArray = new BooleanArray(graph.getVertices()); for (Integer i : list) { booleanArray.set(i); } return booleanArray; } private LinkedList<Integer> getFrom3To(LinkedList<Integer> fromComponent, int toColor) { LinkedList<Integer> big3Small = new LinkedList<>(); for (Integer i : fromComponent) { if (X3Y.hasAllNeighboursInY(i, toColor, coloring)) { big3Small.add(i); } } return big3Small; } }
package it.cnr.isti.vir.id; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; public class IDFace extends AbstractID { public final String id; public final float minX; public final float minY; public final float maxX; public final float maxY; public final int inImageID; public IDFace(String id) { this(id, -1, Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE); } public IDFace(String id, int inImageID) { this(id, inImageID, Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE); } public IDFace(String id,float minX, float minY, float maxX, float maxY) { this(id, -1, minX, minY, maxX, maxY); } /** * The rectangle of the face in the image is expressed in float. * Min and max x and y are reported as relative position in the image * in order to be invariant to resize of the image. * Thus if x=300 pixels and image has a width of 600, x sould be 0.5 * * @param id The ID of the whole image * @param inImageID Optional ID for the face in the image * @param minX * @param minY * @param maxX * @param maxY */ public IDFace(String id, int inImageID, float minX, float minY, float maxX, float maxY) { this.id = id; this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; this.inImageID = inImageID; } @Override public void writeData(DataOutput out) throws IOException { out.writeInt ( id.length()); out.writeChars ( id ); out.writeInt( inImageID); out.writeFloat(minX); out.writeFloat(minY); out.writeFloat(maxX); out.writeFloat(maxY); } public IDFace(ByteBuffer in) throws IOException { int size = in.getInt(); char[] chars = new char[size]; for ( int i=0; i<chars.length; i++ ) { chars[i] = in.getChar(); } id = new String(chars); inImageID = in.getInt(); minX = in.getFloat(); minY = in.getFloat(); maxX = in.getFloat(); maxY = in.getFloat(); } public IDFace(DataInput in) throws IOException { int size = in.readInt(); char[] chars = new char[size]; byte[] byteArray = new byte[size*2]; CharBuffer inBuffer = ByteBuffer.wrap(byteArray).asCharBuffer(); in.readFully(byteArray); inBuffer.get(chars, 0, size); id = new String(chars); inImageID = in.readInt(); minX = in.readFloat(); minY = in.readFloat(); maxX = in.readFloat(); maxY = in.readFloat(); } public static final IDFace[] readArray(DataInput in, int n) throws IOException { IDFace[] arr = new IDFace[n]; for ( int i=0; i<arr.length; i++ ) { arr[i] = new IDFace(in); } return arr; } public boolean equals(Object obj) { return this.id.equals(((IDFace) obj).id) && this.inImageID==((IDFace) obj).inImageID; } public final int hashCode() { return id.hashCode()*31+Integer.hashCode(inImageID); } public String toString() { if (inImageID < 0) return "" + id; else return id + "_" + inImageID; } @Override public int compareTo(AbstractID o) { // if ID classes differ the class id is used for comparing if ( !o.getClass().equals(IDFace.class) ) return IDClasses.getClassID(this.getClass()) - IDClasses.getClassID(o.getClass()); int temp = id.compareTo(((IDString) o).id); if ( temp == 0 ) return Integer.compare(this.inImageID,((IDFace)o).inImageID); else return temp; } public String getId() { return id; } public float getMinX() { return minX; } public float getMinY() { return minY; } public float getMaxX() { return maxX; } public float getMaxY() { return maxY; } public int getInImageID() { return inImageID; } }
package jade.onto; import java.lang.reflect.*; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; /** @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class DefaultOntology implements Ontology { private static final List primitiveTypes = new ArrayList(10); static { primitiveTypes.add(BOOLEAN_TYPE, Boolean.TYPE); primitiveTypes.add(BYTE_TYPE, Byte.TYPE); primitiveTypes.add(CHARACTER_TYPE, Character.TYPE); primitiveTypes.add(DOUBLE_TYPE, Double.TYPE); primitiveTypes.add(FLOAT_TYPE, Float.TYPE); primitiveTypes.add(INTEGER_TYPE, Integer.TYPE); primitiveTypes.add(LONG_TYPE, Long.TYPE); primitiveTypes.add(SHORT_TYPE, Short.TYPE); primitiveTypes.add(STRING_TYPE, String.class); primitiveTypes.add(BINARY_TYPE, (new byte[0]).getClass()); } // Special slot, all actions must have it. private static final TermDescriptor actorSlot = new TermDescriptor(":actor", STRING_TYPE, M); private Map schemas; private Map factories; public DefaultOntology() { schemas = new HashMap(); factories = new HashMap(); } // Raw interface, exposes Frame Schemas directly. // This is package scoped, not to be used by applications. FrameSchema lookupSchema(String name) { return (FrameSchema)schemas.get(new Name(name)); } RoleFactory lookupFactory(String name) { return (RoleFactory)factories.get(new Name(name)); } public void addFrame(String conceptName, int kind, TermDescriptor[] slots) throws OntologyException { if((kind != CONCEPT_TYPE) && (kind != ACTION_TYPE) && (kind != PREDICATE_TYPE)) throw new OntologyException("Error: Unknown kind of Frame requested"); FrameSchema fs = new FrameSchema(this, conceptName, kind); for(int i = 0; i < slots.length; i++) { String n = slots[i].getName(); if(n.length() == 0) slots[i].setName("_" + i); fs.addTerm(slots[i]); } // Add a special ':actor' slot for actions if(kind == ACTION_TYPE) fs.addTerm(actorSlot); addSchemaToTable(conceptName, fs); } public void addFrame(String conceptName, int kind, TermDescriptor[] slots, RoleFactory rf) throws OntologyException { addFrame(conceptName, kind, slots); Class c = rf.getClassForRole(); checkClass(conceptName, c); addFactoryToTable(conceptName, rf); } public Object createObject(Frame f) throws OntologyException { String roleName = f.getName(); RoleFactory fac = lookupFactory(roleName); if(fac == null) throw new OntologyException("No class able to play " + roleName + " role."); Class c = fac.getClassForRole(); Object o = fac.create(f); return initObject(f, o, c); } public Frame createFrame(Object o, String roleName) throws OntologyException { RoleFactory rf = lookupFactory(roleName); if(rf == null) throw new OntologyException("No class able to play " + roleName + " role."); Class theConceptClass = rf.getClassForRole(); if(!theConceptClass.isInstance(o)) throw new OntologyException("The object <" + o + "> is not an instance of " + theConceptClass.getName() + " class."); FrameSchema fs = lookupSchema(roleName); if(fs == null) throw new OntologyException("Internal error: inconsistency between schema and class table"); if(!fs.isConcept() && !fs.isAction() && !fs.isPredicate()) throw new OntologyException("The role " + roleName + " is not a concept, action or predicate in this ontology."); Frame f = new Frame(roleName); buildFromObject(f, fs, o, theConceptClass); return f; } public void check(Frame f) throws OntologyException { String roleName = f.getName(); FrameSchema fs = lookupSchema(roleName); fs.checkAgainst(f); } public void check(Object o, String roleName) throws OntologyException { /* * Algorithm: * * - Check that the object is an instance of the correct class * - FOR EACH term t * - The Object get method must not return 'null' */ RoleFactory rf = lookupFactory(roleName); if(rf == null) throw new OntologyException("No class able to play " + roleName + " role."); Class implementationClass = rf.getClassForRole(); if(!implementationClass.isInstance(o)) throw new OntologyException("The object is not an instance of " + implementationClass.getName() + " class."); FrameSchema fs = lookupSchema(roleName); Iterator it = fs.subSchemas(); while(it.hasNext()) { TermDescriptor desc = (TermDescriptor)it.next(); Method m = findMethodCaseInsensitive("get" + translateName(desc.getName()), implementationClass.getMethods()); try { Object value = m.invoke(o, new Object[] { }); if(!desc.isOptional() && (value == null)) throw new OntologyException("The given object has a 'null' value for the mandatory term " + desc.getName()); if(desc.isComplex()) // Recursive check for subobjects check(value, desc.getTypeName()); } catch(InvocationTargetException ite) { String msg = ite.getTargetException().getMessage(); throw new OntologyException("Internal error: a reflected method threw an exception.\nMessage was " + msg); } catch(IllegalAccessException iae) { throw new OntologyException("Internal error: the required method is not accessible [" + iae.getMessage() + "]"); } catch(SecurityException se) { throw new OntologyException("Wrong class: some required method is not accessible."); } } } public boolean isConcept(String roleName) throws OntologyException { FrameSchema fs = lookupSchema(roleName); if(fs == null) throw new OntologyException("No schema was found for " + roleName + "role."); return fs.isConcept(); } public boolean isAction(String roleName) throws OntologyException { FrameSchema fs = lookupSchema(roleName); if(fs == null) throw new OntologyException("No schema was found for " + roleName + "role."); return fs.isAction(); } public boolean isPredicate(String roleName) throws OntologyException { FrameSchema fs = lookupSchema(roleName); if(fs == null) throw new OntologyException("No schema was found for " + roleName + "role."); return fs.isPredicate(); } public TermDescriptor[] getTerms(String roleName) throws OntologyException { FrameSchema fs = lookupSchema(roleName); return fs.termsArray(); } // Private methods. private String translateName(String name) { StringBuffer buf = new StringBuffer(name); for(int i = 0; i < buf.length(); i++) { char c = buf.charAt(i); switch(c) { case ':': buf.deleteCharAt(i); --i; break; case '-': buf.deleteCharAt(i); buf.setCharAt(i, Character.toUpperCase(buf.charAt(i))); --i; break; } } return new String(buf); } private Class checkGetAndSet(String name, Method[] methods) throws OntologyException { Class result; Method getMethod = findMethodCaseInsensitive("get" + name, methods); Method setMethod = findMethodCaseInsensitive("set" + name, methods); // Make sure "get" method takes no arguments. Class[] getParams = getMethod.getParameterTypes(); if(getParams.length > 0) throw new OntologyException("Wrong class: method " + getMethod.getName() + "() must take no arguments."); // Now find a matching set method. result = getMethod.getReturnType(); Class[] setParams = setMethod.getParameterTypes(); if((setParams.length != 1) || (!setParams[0].equals(result))) throw new OntologyException("Wrong class: method " + setMethod.getName() + "() must take a single argument of type " + result.getName() + "."); Class setReturn = setMethod.getReturnType(); if(!setReturn.equals(Void.TYPE)) throw new OntologyException("Wrong class: method " + setMethod.getName() + "() must return void."); return result; } private void checkClass(String roleName, Class c) throws OntologyException { FrameSchema fs = lookupSchema(roleName); if(fs == null) throw new OntologyException("No schema was found for " + roleName + "role."); Iterator it = fs.subSchemas(); while(it.hasNext()) { TermDescriptor desc = (TermDescriptor)it.next(); String termName = translateName(desc.getName()); try { Method[] methods = c.getMethods(); // Check for correct set and get methods for the current // descriptor and retrieve the implementation type. Class implType = checkGetAndSet(termName, methods); // If the descriptor is a complex term (Concept, Action or // Predicate) and some class C is registered for that role, // then the implementation type must be a supertype of C. if(desc.isComplex()) { RoleFactory rf = lookupFactory(desc.getTypeName()); if(rf != null) { Class roleType = rf.getClassForRole(); if(!implType.isAssignableFrom(roleType)) throw new OntologyException("Wrong class: the " + desc.getName() + " role is played by " + roleType + " class, which is not a subtype of " + implType + " class."); } } else { // Check that the returned type is compatible with the one dictated by the TermDescriptor Class primitive = (Class)primitiveTypes.get(desc.getType()); if(!implType.isAssignableFrom(primitive)) throw new OntologyException("Wrong class: the primitive term " + desc.getName() + " is of type "+ primitive + ", but must be a subtype of " + implType + " class."); } } catch(SecurityException se) { throw new OntologyException("Wrong class: some required method is not accessible."); } } } private Object initObject(Frame f, Object concept, Class theConceptClass) throws OntologyException { String roleName = f.getName(); FrameSchema fs = lookupSchema(roleName); Iterator it = fs.subSchemas(); while(it.hasNext()) { TermDescriptor desc = (TermDescriptor)it.next(); String slotName = desc.getName(); String methodName = "set" + translateName(slotName); // Retrieve the modifier method from the class and call it Method setMethod = findMethodCaseInsensitive(methodName, theConceptClass.getMethods()); try { Object slotValue = f.getSlot(slotName); // System.out.println("Name: " + slotName + " - Value: " + slotValue); // For complex slots, transform from sub-frame to sub-object. // This is performed calling createObject() recursively. if(desc.isComplex()) slotValue = createObject((Frame)slotValue); setMethod.invoke(concept, new Object[] { slotValue }); } catch(Frame.NoSuchSlotException fnsse) { // Ignore 'No such slot' errors for optional slots if(!desc.isOptional()) throw fnsse; } catch(InvocationTargetException ite) { Throwable e = ite.getTargetException(); e.printStackTrace(); throw new OntologyException("Internal error: a reflected method threw an exception.\n e.getMessage()"); } catch(IllegalAccessException iae) { throw new OntologyException("Internal error: the required method is not accessible [" + iae.getMessage() + "]"); } catch(SecurityException se) { throw new OntologyException("Wrong class: some required method is not accessible."); } } return concept; } private void buildFromObject(Frame f, FrameSchema fs, Object o, Class c) throws OntologyException { Iterator it = fs.subSchemas(); while(it.hasNext()) { TermDescriptor desc = (TermDescriptor)it.next(); String name = desc.getName(); String methodName = translateName(name); // Retrieve the accessor method from the class and call it Method getMethod = findMethodCaseInsensitive("get" +methodName, c.getMethods()); try { Object value = getMethod.invoke(o, new Object[] { }); // Now set the corresponding frame subterm appropriately if(!desc.isComplex()) { // For elementary terms, just put the Object as a slot f.putSlot(name, value); } else { // For complex terms, do a name lookup and call createFrame() recursively String roleName = desc.getTypeName(); f.putSlot(name, createFrame(value, roleName)); } } catch(InvocationTargetException ite) { String msg = ite.getTargetException().getMessage(); throw new OntologyException("Internal error: a reflected method threw an exception.\nMessage was " + msg); } catch(IllegalAccessException iae) { throw new OntologyException("Internal error: the required method is not accessible [" + iae.getMessage() + "]"); } catch(SecurityException se) { throw new OntologyException("Wrong class: some required method is not accessible."); } } } private void addSchemaToTable(String roleName, FrameSchema fs) { schemas.put(new Name(roleName), fs); } private void addFactoryToTable(String roleName, RoleFactory rf) { factories.put(new Name(roleName), rf); } private Method findMethodCaseInsensitive(String name, Method[] methods) throws OntologyException { for(int i = 0; i < methods.length; i++) { String ithName = methods[i].getName(); if(ithName.equalsIgnoreCase(name)) return methods[i]; } throw new OntologyException("Method " + name + " not found."); } }
package stray.blocks; import com.badlogic.gdx.math.MathUtils; import stray.Main; import stray.util.MathHelper; import stray.util.ParticlePool; import stray.world.World; public class BlockGearCollectible extends BlockCollectible { public BlockGearCollectible(String path) { super(path, collectibleName); } public static final String collectibleName = "gears"; @Override public void render(World world, int x, int y) { super.renderWithOffset( world, x, y, 0, (World.tilesizey / 8f) * ((MathHelper.clampNumberFromTime(System.currentTimeMillis() + (2500 - ((x % 4) * 625)), 2.5f) * 2f) - 0.5f)); } @Override public void tickUpdate(World world, int x, int y) { super.tickUpdate(world, x, y); if (world.tickTime % 2 == 0) return; world.particles.add(ParticlePool .obtain() .setTexture("checkpoint") .setPosition(x + 0.5f + MathUtils.random(-0.25f, 0.25f), y + 0.5f + MathUtils.random(-0.25f, 0.25f)).setStartScale(0.2f) .setEndScale(0.1f).setLifetime(0.5f).setAlpha(0.25f) .setVelocity(MathUtils.random(-0.5f, 0.5f), -MathUtils.random(0.5f, 1.1f))); } }
// Convert.java package ed.js.engine; import java.io.*; import java.util.*; import org.mozilla.javascript.*; import ed.js.*; import ed.io.*; import ed.util.*; public class Convert { static boolean D = Boolean.getBoolean( "DEBUG.JS" ); public static final String DEFAULT_PACKAGE = "ed.js.gen"; public static JSFunction makeAnon( String code ){ try { Convert c = new Convert( "anon" + Math.random() , code ); return c.get(); } catch ( IOException ioe ){ throw new RuntimeException( "should be impossible" , ioe ); } } public Convert( File sourceFile ) throws IOException { this( sourceFile.toString() , StreamUtil.readFully( sourceFile , "UTF-8" ) ); } public Convert( String name , String source ) throws IOException { _name = name; _source = source; _className = _name.replaceAll(".*/(.*?)","").replaceAll( "[^\\w]+" , "_" ); CompilerEnvirons ce = new CompilerEnvirons(); Parser p = new Parser( ce , ce.getErrorReporter() ); ScriptOrFnNode theNode = p.parse( _source , _name , 0 ); _encodedSource = p.getEncodedSource(); init( theNode ); } private void init( ScriptOrFnNode sn ){ if ( _it != null ) throw new RuntimeException( "too late" ); NodeTransformer nf = new NodeTransformer(); nf.transform( sn ); if ( D ){ Debug.print( sn , 0 ); } State state = new State(); _setLineNumbers( sn , sn ); _addFunctionNodes( sn , state ); if ( D ) System.out.println( "***************" ); Node n = sn.getFirstChild(); while ( n != null ){ if ( n.getType() != Token.FUNCTION ){ if ( n.getNext() == null ){ if ( n.getType() == Token.EXPR_RESULT ){ _append( "return " , n ); _hasReturn = true; } if ( n.getType() == Token.RETURN ) _hasReturn = true; } _add( n , sn , state ); _append( "\n" , n ); } n = n.getNext(); } if ( ! _hasReturn ) { _append( "return null;" , sn ); } else { int end = _mainJavaCode.length() - 1; boolean alreadyHaveOne = false; for ( ; end >= 0; end char c = _mainJavaCode.charAt( end ); if ( Character.isWhitespace( c ) ) continue; if ( c == ';' ){ if ( ! alreadyHaveOne ){ alreadyHaveOne = true; continue; } _mainJavaCode.setLength( end + 1 ); } break; } } } private void _add( Node n , State s ){ _add( n , null , s ); } private void _add( Node n , ScriptOrFnNode sn , State state ){ switch ( n.getType() ){ case Token.TYPEOF: _append( "JS_typeof( " , n ); _assertOne( n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.TYPEOFNAME: _append( "JS_typeof( " , n ); if ( state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); _append( " ) " , n ); break; case Token.REGEXP: int myId = _regex.size(); ScriptOrFnNode parent = _nodeToSOR.get( n ); int rId = n.getIntProp( Node.REGEXP_PROP , -1 ); _regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) ); _append( " _regex[" + myId + "] " , n ); break; case Token.ARRAYLIT: { _append( "( JSArray.create( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) ) " , n ); } break; case Token.OBJECTLIT: { _append( "JS_buildLiteralObject( new String[]{ " , n ); boolean first = true; for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){ if ( first ) first = false; else _append( " , " , n ); //_append( "\"" + id.toString() + "\"" , n ); _append( getStringCode( id.toString() ) + ".toString()" , n ); } _append( " } " , n ); Node c = n.getFirstChild(); while ( c != null ){ _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) " , n ); } break; case Token.NEW: _append( "scope.clearThisNew( " , n ); _addCall( n , state , true ); _append( " ) " , n ); break; case Token.THIS: _append( "passedIn.getThis()" , n ); break; case Token.INC: case Token.DEC: _assertOne( n ); Node tempChild = n.getFirstChild(); if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ) throw new RuntimeException( "can't increment local variables" ); _append( "JS_inc( " , n ); _createRef( n.getFirstChild() , state ); _append( " , " , n ); _append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n ); _append( " , " , n ); _append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n ); _append( ")" , n ); break; case Token.USE_STACK: _append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n ); break; case Token.SETPROP_OP: case Token.SETELEM_OP: Node theOp = n.getFirstChild().getNext().getNext(); if ( theOp.getType() == Token.ADD && ( theOp.getFirstChild().getType() == Token.USE_STACK || theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){ _append( "\n" , n ); _append( "JS_setDefferedPlus( (JSObject) " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( theOp.getFirstChild().getType() == Token.USE_STACK ? theOp.getFirstChild().getNext() : theOp.getFirstChild() , state ); _append( " \n ) \n" , n ); break; } _append( "\n { \n" , n ); _append( "JSObject __tempObject = (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); String tempName = "__temp" + (int)(Math.random() * 10000); state._tempOpNames.push( tempName ); _append( "Object " + tempName + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( ";\n" , n ); _append( " __tempObject.set(" , n ); _append( tempName , n ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ); \n" , n ); _append( " } \n" , n ); break; case Token.SETPROP: case Token.SETELEM: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ").set( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) " , n ); break; case Token.GETPROPNOWARN: case Token.GETPROP: case Token.GETELEM: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ").get( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.SET_REF: _assertType( n.getFirstChild() , Token.REF_SPECIAL ); _assertType( n.getFirstChild().getFirstChild() , Token.NAME ); _append( "((JSObject)" , n ); _add( n.getFirstChild().getFirstChild() , state ); _append( ").set( \"" , n ); _append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n ); _append( "\" , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.GET_REF: _assertType( n.getFirstChild() , Token.REF_SPECIAL ); _append( "((JSObject)" , n ); _add( n.getFirstChild().getFirstChild() , state ); _append( ").get( \"" , n ); _append( n.getFirstChild().getProp( Node.NAME_PROP ).toString() , n ); _append( "\" )" , n ); break; case Token.EXPR_RESULT: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.CALL: _addCall( n , state ); break; case Token.NUMBER: double d = n.getDouble(); String temp = String.valueOf( d ); boolean useInt = temp.endsWith( ".0" ) || JSNumericFunctions.couldBeInt( d ); if ( useInt ) temp = "Integer.valueOf( " + ((int)d) + " ) "; else temp = "Double.valueOf( " + temp + " ) "; _append( temp , n ); break; case Token.STRING: _append( getStringCode( n.getString() ) , n ); //int stringId = _strings.size(); //_strings.add( n.getString() ); //_append( "_strings[" + stringId + "]" ,n ); break; case Token.TRUE: _append( " true " , n ); break; case Token.FALSE: _append( " false " , n ); break; case Token.NULL: _append( " null " , n ); break; case Token.VAR: _addVar( n , state ); break; case Token.GETVAR: if ( state.useLocalVariable( n.getString() ) ){ _append( n.getString() , n ); break; } case Token.NAME: if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); break; case Token.SETVAR: final String foo = n.getFirstChild().getString(); if ( state.useLocalVariable( foo ) ){ if ( ! state.hasSymbol( foo ) ) throw new RuntimeException( "something is wrong" ); _append( "JSInternalFunctions.self ( " , n ); _append( foo + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n" , n ); } else { _setVar( foo , n.getFirstChild().getNext() , state , true ); } break; case Token.SETNAME: _addSet( n , state ); break; case Token.FUNCTION: _addFunction( n , state ); break; case Token.BLOCK: _addBlock( n , state ); break; case Token.EXPR_VOID: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.RETURN: boolean last = n.getNext() == null; if ( ! last ) _append( "if ( true ) { " , n ); _append( "return " , n ); if ( n.getFirstChild() != null ){ _assertOne( n ); _add( n.getFirstChild() , state ); } else { _append( " null " , n ); } _append( ";" , n ); if ( ! last ) _append( "}" , n ); _append( "\n" , n ); break; case Token.BITNOT: _assertOne( n ); _append( "JS_bitnot( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.HOOK: _append( " JSInternalFunctions.self( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ? ( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) : ( " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) ) " , n ); break; case Token.NE: _append( " ! " , n ); case Token.MUL: case Token.DIV: case Token.ADD: case Token.SUB: case Token.EQ: case Token.SHEQ: case Token.SHNE: case Token.GE: case Token.LE: case Token.LT: case Token.GT: case Token.BITOR: case Token.BITAND: case Token.BITXOR: case Token.URSH: case Token.RSH: case Token.LSH: case Token.MOD: _append( "JS_" , n ); String fooooo = _2ThingThings.get( n.getType() ); if ( fooooo == null ) throw new RuntimeException( "noting for : " + n ); _append( fooooo , n ); _append( "\n( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n " , n ); break; case Token.IFNE: _addIFNE( n , state ); break; case Token.LOOP: _addLoop( n , state ); break; case Token.EMPTY: if ( n.getFirstChild() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "not really empty" ); } break; case Token.LABEL: _append( n.getString() + ":" , n ); break; case Token.BREAK: _append( "break " + n.getString() + ";\n" , n ); break; case Token.CONTINUE: _append( "continue " + n.getString() + ";\n" , n ); break; case Token.WHILE: _append( "while( false || JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ) " , n ); _add( n.getFirstChild().getNext() , state ); break; case Token.FOR: _addFor( n , state ); break; case Token.TARGET: break; case Token.NOT: _assertOne( n ); _append( " JS_not( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.AND: _append( " ( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " && " , n ); _append( " JS_evalToBool( " , n ); _add( c , state ); _append( " ) " , n ); c = c.getNext(); } _append( " ) " , n ); break; case Token.OR: Node cc = n.getFirstChild(); if ( cc.getNext() == null ) throw new RuntimeException( "what?" ); if ( cc.getNext().getNext() != null ) throw new RuntimeException( "what?" ); _append( "JSInternalFunctions.self( scope.orSave( " , n ); _add( cc , state ); _append( " ) ? scope.getOrSave() : ( " , n ); _add( cc.getNext() , state ); _append( " ) ) " , n ); break; case Token.LOCAL_BLOCK: _assertOne( n ); if ( n.getFirstChild().getType() != Token.TRY ) throw new RuntimeException("only know about LOCAL_BLOCK with try" ); _addTry( n.getFirstChild() , state ); break; case Token.THROW: _append( "if ( true ) throw new JSException( " , n ); _add( n.getFirstChild() , state ); _append( " ); " , n ); break; case Token.INSTANCEOF: _append( "JS_instanceof( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); if ( n.getFirstChild().getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); break; case Token.DELPROP: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " ).removeField( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); break; case Token.SWITCH: _addSwitch( n , state ); break; case Token.COMMA: _append( "JS_comma( " , n ); boolean first = true; Node inner = n.getFirstChild(); while ( inner != null ){ if ( first ) first = false; else _append( " , " , n ); _append( "\n ( " , n ); _add( inner , state ); _append( " )\n " , n ); inner = inner.getNext(); } _append( " ) " , n ); break; case Token.IN: _append( "((JSObject)" , n ); _add( n.getFirstChild().getNext() , state ); _append( " ).containsKey( " , n ); _add( n.getFirstChild() , state ); _append( ".toString() ) " , n ); break; case Token.NEG: _append( "JS_mul( -1 , " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.ENTERWITH: _append( "scope.enterWith( (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " );" , n ); break; case Token.LEAVEWITH: _append( "scope.leaveWith();" , n ); break; case Token.WITH: _add( n.getFirstChild() , state ); break; default: Debug.printTree( n , 0 ); throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() ); } } private void _addSwitch( Node n , State state ){ _assertType( n , Token.SWITCH ); String ft = "ft" + (int)(Math.random() * 10000); String val = "val" + (int)(Math.random() * 10000); _append( "boolean " + ft + " = false;\n" , n ); _append( "do { \n " , n ); _append( " if ( false ) break; \n" , n ); Node caseArea = n.getFirstChild(); _append( "Object " + val + " = " , n ); _add( caseArea , state ); _append( " ; \n " , n ); n = n.getNext(); _assertType( n , Token.GOTO ); // this is default ? n = n.getNext().getNext(); caseArea = caseArea.getNext(); while ( caseArea != null ){ _append( "if ( " + ft + " || JS_eq( " + val + " , " , caseArea ); _add( caseArea.getFirstChild() , state ); _append( " ) ){\n " + ft + " = true; \n " , caseArea ); _assertType( n , Token.BLOCK ); _add( n , state ); n = n.getNext().getNext(); _append( " } \n " , caseArea ); caseArea = caseArea.getNext(); } if ( n != null && n.getType() == Token.BLOCK ){ _add( n , state ); } _append(" } while ( false );\n " , n ); //throw new RuntimeException( "switch not supported yet" ); } private void _createRef( Node n , State state ){ if ( n.getType() == Token.NAME || n.getType() == Token.GETVAR ){ if ( state.useLocalVariable( n.getString() ) ) throw new RuntimeException( "can't create a JSRef from a local variable : " + n.getString() ); _append( " new JSRef( scope , null , " , n ); _append( "\"" + n.getString() + "\"" , n ); _append( " ) " , n ); return; } if ( n.getType() == Token.GETPROP || n.getType() == Token.GETELEM ){ _append( " new JSRef( scope , (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); return; } throw new RuntimeException( "can't handle" ); } private void _addTry( Node n , State state ){ _assertType( n , Token.TRY ); Node mainBlock = n.getFirstChild(); _assertType( mainBlock , Token.BLOCK ); _append( "try { \n " , n ); _add( mainBlock , state ); _append( " \n } \n " , n ); n = mainBlock.getNext(); while ( n != null ){ if ( n.getType() == Token.FINALLY ){ _assertType( n.getFirstChild() , Token.BLOCK ); _append( "finally { \n" , n ); _add( n.getFirstChild() , state ); _append( " \n } \n " , n ); n = n.getNext(); continue; } if ( n.getType() == Token.LOCAL_BLOCK && n.getFirstChild().getType() == Token.CATCH_SCOPE ){ Node c = n.getFirstChild(); Node b = c.getNext(); _assertType( b , Token.BLOCK ); _assertType( b.getFirstChild() , Token.ENTERWITH ); _assertType( b.getFirstChild().getNext() , Token.WITH ); b = b.getFirstChild().getNext().getFirstChild(); _assertType( b , Token.BLOCK ); //Debug.printTree( b , 0 ); String jsName = c.getFirstChild().getString(); String javaName = "javaEEE" + jsName; _append( " catch ( Throwable " + javaName + " ){ \n " , c ); _append( " if ( " + javaName + " instanceof JSException ) " , c ); _append( " scope.put( \"" + jsName + "\" , ((JSException)" + javaName + ").getObject() , true ); " , c ); _append( " else \n " , c ); _append( " scope.put( \"" + jsName + "\" , " + javaName + " , true ); " , c ); b = b.getFirstChild(); while ( b != null ){ if ( b.getType() == Token.LEAVEWITH ) break; _add( b , state ); b = b.getNext(); } _append( " } \n " , c ); n = n.getNext(); continue; } if ( n.getType() == Token.GOTO || n.getType() == Token.TARGET || n.getType() == Token.JSR ){ n = n.getNext(); continue; } throw new RuntimeException( "what : " + n.getType() ); } } private void _addFor( Node n , State state ){ _assertType( n , Token.FOR ); final int numChildren = countChildren( n ); if ( numChildren == 4 ){ _append( "\n for ( " , n ); if ( n.getFirstChild().getType() == Token.BLOCK ){ Node temp = n.getFirstChild().getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.EXPR_VOID ) _add( temp.getFirstChild() , state ); else _add( temp , state ); temp = temp.getNext(); if ( temp != null ) _append( " , " , n ); } _append( " ; " , n ); } else { _add( n.getFirstChild() , state ); _append( " ; " , n ); } _append( " \n JS_evalToBool( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ; \n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " )\n " , n ); _add( n.getFirstChild().getNext().getNext().getNext() , state ); } else if ( numChildren == 3 ){ String name = n.getFirstChild().getString(); String tempName = name + "TEMP"; _append( "\n for ( String " , n ); _append( tempName , n ); _append( " : ((JSObject)" , n ); _add( n.getFirstChild().getNext() , state ); _append( " ).keySet() ){\n " , n ); if ( state.useLocalVariable( name ) ) _append( name + " = new JSString( " + tempName + ") ; " , n ); else _append( "scope.put( \"" + name + "\" , new JSString( " + tempName + " ) , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } else { throw new RuntimeException( "wtf?" ); } } private void _addLoop( Node n , State state ){ _assertType( n , Token.LOOP ); final Node theLoop = n; n = n.getFirstChild(); Node nodes[] = null; if ( ( nodes = _matches( n , _while1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[5]; _append( "while ( JS_evalToBool( " , theLoop ); _add( predicate.getFirstChild() , state ); _append( " ) ) " , theLoop ); _add( main , state ); } else if ( ( nodes = _matches( n , _doWhile1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[3]; _assertType( predicate , Token.IFEQ ); _append( "do { \n " , theLoop ); _add( main , state ); _append( " } \n while ( false || JS_evalToBool( " , n ); _add( predicate.getFirstChild() , state ); _append( " ) );\n " , n ); } else { throw new RuntimeException( "what?" ); } } private void _addIFNE( Node n , State state ){ _assertType( n , Token.IFNE ); final Node.Jump theIf = (Node.Jump)n; _assertOne( n ); // this is the predicate Node ifBlock = n.getNext(); _append( "if ( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){\n" , n ); _add( ifBlock , state ); _append( "}\n" , n ); n = n.getNext().getNext(); if ( n.getType() == Token.TARGET ){ if ( n.getNext() != null ) throw new RuntimeException( "something is wrong" ); return; } _assertType( n , Token.GOTO ); _assertType( n.getNext() , Token.TARGET ); if ( theIf.target.hashCode() != n.getNext().hashCode() ) throw new RuntimeException( "hashes don't match" ); n = n.getNext().getNext(); _append( " else if ( true ) { " , n ); _add( n , state ); _append( " } \n" , n ); _assertType( n.getNext() , Token.TARGET ); if ( n.getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); } private void _addFunctionNodes( ScriptOrFnNode sn , State state ){ for ( int i=0; i<sn.getFunctionCount(); i++ ){ FunctionNode fn = sn.getFunctionNode( i ); _setLineNumbers( fn , fn ); String name = fn.getFunctionName(); if ( name.length() == 0 ) name = "tempFunc_" + _id + "_" + i + "_" + _methodId++; state._functionIdToName.put( i , name ); if ( D ){ System.out.println( "***************" ); System.out.println( i + " : " + name ); } _setVar( name , fn , state ); _append( "; \n scope.getFunction( \"" + name + "\" ).setName( \"" + name + "\" );\n\n" , fn ); } } private void _addFunction( Node n , State state ){ if ( ! ( n instanceof FunctionNode ) ){ if ( n.getString() != null && n.getString().length() != 0 ) return; _append( getFunc( n , state ) , n ); return; } FunctionNode fn = (FunctionNode)n; _assertOne( n ); state = state.child(); state._hasLambdaExpressions = fn.getFunctionCount() > 0; boolean hasArguments = false; { List<Node> toSearch = new ArrayList<Node>(); toSearch.add( n ); while ( toSearch.size() > 0 ){ Node cur = toSearch.remove( toSearch.size() - 1 ); if ( cur.getType() == Token.NAME || cur.getType() == Token.GETVAR ) if ( cur.getString().equals( "arguments" ) ) hasArguments = true; if ( cur.getType() == Token.INC || cur.getType() == Token.DEC ){ if ( cur.getFirstChild().getType() == Token.GETVAR || cur.getFirstChild().getType() == Token.NAME ){ state.addBadLocal( cur.getFirstChild().getString() ); } } if ( cur.getNext() != null ) toSearch.add( cur.getNext() ); if ( cur.getFirstChild() != null ) toSearch.add( cur.getFirstChild() ); } } //state.debug(); _append( "new JSFunctionCalls" + fn.getParamCount() + "( scope , null ){ \n" , n ); String callLine = "public Object call( final Scope passedIn "; String varSetup = ""; for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); callLine += " , "; callLine += " Object " + foo; if ( ! state.useLocalVariable( foo ) ){ callLine += "INNNNN"; varSetup += " \nscope.put(\"" + foo + "\"," + foo + "INNNNN , true );\n "; if ( hasArguments ) varSetup += "arguments.add( " + foo + "INNNNN );\n"; } else { state.addSymbol( foo ); if ( hasArguments ) varSetup += "arguments.add( " + foo + " );\n"; } callLine += " "; } callLine += " , Object extra[] ){\n" ; _append( callLine + " final Scope scope = new Scope( \"temp scope for: \" + _name , _scope , passedIn ); " , n ); if ( hasArguments ){ _append( "JSArray arguments = new JSArray();\n" , n ); _append( "scope.put( \"arguments\" , arguments , true );\n" , n ); } _append( varSetup , n ); if ( hasArguments ) _append( "if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" , n ); for ( int i=fn.getParamCount(); i<fn.getParamAndVarCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); if ( state.useLocalVariable( foo ) ){ state.addSymbol( foo ); _append( "Object " + foo + " = null;\n" , n ); } else { _append( "scope.put( \"" + foo + "\" , null , true );\n" , n ); } } _addFunctionNodes( fn , state ); _add( n.getFirstChild() , state ); _append( "}\n" , n ); int myStringId = _strings.size(); _strings.add( getSource( fn ) ); _append( "\t public String toString(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "}\n" , n ); } private void _addBlock( Node n , State state ){ _assertType( n , Token.BLOCK ); if ( n.getFirstChild() == null ){ _append( "{}" , n ); return; } // this is weird. look at bracing0.js boolean bogusBrace = true; Node c = n.getFirstChild(); while ( c != null ){ if ( c.getType() != Token.EXPR_VOID ){ bogusBrace = false; break; } if ( c.getFirstChild().getNext() != null ){ bogusBrace = false; break; } if ( c.getFirstChild().getType() != Token.SETVAR ){ bogusBrace = false; break; } c = c.getNext(); } bogusBrace = bogusBrace || ( n.getFirstChild().getNext() == null && n.getFirstChild().getType() == Token.EXPR_VOID && n.getFirstChild().getFirstChild() == null ); if ( bogusBrace ){ c = n.getFirstChild(); while ( c != null ){ _add( c , state ); c = c.getNext(); } return; } _append( "{" , n ); Node child = n.getFirstChild(); while ( child != null ){ _add( child , state ); if ( child.getType() == Token.IFNE || child.getType() == Token.SWITCH ) break; child = child.getNext(); } _append( "}" , n ); } private void _addSet( Node n , State state ){ _assertType( n , Token.SETNAME ); Node name = n.getFirstChild(); _setVar( name.getString() , name.getNext() , state ); } private void _addVar( Node n , State state ){ _assertType( n , Token.VAR ); _assertOne( n ); Node name = n.getFirstChild(); _assertOne( name ); _setVar( name.getString() , name.getFirstChild() , state ); } private void _addCall( Node n , State state ){ _addCall( n , state , false ); } private void _addCall( Node n , State state , boolean isClass ){ Node name = n.getFirstChild(); boolean useThis = name.getType() == Token.GETPROP && ! isClass; if ( useThis ) _append( "scope.clearThisNormal( " , n ); Boolean inc[] = new Boolean[]{ true }; String f = getFunc( name , state , isClass , inc ); _append( ( inc[0] ? f : "" ) + ".call( scope" + ( isClass ? ".newThis( " + f + " )" : "" ) + " " , n ); Node param = name.getNext(); while ( param != null ){ _append( " , " , param ); _add( param , state ); param = param.getNext(); } _append( " ) " , n ); if ( useThis ) _append( " ) " , n ); } private void _setVar( String name , Node val , State state ){ _setVar( name , val , state , false ); } private void _setVar( String name , Node val , State state , boolean local ){ if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ){ _append( "JSInternalFunctions.self( " , val ); _append( name + " = " , val ); _add( val , state ); _append( "\n" , val ); _append( ")\n" , val ); return; } _append( "scope.put( \"" + name + "\" , " , val); _add( val , state ); _append( " , " + local + " ) " , val ); } private int countChildren( Node n ){ int num = 0; Node c = n.getFirstChild(); while ( c != null ){ num++; c = c.getNext(); } return num; } public static void _assertOne( Node n ){ if ( n.getFirstChild() == null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "no child" ); } if ( n.getFirstChild().getNext() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "more than 1 child" ); } } public static void _assertType( Node n , int type ){ if ( type != n.getType() ) throw new RuntimeException( "wrong type" ); } private void _setLineNumbers( Node n , final ScriptOrFnNode sof ){ final int line = n.getLineno(); if ( line < 0 ) throw new RuntimeException( "something is wrong" ); List<Node> todo = new LinkedList<Node>(); _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); while ( todo.size() > 0 ){ n = todo.remove(0); if ( n.getLineno() > 0 ){ _setLineNumbers( n , n instanceof ScriptOrFnNode ? (ScriptOrFnNode)n : sof ); continue; } _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); } } private void _append( String s , Node n ){ _mainJavaCode.append( s ); if ( n == null ) return; int numLines = 0; for ( int i=0; i<s.length(); i++ ) if ( s.charAt( i ) == '\n' ) numLines++; final int start = _currentLineNumber; final int end = _currentLineNumber + numLines; for ( int i=start; i<end; i++ ){ List<Node> l = _javaCodeToLines.get( i ); if ( l == null ){ l = new ArrayList<Node>(); _javaCodeToLines.put( i , l ); } l.add( n ); } _currentLineNumber = end; } private String getFunc( Node n , State state ){ return getFunc( n , state , false , null ); } private String getFunc( Node n , State state , boolean isClass , Boolean inc[] ){ if ( n.getClass().getName().indexOf( "StringNode" ) < 0 ){ if ( n.getType() == Token.GETPROP && ! isClass ){ _append( "scope.getFunctionAndSetThis( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( ".toString() ) " , n ); return ""; } int start = _mainJavaCode.length(); _append( "((JSFunction )" , n); _add( n , state ); _append( ")" , n ); int end = _mainJavaCode.length(); if( isClass ){ if ( inc == null ) throw new RuntimeException( "inc is null and can't be here" ); inc[0] = false; return "(" + _mainJavaCode.substring( start , end ) + ")"; } return ""; } String name = n.getString(); if ( name == null || name.length() == 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( id == -1 ) throw new RuntimeException( "no name or id for this thing" ); name = state._functionIdToName.get( id ); if ( name == null || name.length() == 0 ) throw new RuntimeException( "no name for this id " ); } if ( state.hasSymbol( name ) ) return "(( JSFunction)" + name + ")"; return "scope.getFunction( \"" + name + "\" )"; } public String getClassName(){ return _className; } String getClassString(){ StringBuilder buf = new StringBuilder(); buf.append( "package " + _package + ";\n" ); buf.append( "import ed.js.*;\n" ); buf.append( "import ed.js.func.*;\n" ); buf.append( "import ed.js.engine.Scope;\n" ); buf.append( "import ed.js.engine.JSCompiledScript;\n" ); buf.append( "public class " ).append( _className ).append( " extends JSCompiledScript {\n" ); buf.append( "\tpublic Object _call( Scope scope , Object extra[] ){\n" ); buf.append( "\t\t final Scope passedIn = scope; \n" ); buf.append( "\t\t scope = new Scope( \"compiled script for:" + _name.replaceAll( "/tmp/jxp/s?/?0\\.\\d+/" , "" ) + "\" , scope ); \n" ); buf.append( "\t\t JSArray arguments = new JSArray(); scope.put( \"arguments\" , arguments , true );\n " ); buf.append( "\t\t if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" ); _preMainLines = StringUtil.count( buf.toString() , "\n" ); buf.append( _mainJavaCode ); buf.append( "\n\n\t}\n\n" ); buf.append( "\n}\n\n" ); return buf.toString(); } public JSFunction get(){ if ( _it != null ) return _it; try { Class c = CompileUtil.compile( _package , getClassName() , getClassString() ); JSCompiledScript it = (JSCompiledScript)c.newInstance(); it._convert = this; it._regex = new JSRegex[ _regex.size() ]; for ( int i=0; i<_regex.size(); i++ ){ Pair<String,String> p = _regex.get( i ); JSRegex foo = new JSRegex( p.first , p.second ); it._regex[i] = foo; } it._strings = new JSString[ _strings.size() ]; for ( int i=0; i<_strings.size(); i++ ) it._strings[i] = new JSString( _strings.get( i ) ); it.setName( _name ); _it = it; return _it; } catch ( RuntimeException re ){ re.printStackTrace(); fixStack( re ); throw re; } catch ( Exception e ){ e.printStackTrace(); fixStack( e ); throw new RuntimeException( e ); } } public void fixStack( Throwable e ){ final boolean debug = false; boolean removeThings = false; StackTraceElement stack[] = e.getStackTrace(); boolean changed = false; for ( int i=0; i<stack.length; i++ ){ StackTraceElement element = stack[i]; if ( element == null ) continue; if ( debug ) System.out.println( element ); if ( element.toString().contains( ".call(JSFunctionCalls" ) || element.toString().contains( "ed.js.JSFunctionBase.call(" ) || element.toString().contains( "ed.js.engine.JSCompiledScript.call" ) ){ removeThings = true; changed = true; stack[i] = null; continue; } final String file = getClassName() + ".java"; String es = element.toString(); if ( ! es.contains( file ) ) continue; int line = StringParseUtil.parseInt( es.substring( es.lastIndexOf( ":" ) + 1 ) , -1 ); if ( debug ) System.out.println( "\t" + line ); line = ( line - _preMainLines ) - 1; if ( debug ) System.out.println( "\t" + line ); List<Node> nodes = _javaCodeToLines.get( line ); if ( nodes == null ) continue; // the +1 is for the way rhino stuff line = _nodeToSourceLine.get( nodes.get(0) ) + 1; ScriptOrFnNode sof = _nodeToSOR.get( nodes.get(0) ); String method = "___"; if ( sof instanceof FunctionNode ) method = ((FunctionNode)sof).getFunctionName(); if ( debug ) System.out.println( "\t\t" + line ); stack[i] = new StackTraceElement( _name , method , _name , line ); changed = true; } if ( removeThings ){ List<StackTraceElement> lst = new ArrayList<StackTraceElement>(); for ( StackTraceElement s : stack ){ if ( s == null ) continue; lst.add( s ); } stack = new StackTraceElement[lst.size()]; for ( int i=0; i<stack.length; i++ ) stack[i] = lst.get(i); } if ( changed ) e.setStackTrace( stack ); } String getSource( FunctionNode fn ){ final int start = fn.getEncodedSourceStart(); final int end = fn.getEncodedSourceEnd(); final String encoded = _encodedSource.substring( start , end ); final String realSource = Decompiler.decompile( encoded , 0 , new UintMap() ); return realSource; } private String getStringCode( String s ){ int stringId = _strings.size(); _strings.add( s ); return "_strings[" + stringId + "]"; } public boolean hasReturn(){ return _hasReturn; } //final File _file; final String _name; final String _source; final String _encodedSource; final String _className; final String _package = DEFAULT_PACKAGE; final int _id = ID++; // these 3 variables should only be use by _append private int _currentLineNumber = 0; final Map<Integer,List<Node>> _javaCodeToLines = new TreeMap<Integer,List<Node>>(); final Map<Node,Integer> _nodeToSourceLine = new HashMap<Node,Integer>(); final Map<Node,ScriptOrFnNode> _nodeToSOR = new HashMap<Node,ScriptOrFnNode>(); final List<Pair<String,String>> _regex = new ArrayList<Pair<String,String>>(); final List<String> _strings = new ArrayList<String>(); int _preMainLines = -1; private final StringBuilder _mainJavaCode = new StringBuilder(); private boolean _hasReturn = false; private JSFunction _it; private int _methodId = 0; private static int ID = 1; private final static Map<Integer,String> _2ThingThings = new HashMap<Integer,String>(); static { _2ThingThings.put( Token.ADD , "add" ); _2ThingThings.put( Token.MUL , "mul" ); _2ThingThings.put( Token.SUB , "sub" ); _2ThingThings.put( Token.DIV , "div" ); _2ThingThings.put( Token.SHEQ , "sheq" ); _2ThingThings.put( Token.SHNE , "shne" ); _2ThingThings.put( Token.EQ , "eq" ); _2ThingThings.put( Token.NE , "eq" ); _2ThingThings.put( Token.GE , "ge" ); _2ThingThings.put( Token.LE , "le" ); _2ThingThings.put( Token.LT , "lt" ); _2ThingThings.put( Token.GT , "gt" ); _2ThingThings.put( Token.BITOR , "bitor" ); _2ThingThings.put( Token.BITAND , "bitand" ); _2ThingThings.put( Token.BITXOR , "bitxor" ); _2ThingThings.put( Token.URSH , "ursh" ); _2ThingThings.put( Token.RSH , "rsh" ); _2ThingThings.put( Token.LSH , "lsh" ); _2ThingThings.put( Token.MOD , "mod" ); } private static final int _while1[] = new int[]{ Token.GOTO , Token.TARGET , 0 , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static final int _doWhile1[] = new int[]{ Token.TARGET , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static Node[] _matches( Node n , int types[] ){ Node foo[] = new Node[types.length]; for ( int i=0; i<types.length; i++ ){ foo[i] = n; if ( types[i] > 0 && n.getType() != types[i] ) return null; n = n.getNext(); } return n == null ? foo : null; } }
// Convert.java package ed.js.engine; import java.io.*; import java.util.*; import java.util.regex.*; import com.twmacinta.util.*; import ed.ext.org.mozilla.javascript.*; import ed.js.*; import ed.io.*; import ed.lang.*; import ed.util.*; public class Convert { static boolean DJS = Boolean.getBoolean( "DEBUG.JS" ); final boolean D; public static final String DEFAULT_PACKAGE = "ed.js.gen"; public static JSFunction makeAnon( String code ){ return makeAnon( code , false ); } public static JSFunction makeAnon( String code , boolean forceEval ){ try { final String nice = code.trim(); final String name = "anon" + Math.random(); if ( nice.startsWith( "function" ) && nice.endsWith( "}" ) ){ Convert c = new Convert( name , code , true ); JSFunction func = c.get(); Scope s = Scope.newGlobal().child(); s.setGlobal( true ); func.call( s ); String keyToUse = null; int numKeys = 0; for ( String key : s.keySet() ){ if ( key.equals( "arguments" ) ) continue; keyToUse = key; numKeys++; } if ( numKeys == 1 ){ Object val = s.get( keyToUse ); if ( val instanceof JSFunction ){ JSFunction f = (JSFunction)val; f.setUsePassedInScope( forceEval ); return f; } } } Convert c = new Convert( name , nice , forceEval ); return c.get(); } catch ( IOException ioe ){ throw new RuntimeException( "should be impossible" , ioe ); } } public Convert( File sourceFile ) throws IOException { this( sourceFile.getAbsolutePath() , StreamUtil.readFully( sourceFile , "UTF-8" ) ); } public Convert( String name , String source ) throws IOException { this(name, source, false); } public Convert( String name , String source, boolean invokedFromEval) throws IOException { this( name , source , invokedFromEval , Language.JS ); } public Convert( String name , String source, boolean invokedFromEval , Language sourceLanguage ) throws IOException { D = DJS && ! name.contains( "src/main/ed/lang" ) && ! name.contains( "src_main_ed_lang" ) ; _invokedFromEval = invokedFromEval; _sourceLanguage = sourceLanguage; _name = name; _source = source; _className = cleanName( _name ) + _getNumForClass( _name , _source ); _fullClassName = _package + "." + _className; _random = _random( _fullClassName ); _id = _random.nextInt(); _scriptInfo = new ScriptInfo( _name , _fullClassName , _sourceLanguage , this ); CompilerEnvirons ce = new CompilerEnvirons(); Parser p = new Parser( ce , ce.getErrorReporter() ); ScriptOrFnNode theNode = null; try { theNode = p.parse( _source , _name , 0 ); } catch ( ed.ext.org.mozilla.javascript.EvaluatorException ee ){ throw JSCompileException.create( ee ); } _encodedSource = p.getEncodedSource(); init( theNode ); } public static String cleanName( String name ){ StringBuilder buf = new StringBuilder( name.length() + 5 ); for ( int i=0; i<name.length(); i++ ){ final char c = name.charAt(i); if ( Character.isLetter( c ) || Character.isDigit( c ) ){ buf.append( c ); continue; } if ( buf.length() == 0 ) continue; buf.append( "_" ); } return buf.toString(); } private void init( ScriptOrFnNode sn ){ if ( _it != null ) throw new RuntimeException( "too late" ); NodeTransformer nf = new NodeTransformer(); nf.transform( sn ); if ( D ){ Debug.print( sn , 0 ); } State state = new State(); _setLineNumbers( sn , sn ); _addFunctionNodes( sn , state ); if ( D ) System.out.println( "***************" ); Node n = sn.getFirstChild(); String whyRasReturn = null; while ( n != null ){ if ( n.getType() != Token.FUNCTION ){ if ( n.getNext() == null ){ if ( n.getType() == Token.EXPR_RESULT ){ _append( "return " , n ); _hasReturn = true; whyRasReturn = "EXPR_RESULT"; } if ( n.getType() == Token.RETURN ){ _hasReturn = true; whyRasReturn = "RETURN"; } } _add( n , sn , state ); _append( "\n" , n ); } n = n.getNext(); } if ( ! _hasReturn ) { _append( "return null; /* null added at end */" , sn ); } else { _append( "/* no return b/c : " + whyRasReturn + " */" , sn ); int end = _mainJavaCode.length() - 1; boolean alreadyHaveOne = false; for ( ; end >= 0; end char c = _mainJavaCode.charAt( end ); if ( Character.isWhitespace( c ) ) continue; if ( c == ';' ){ if ( ! alreadyHaveOne ){ alreadyHaveOne = true; continue; } _mainJavaCode.setLength( end + 1 ); } break; } } } private void _add( Node n , State state ){ _add( n , null , state ); } private void _add( Node n , ScriptOrFnNode sn , State state ){ switch ( n.getType() ){ case Token.TYPEOF: _append( "JS_typeof( " , n ); _assertOne( n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.TYPEOFNAME: _append( "JS_typeof( " , n ); if ( state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); _append( " ) " , n ); break; case Token.REGEXP: int myId = _regex.size(); ScriptOrFnNode parent = _nodeToSOR.get( n ); if ( parent == null ) throw new RuntimeException( "how is parent null" ); int rId = n.getIntProp( Node.REGEXP_PROP , -1 ); _regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) ); _append( " _regex(" + myId + ") " , n ); break; case Token.ARRAYLIT: { _append( "( JSArray.create( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) ) " , n ); } break; case Token.OBJECTLIT: { _append( "JS_buildLiteralObject( new String[]{ " , n ); boolean first = true; Node c = n.getFirstChild(); for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){ if ( first ) first = false; else _append( " , " , n ); String name = id.toString(); if ( c.getType() == Token.GET ) name = JSObjectBase.getterName( name ); else if ( c.getType() == Token.SET ) name = JSObjectBase.setterName( name ); _append( getStringCode( name ) + ".toString()" , n ); c = c.getNext(); } _append( " } " , n ); c = n.getFirstChild(); while ( c != null ){ _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) " , n ); } break; case Token.NEW: _append( "scope.clearThisNew( " , n ); _addCall( n , state , true ); _append( " ) " , n ); break; case Token.THIS: _append( "passedIn.getThis()" , n ); break; case Token.INC: case Token.DEC: _assertOne( n ); Node tempChild = n.getFirstChild(); if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){ if ( ! state.isNumber( tempChild.getString() ) ) throw new RuntimeException( "can't increment local variable : " + tempChild.getString() ); _append( tempChild.getString() + "++ " , n ); } else { _append( "JS_inc( " , n ); _createRef( n.getFirstChild() , state ); _append( " , " , n ); _append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n ); _append( " , " , n ); _append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n ); _append( ")" , n ); } break; case Token.USE_STACK: _append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n ); break; case Token.SETPROP_OP: case Token.SETELEM_OP: Node theOp = n.getFirstChild().getNext().getNext(); if ( ( theOp.getType() == Token.ADD || theOp.getType() == Token.SUB || theOp.getType() == Token.MUL || theOp.getType() == Token.DIV ) && ( theOp.getFirstChild().getType() == Token.USE_STACK || theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){ _append( "\n" , n ); _append( "JS_setDefferedOp( (JSObject) " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( theOp.getFirstChild().getType() == Token.USE_STACK ? theOp.getFirstChild().getNext() : theOp.getFirstChild() , state ); _append( " , " + theOp.getType() , n ); _append( " \n ) \n" , n ); break; } _append( "\n { \n" , n ); _append( "JSObject __tempObject = (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); String tempName = "__temp" + _rand(); state._tempOpNames.push( tempName ); _append( "Object " + tempName + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( ";\n" , n ); _append( " __tempObject.set(" , n ); _append( tempName , n ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ); \n" , n ); _append( " } \n" , n ); break; case Token.SETPROP: case Token.SETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".set( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) " , n ); break; case Token.GETPROPNOWARN: case Token.GETPROP: case Token.GETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.SET_REF: Node fc = n.getFirstChild(); if( fc.getType() != Token.REF_SPECIAL && fc.getType() != Token.REF_MEMBER ) throw new RuntimeException( "token is of type "+Token.name(fc.getType())+", should be of type REF_SPECIAL or REF_MEMBER."); _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".set( " , n ); _add( fc , state ); _append( " , " , n ); _add( fc.getNext() , state ); _append( " )" , n ); break; case Token.GET_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.REF_SPECIAL : _append( "\"" + n.getProp( Node.NAME_PROP ).toString() + "\"" , n ); break; case Token.REF_MEMBER : _append( "\"" , n ); final int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ( ( memberTypeFlags & Node.DESCENDANTS_FLAG ) != 0 ) _append( ".." , n ); if ( ( memberTypeFlags & Node.ATTRIBUTE_FLAG ) != 0 ) _append( "@" , n ); _append( n.getFirstChild().getNext().getString() , n ); _append( "\"" , n ); break; case Token.REF_NS_MEMBER : if( ( n.getIntProp(Node.MEMBER_TYPE_PROP,0) & Node.ATTRIBUTE_FLAG ) != 0 ) { _append( "\"@\" + " , n ); } _add( n.getFirstChild().getNext() , state ); _append( " + \"::\" + ", n ); _add( n.getFirstChild().getNext().getNext() , state ); break; case Token.REF_NAME : case Token.ESCXMLTEXT : case Token.ESCXMLATTR : _add( n.getFirstChild(), state ); break; case Token.EXPR_RESULT: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.CALL: _addCall( n , state ); break; case Token.NUMBER: double d = n.getDouble(); String temp = String.valueOf( d ); if ( temp.endsWith( ".0" ) || JSNumericFunctions.couldBeInt( d ) ) temp = String.valueOf( (int)d ); _append( "JSNumber.self( " + temp + ")" , n ); break; case Token.STRING: final String theString = n.getString(); _append( getStringCode( theString ) , n ); break; case Token.TRUE: _append( " true " , n ); break; case Token.FALSE: _append( " false " , n ); break; case Token.NULL: _append( " null " , n ); break; case Token.VAR: _addVar( n , state ); break; case Token.GETVAR: if ( state.useLocalVariable( n.getString() ) ){ _append( n.getString() , n ); break; } case Token.NAME: if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); break; case Token.SETVAR: final String foo = n.getFirstChild().getString(); if ( state.useLocalVariable( foo ) ){ if ( ! state.hasSymbol( foo ) ) throw new RuntimeException( "something is wrong" ); if ( ! state.isPrimitive( foo ) ) _append( "JSInternalFunctions.self ( " , n ); _append( foo + " = " , n ); _add( n.getFirstChild().getNext() , state ); if ( ! state.isPrimitive( foo ) ) _append( " )\n" , n ); } else { _setVar( foo , n.getFirstChild().getNext() , state , true ); } break; case Token.SETNAME: _addSet( n , state ); break; case Token.GET: _addFunction( n.getFirstChild() , state ); break; case Token.SET: _addFunction( n.getFirstChild() , state ); break; case Token.FUNCTION: _addFunction( n , state ); break; case Token.BLOCK: _addBlock( n , state ); break; case Token.EXPR_VOID: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.RETURN: boolean last = n.getNext() == null; if ( ! last ) _append( "if ( true ) { " , n ); _append( "return " , n ); if ( n.getFirstChild() != null ){ _assertOne( n ); _add( n.getFirstChild() , state ); } else { _append( " null " , n ); } _append( "; /* explicit return */" , n ); if ( ! last ) _append( "}" , n ); _append( "\n" , n ); break; case Token.BITNOT: _assertOne( n ); _append( "JS_bitnot( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.HOOK: _append( " JSInternalFunctions.self( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ? ( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) : ( " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) ) " , n ); break; case Token.POS: _assertOne( n ); _add( n.getFirstChild() , state ); break; case Token.ADD: if ( state.isNumberAndLocal( n.getFirstChild() ) && state.isNumberAndLocal( n.getFirstChild().getNext() ) ){ _append( "(" , n ); _add( n.getFirstChild() , state ); _append( " + " , n ); _add( n.getFirstChild().getNext() , state ); _append( ")" , n ); break; } case Token.NE: case Token.MUL: case Token.DIV: case Token.SUB: case Token.EQ: case Token.SHEQ: case Token.SHNE: case Token.GE: case Token.LE: case Token.LT: case Token.GT: case Token.BITOR: case Token.BITAND: case Token.BITXOR: case Token.URSH: case Token.RSH: case Token.LSH: case Token.MOD: if ( n.getType() == Token.NE ) _append( " ! " , n ); _append( "JS_" , n ); String fooooo = _2ThingThings.get( n.getType() ); if ( fooooo == null ) throw new RuntimeException( "noting for : " + n ); _append( fooooo , n ); _append( "\n( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n " , n ); break; case Token.IFNE: _addIFNE( n , state ); break; case Token.LOOP: _addLoop( n , state ); break; case Token.EMPTY: if ( n.getFirstChild() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "not really empty" ); } break; case Token.LABEL: _append( n.getString() + ":" , n ); break; case Token.BREAK: _append( "break " + n.getString() + ";\n" , n ); break; case Token.CONTINUE: _append( "if ( true ) continue " + n.getString() + ";\n" , n ); break; case Token.WHILE: _append( "while( false || JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){ " , n ); _add( n.getFirstChild().getNext() , state ); _append( " }\n" , n ); break; case Token.FOR: _addFor( n , state ); break; case Token.TARGET: break; case Token.NOT: _assertOne( n ); _append( " JS_not( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.AND: /* _append( " ( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " && " , n ); _append( " JS_evalToBool( " , n ); _add( c , state ); _append( " ) " , n ); c = c.getNext(); } _append( " ) " , n ); break; */ case Token.OR: Node cc = n.getFirstChild(); if ( cc.getNext() == null ) throw new RuntimeException( "what?" ); if ( cc.getNext().getNext() != null ) throw new RuntimeException( "what?" ); String mod = n.getType() == Token.AND ? "and" : "or"; _append( "JSInternalFunctions.self( scope." + mod + "Save( " , n ); _add( cc , state ); _append( " ) ? scope.get" + mod + "Save() : ( " , n ); _add( cc.getNext() , state ); _append( " ) ) " , n ); break; case Token.LOCAL_BLOCK: _assertOne( n ); if ( n.getFirstChild().getType() != Token.TRY ) throw new RuntimeException("only know about LOCAL_BLOCK with try" ); _addTry( n.getFirstChild() , state ); break; case Token.JSR: case Token.RETURN_RESULT: // these are handled in block break; case Token.THROW: _append( "if ( true ) _throw( " , n ); _add( n.getFirstChild() , state ); _append( " ); " , n ); break; case Token.INSTANCEOF: _append( "JS_instanceof( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); if ( n.getFirstChild().getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); break; case Token.DELPROP: _addAsJSObject( n.getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); break; case Token.DEL_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.SWITCH: _addSwitch( n , state ); break; case Token.COMMA: _append( "JS_comma( " , n ); boolean first = true; Node inner = n.getFirstChild(); while ( inner != null ){ if ( first ) first = false; else _append( " , " , n ); _append( "\n ( " , n ); _add( inner , state ); _append( " )\n " , n ); inner = inner.getNext(); } _append( " ) " , n ); break; case Token.IN: _addAsJSObject( n.getFirstChild().getNext() , state ); _append( ".containsKey( " , n ); _add( n.getFirstChild() , state ); _append( ".toString() ) " , n ); break; case Token.NEG: _append( "JS_mul( -1 , " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.ENTERWITH: _append( "scope.enterWith( (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " );" , n ); break; case Token.LEAVEWITH: _append( "scope.leaveWith();" , n ); break; case Token.WITH: _add( n.getFirstChild() , state ); break; case Token.DOTQUERY: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( new ed.js.e4x.Query( " , n ); Node n2 = n.getFirstChild().getNext(); switch( n2.getFirstChild().getType() ) { case Token.GET_REF : _append( "\"@\" + " , n ); _add( n2.getFirstChild().getFirstChild() , state ); break; case Token.NAME : _append( "\"" + n2.getFirstChild().getString() + "\"" , n ); break; } _append( " , " , n ); _add( n2.getFirstChild().getNext() , state ); _append( " + \"\" , " , n ); String comp = Token.name( n2.getType() ); _append( "\"" + comp + "\" ) ) " , n ); break; case Token.DEFAULTNAMESPACE : _append( "((ed.js.e4x.ENode.Cons)scope.get( \"XML\")).setAndGetDefaultNamespace( ", n ); _add( n.getFirstChild(), state ); _append(")", n ); break; default: Debug.printTree( n , 0 ); throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() ); } } private void _addAsJSObject( Node n , State state ){ if ( n.getType() == Token.NUMBER ){ _append( "(new JSNumber( " + n.getDouble() + "))" , n ); return; } _append( "((JSObject)" , n ); _add( n , state ); _append( ")" , n ); } private void _addDotQuery( Node n , State state ){ _append( "(new ed.js.e4x.E4X.Query(" , n ); String s = Token.name( n.getType() ); { Node t = n.getFirstChild(); switch ( t.getType() ){ case Token.GET_REF: _append( "\"@\" + " , n ); _add( t.getFirstChild().getFirstChild() , state ); break; default: throw new RuntimeException( "don't know how to handle " + Token.name( t.getType() ) + " in a DOTQUERY" ); } } _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( "))" , n ); } private void _addSwitch( Node n , State state ){ _assertType( n , Token.SWITCH ); String ft = "ft" + _rand(); String val = "val" + _rand(); _append( "boolean " + ft + " = false;\n" , n ); _append( "do { \n " , n ); _append( " if ( false ) break; \n" , n ); Node caseArea = n.getFirstChild(); _append( "Object " + val + " = " , n ); _add( caseArea , state ); _append( " ; \n " , n ); n = n.getNext(); _assertType( n , Token.GOTO ); // this is default ? n = n.getNext().getNext(); caseArea = caseArea.getNext(); while ( caseArea != null ){ _append( "if ( " + ft + " || JS_eq( " + val + " , " , caseArea ); _add( caseArea.getFirstChild() , state ); _append( " ) ){\n " + ft + " = true; \n " , caseArea ); _assertType( n , Token.BLOCK ); _add( n , state ); n = n.getNext().getNext(); _append( " } \n " , caseArea ); caseArea = caseArea.getNext(); } if ( n != null && n.getType() == Token.BLOCK ){ _add( n , state ); } _append(" } while ( false );" , n ); } private void _createRef( Node n , State state ){ if ( n.getType() == Token.NAME || n.getType() == Token.GETVAR ){ if ( state.useLocalVariable( n.getString() ) ) throw new RuntimeException( "can't create a JSRef from a local variable : " + n.getString() ); _append( " new JSRef( scope , null , " , n ); _append( "\"" + n.getString() + "\"" , n ); _append( " ) " , n ); return; } if ( n.getType() == Token.GETPROP || n.getType() == Token.GETELEM ){ _append( " new JSRef( scope , (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); return; } throw new RuntimeException( "can't handle" ); } private void _addTry( Node n , State state ){ _assertType( n , Token.TRY ); Node mainBlock = n.getFirstChild(); _assertType( mainBlock , Token.BLOCK ); _append( "try { \n " , n ); _add( mainBlock , state ); _append( " \n } \n " , n ); n = mainBlock.getNext(); final String num = _rand(); final String javaEName = "javaEEE" + num; final String javaName = "javaEEEO" + num; while ( n != null ){ if ( n.getType() == Token.FINALLY ){ _assertType( n.getFirstChild() , Token.BLOCK ); _append( "finally { \n" , n ); _add( n.getFirstChild() , state ); _append( " \n } \n " , n ); n = n.getNext(); continue; } if ( n.getType() == Token.LOCAL_BLOCK && n.getFirstChild().getType() == Token.CATCH_SCOPE ){ _append( " \n catch ( Exception " + javaEName + " ){ \n " , n ); _append( " \n Object " + javaName + " = ( " + javaEName + " instanceof JSException ) ? " + " ((JSException)" + javaEName + ").getObject() : " + javaEName + " ; \n" , n ); _append( "try { scope.pushException( " + javaEName + " ); \n" , n ); Node catchScope = n.getFirstChild(); while ( catchScope != null ){ final Node c = catchScope; if ( c.getType() != Token.CATCH_SCOPE ) break; Node b = c.getNext(); _assertType( b , Token.BLOCK ); _assertType( b.getFirstChild() , Token.ENTERWITH ); _assertType( b.getFirstChild().getNext() , Token.WITH ); b = b.getFirstChild().getNext().getFirstChild(); _assertType( b , Token.BLOCK ); String jsName = c.getFirstChild().getString(); _append( " scope.put( \"" + jsName + "\" , " + javaName + " , true ); " , c ); b = b.getFirstChild(); boolean isIF = b.getType() == Token.IFNE; if ( isIF ){ _append( "\n if ( " + javaEName + " != null && JS_evalToBool( " , b ); _add( b.getFirstChild() , state ); _append( " ) ){ \n " , b ); b = b.getNext().getFirstChild(); } while ( b != null ){ if ( b.getType() == Token.LEAVEWITH ) break; _add( b , state ); b = b.getNext(); } _append( "if ( true ) " + javaEName + " = null ;\n" , b ); if ( isIF ){ _append( "\n } \n " , b ); } catchScope = catchScope.getNext().getNext(); } _append( "if ( " + javaEName + " != null ){ if ( " + javaEName + " instanceof RuntimeException ){ throw (RuntimeException)" + javaEName + ";} throw new JSException( " + javaEName + ");}\n" , n ); _append( " } finally { scope.popException(); } " , n ); _append( "\n } \n " , n ); // ends catch n = n.getNext(); continue; } if ( n.getType() == Token.GOTO || n.getType() == Token.TARGET || n.getType() == Token.JSR ){ n = n.getNext(); continue; } if ( n.getType() == Token.RETHROW ){ //_append( "\nthrow " + javaEName + ";\n" , n ); n = n.getNext(); continue; } throw new RuntimeException( "what : " + Token.name( n.getType() ) ); } } private void _addFor( Node n , State state ){ _assertType( n , Token.FOR ); final int numChildren = countChildren( n ); if ( numChildren == 4 ){ _append( "\n for ( " , n ); if ( n.getFirstChild().getType() == Token.BLOCK ){ Node temp = n.getFirstChild().getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.EXPR_VOID ) _add( temp.getFirstChild() , state ); else _add( temp , state ); temp = temp.getNext(); if ( temp != null ) _append( " , " , n ); } _append( " ; " , n ); } else { _add( n.getFirstChild() , state ); _append( " ; " , n ); } _append( " \n JS_evalToBool( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ; \n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " )\n " , n ); _append( " { \n " , n ); _add( n.getFirstChild().getNext().getNext().getNext() , state ); _append( " } \n " , n ); } else if ( numChildren == 3 ){ String name = n.getFirstChild().getString(); String tempName = name + "TEMP"; if( n.getFirstChild().getFirstChild() != null && n.getFirstChild().getFirstChild().getType() == Token.ENUM_INIT_VALUES ) { _append( "\n for ( Object " , n ); _append( tempName , n ); _append( " : JSInternalFunctions.JS_collForForEach( ", n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ){\n " , n ); if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ) _append( name + " = " + tempName + "; " , n ); else _append( "scope.put( \"" + name + "\" , " + tempName + " , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } else { _append( "\n for ( String " , n ); _append( tempName , n ); _append( " : JSInternalFunctions.JS_collForFor( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ){\n " , n ); if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ) _append( name + " = new JSString( " + tempName + ") ; " , n ); else _append( "scope.put( \"" + name + "\" , new JSString( " + tempName + " ) , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } } else { throw new RuntimeException( "wtf?" ); } } private void _addLoop( Node n , State state ){ _assertType( n , Token.LOOP ); final Node theLoop = n; n = n.getFirstChild(); Node nodes[] = null; if ( ( nodes = _matches( n , _while1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[5]; _append( "while ( JS_evalToBool( " , theLoop ); _add( predicate.getFirstChild() , state ); _append( " ) ) " , theLoop ); _add( main , state ); } else if ( ( nodes = _matches( n , _doWhile1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[3]; _assertType( predicate , Token.IFEQ ); _append( "do { \n " , theLoop ); _add( main , state ); _append( " } \n while ( false || JS_evalToBool( " , n ); _add( predicate.getFirstChild() , state ); _append( " ) );\n " , n ); } else { throw new RuntimeException( "what?" ); } } private void _addIFNE( Node n , State state ){ _assertType( n , Token.IFNE ); final Node.Jump theIf = (Node.Jump)n; _assertOne( n ); // this is the predicate Node ifBlock = n.getNext(); _append( "if ( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){\n" , n ); _add( ifBlock , state ); _append( "}\n" , n ); n = n.getNext().getNext(); if ( n.getType() == Token.TARGET ){ if ( n.getNext() != null ) throw new RuntimeException( "something is wrong" ); return; } _assertType( n , Token.GOTO ); _assertType( n.getNext() , Token.TARGET ); if ( theIf.target.hashCode() != n.getNext().hashCode() ) throw new RuntimeException( "hashes don't match" ); n = n.getNext().getNext(); _append( " else if ( true ) { " , n ); _add( n , state ); _append( " } \n" , n ); _assertType( n.getNext() , Token.TARGET ); if ( n.getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); } private void _addFunctionNodes( final ScriptOrFnNode sn , final State state ){ Set<Integer> baseIds = new HashSet<Integer>(); { Node temp = sn.getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.FUNCTION && temp.getString() != null ){ int prop = temp.getIntProp( Node.FUNCTION_PROP , -1 ); if ( prop >= 0 ){ baseIds.add( prop ); } } temp = temp.getNext(); } } for ( int i=0; i<sn.getFunctionCount(); i++ ){ FunctionNode fn = sn.getFunctionNode( i ); _setLineNumbers( fn , fn ); String name = fn.getFunctionName(); String anonName = "tempFunc_" + _id + "_" + i + "_" + _methodId++; boolean anon = name.length() == 0; if ( anon ) name = anonName; if ( D ){ System.out.println( "***************" ); System.out.println( i + " : " + name ); } String useName = name; if ( ! anon && ! baseIds.contains( i ) ){ useName = anonName; state._nonRootFunctions.add( i ); } state._functionIdToName.put( i , useName ); _setVar( useName , fn , state , anon ); _append( "; \n scope.getFunction( \"" + useName + "\" ).setName( \"" + name + "\" );\n\n" , fn ); } } private void _addFunction( Node n , State state ){ if ( ! ( n instanceof FunctionNode ) ){ if ( n.getString() != null && n.getString().length() != 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( state._nonRootFunctions.contains( id ) ){ _append( "scope.set( \"" + n.getString() + "\" , scope.get( \"" + state._functionIdToName.get( id ) + "\" ) );\n" , n ); } return; } _append( getFunc( n , state ) , n ); return; } _assertOne( n ); FunctionNode fn = (FunctionNode)n; FunctionInfo fi = FunctionInfo.create( fn ); state = state.child(); state._fi = fi; boolean hasArguments = fi.usesArguemnts(); _append( "new JSFunctionCalls" + fn.getParamCount() + "( scope , null ){ \n" , n ); _append( "protected void init(){ super.init(); _sourceLanguage = getFileLanguage(); \n " , n ); _append( "_arguments = new JSArray();\n" , n ); for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); _append( "_arguments.add( \"" + foo + "\" );\n" , n ); } _append( "_globals = new JSArray();\n" , n ); for ( String g : fi._globals ) _append( "_globals.add( \"" + g + "\" );\n" , n ); _append( "}\n" , n ); String callLine = "public Object call( final Scope passedIn "; String varSetup = ""; for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); callLine += " , "; callLine += " Object " + foo; if ( ! state.useLocalVariable( foo ) ){ callLine += "INNNNN"; varSetup += " \nscope.put(\"" + foo + "\"," + foo + "INNNNN , true );\n "; if ( hasArguments ) varSetup += "arguments.add( " + foo + "INNNNN );\n"; } else { state.addSymbol( foo ); if ( hasArguments ) varSetup += "arguments.add( " + foo + " );\n"; } callLine += " "; } callLine += " , Object ___extra[] ){\n" ; _append( callLine + " final Scope scope = usePassedInScope() ? passedIn : new Scope( \"func scope\" , getScope() , passedIn , getFileLanguage() ); " , n ); if ( hasArguments ){ _append( "JSArray arguments = new JSArray();\n" , n ); _append( "scope.put( \"arguments\" , arguments , true );\n" , n ); } for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); final String javaName = foo + ( state.useLocalVariable( foo ) ? "" : "INNNNN" ); final Node defArg = fn.getDefault( foo ); if ( defArg == null ) continue; _append( "if ( null == " + javaName + " ) " , defArg ); _append( javaName + " = " , defArg ); _add( defArg , state ); _append( ";\n" , defArg ); } _append( varSetup , n ); if ( hasArguments ){ _append( "if ( ___extra != null ) for ( Object TTTT : ___extra ) arguments.add( TTTT );\n" , n ); _append( "{ Integer numArgs = _lastStart.get(); _lastStart.set( null ); while( numArgs != null && arguments.size() > numArgs && arguments.get( arguments.size() -1 ) == null ) arguments.remove( arguments.size() - 1 ); }" , n ); } for ( int i=fn.getParamCount(); i<fn.getParamAndVarCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); if ( state.useLocalVariable( foo ) ){ state.addSymbol( foo ); if ( state.isNumber( foo ) ){ _append( "double " + foo + " = 0;\n" , n ); } else _append( "Object " + foo + " = null;\n" , n ); } else { _append( "scope.put( \"" + foo + "\" , null , true );\n" , n ); } } _addFunctionNodes( fn , state ); _add( n.getFirstChild() , fn , state ); _append( "}\n" , n ); int myStringId = _strings.size(); _strings.add( getSource( fn ) ); _append( "\t public String getSourceCode(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "\t public String toString(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "}\n" , n ); } private void _addBlock( Node n , State state ){ _assertType( n , Token.BLOCK ); if ( n.getFirstChild() == null ){ _append( "{}" , n ); return; } // this is weird. look at bracing0.js boolean bogusBrace = true; Node c = n.getFirstChild(); while ( c != null ){ if ( c.getType() != Token.EXPR_VOID ){ bogusBrace = false; break; } if ( c.getFirstChild().getNext() != null ){ bogusBrace = false; break; } if ( c.getFirstChild().getType() != Token.SETVAR ){ bogusBrace = false; break; } c = c.getNext(); } bogusBrace = bogusBrace || ( n.getFirstChild().getNext() == null && n.getFirstChild().getType() == Token.EXPR_VOID && n.getFirstChild().getFirstChild() == null ); if ( bogusBrace ){ c = n.getFirstChild(); while ( c != null ){ _add( c , state ); c = c.getNext(); } return; } boolean endReturn = n.getLastChild() != null && n.getLastChild().getType() == Token.RETURN_RESULT; _append( "{" , n ); String ret = "retName" + _rand(); if ( endReturn ) _append( "\n\nObject " + ret + " = null;\n\n" , n ); Node child = n.getFirstChild(); while ( child != null ){ if ( endReturn && child.getType() == Token.LEAVEWITH ) break; if ( endReturn && child.getType() == Token.EXPR_RESULT ) _append( ret + " = " , child ); _add( child , state ); if ( child.getType() == Token.IFNE || child.getType() == Token.SWITCH ) break; child = child.getNext(); } if ( endReturn ) _append( "\n\nif ( true ){ return " + ret + "; }\n\n" , n ); _append( "}" , n ); } private void _addSet( Node n , State state ){ _assertType( n , Token.SETNAME ); Node name = n.getFirstChild(); _setVar( name.getString() , name.getNext() , state ); } private void _addVar( Node n , State state ){ _assertType( n , Token.VAR ); _assertOne( n ); Node name = n.getFirstChild(); _assertOne( name ); _setVar( name.getString() , name.getFirstChild() , state ); } private void _addCall( Node n , State state ){ _addCall( n , state , false ); } private void _addCall( Node n , State state , boolean isClass ){ Node name = n.getFirstChild(); boolean useThis = name.getType() == Token.GETPROP && ! isClass; if ( useThis ) _append( "scope.clearThisNormal( " , n ); Boolean inc[] = new Boolean[]{ true }; String f = getFunc( name , state , isClass , inc ); _append( ( inc[0] ? f : "" ) + ".call( scope" + ( isClass ? ".newThis( " + f + " )" : "" ) + " " , n ); Node param = name.getNext(); while ( param != null ){ _append( " , " , param ); _add( param , state ); param = param.getNext(); } _append( " , new Object[0] ) " , n ); if ( useThis ) _append( " ) " , n ); } private void _setVar( String name , Node val , State state ){ _setVar( name , val , state , false ); } private void _setVar( String name , Node val , State state , boolean local ){ if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ){ boolean prim = state.isPrimitive( name ); if ( ! prim ) _append( "JSInternalFunctions.self( " , val ); _append( name + " = " , val ); _add( val , state ); _append( "\n" , val ); if ( ! prim ) _append( ")\n" , val ); return; } _append( "scope.put( \"" + name + "\" , " , val); _add( val , state ); _append( " , " + local + " ) " , val ); } static int countChildren( Node n ){ int num = 0; Node c = n.getFirstChild(); while ( c != null ){ num++; c = c.getNext(); } return num; } public static void _assertOne( Node n ){ if ( n.getFirstChild() == null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "no child" ); } if ( n.getFirstChild().getNext() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "more than 1 child" ); } } public void _assertType( Node n , int type ){ _assertType( n , type , this ); } public static void _assertType( Node n , int type , Convert c ){ if ( type == n.getType() ) return; String msg = "wrong type. was : " + Token.name( n.getType() ) + " should be " + Token.name( type ); if ( c != null ) msg += " file : " + c._name + " : " + ( c._nodeToSourceLine.get( n ) + 1 ); throw new RuntimeException( msg ); } private void _setLineNumbers( final Node startN , final ScriptOrFnNode startSOF ){ final Set<Integer> seen = new HashSet<Integer>(); final List<Pair<Node,ScriptOrFnNode>> overallTODO = new LinkedList<Pair<Node,ScriptOrFnNode>>(); overallTODO.add( new Pair<Node,ScriptOrFnNode>( startN , startSOF ) ); while ( overallTODO.size() > 0 ){ final Pair<Node,ScriptOrFnNode> temp = overallTODO.remove( 0 ); Node n = temp.first; final ScriptOrFnNode sof = temp.second; final int line = n.getLineno(); if ( line < 0 ) throw new RuntimeException( "something is wrong" ); List<Node> todo = new LinkedList<Node>(); _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); while ( todo.size() > 0 ){ n = todo.remove(0); if ( seen.contains( n.hashCode() ) ) continue; seen.add( n.hashCode() ); if ( n.getLineno() > 0 ){ overallTODO.add( new Pair<Node,ScriptOrFnNode>( n , n instanceof ScriptOrFnNode ? (ScriptOrFnNode)n : sof ) ); continue; } _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); } } } private void _append( String s , Node n ){ _mainJavaCode.append( s ); if ( n == null ) return; int numLines = 0; int max = s.length(); for ( int i=0; i<max; i++ ) if ( s.charAt( i ) == '\n' ) numLines++; final int start = _currentLineNumber; int end = _currentLineNumber + numLines; for ( int i=start; i<end; i++ ){ List<Node> l = _javaCodeToLines.get( i ); if ( l == null ){ l = new ArrayList<Node>(); _javaCodeToLines.put( i , l ); } l.add( n ); } _currentLineNumber = end; } private String getFunc( Node n , State state ){ return getFunc( n , state , false , null ); } private String getFunc( Node n , State state , boolean isClass , Boolean inc[] ){ if ( n.getClass().getName().indexOf( "StringNode" ) < 0 ){ if ( n.getType() == Token.GETPROP && ! isClass ){ _append( "scope.getFunctionAndSetThis( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( ".toString() ) " , n ); return ""; } int start = _mainJavaCode.length(); _append( "((JSFunction )" , n); _add( n , state ); _append( ")" , n ); int end = _mainJavaCode.length(); if( isClass ){ if ( inc == null ) throw new RuntimeException( "inc is null and can't be here" ); inc[0] = false; return "(" + _mainJavaCode.substring( start , end ) + ")"; } return ""; } String name = n.getString(); if ( name == null || name.length() == 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( id == -1 ) throw new RuntimeException( "no name or id for this thing" ); name = state._functionIdToName.get( id ); if ( name == null || name.length() == 0 ) throw new RuntimeException( "no name for this id " ); } if ( state.hasSymbol( name ) ) return "(( JSFunction)" + name + ")"; return "scope.getFunction( \"" + name + "\" )"; } public String getClassName(){ return _className; } public String getClassString(){ StringBuilder buf = new StringBuilder(); buf.append( "package " + _package + ";\n" ); buf.append( "import ed.js.*;\n" ); buf.append( "import ed.js.func.*;\n" ); buf.append( "import ed.js.engine.Scope;\n" ); buf.append( "import ed.js.engine.JSCompiledScript;\n" ); buf.append( "public class " ).append( _className ).append( " extends JSCompiledScript {\n" ); buf.append( "\tpublic Object _call( Scope scope , Object extra[] ) throws Exception {\n" ); buf.append( "\t\t final Scope passedIn = scope; \n" ); if (_invokedFromEval) { buf.append("\t\t // not creating new scope for execution as we're being run in the context of an eval\n"); } else { String cleanName = FileUtil.clean( _name ); buf.append( "\t\t if ( ! usePassedInScope() ){\n" ); buf.append( "\t\t\t scope = new Scope( \"compiled script for:" + cleanName + "\" , scope , null , getFileLanguage() ); \n" ); buf.append( "\t\t }\n" ); buf.append( "\t\t scope.putAll( getTLScope() );\n" ); } buf.append( "\t\t JSArray arguments = new JSArray(); scope.put( \"arguments\" , arguments , true );\n " ); buf.append( "\t\t if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" ); _preMainLines = StringUtil.count( buf.toString() , "\n" ); buf.append( _mainJavaCode ); buf.append( "\n\n\t}\n\n" ); buf.append( "\n}\n\n" ); return buf.toString(); } public JSFunction get(){ if ( _it != null ) return _it; try { Class c = CompileUtil.compile( _package , getClassName() , getClassString() , this ); JSCompiledScript it = (JSCompiledScript)c.newInstance(); _scriptInfo.setup( this ); it._scriptInfo = _scriptInfo; it._regex = _regex; it._strings = new String[ _strings.size() ]; for ( int i=0; i<_strings.size(); i++ ) it._strings[i] = _strings.get( i ); it.setName( _name ); _it = it; StackTraceHolder.getInstance().set( _fullClassName , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js" , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js.func" , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js.engine" , _scriptInfo ); return _it; } catch ( RuntimeException re ){ re.printStackTrace(); fixStack( re ); throw re; } catch ( Exception e ){ e.printStackTrace(); fixStack( e ); throw new RuntimeException( e ); } } public void fixStack( Throwable e ){ StackTraceHolder.getInstance().fix( e ); } Node _getNodeFromJavaLine( int line ){ line = ( line - _preMainLines ) - 1; List<Node> nodes = _javaCodeToLines.get( line ); if ( nodes == null || nodes.size() == 0 ){ return null; } return nodes.get(0); } public int _mapLineNumber( int line ){ Node n = _getNodeFromJavaLine( line ); if ( n == null ) return -1; Integer i = _nodeToSourceLine.get( n ); if ( i == null ) return -1; return i + 1; } public void _debugLineNumber( final int line ){ System.out.println( " for ( int temp = Math.max( 0 , line - 5 ); temp < line + 5 ; temp++ ) System.out.println( "\t" + temp + "->" + _mapLineNumber( temp ) + " || " + _getNodeFromJavaLine( temp ) ); System.out.println( " } String getSource( FunctionNode fn ){ final int start = fn.getEncodedSourceStart(); final int end = fn.getEncodedSourceEnd(); final String encoded = _encodedSource.substring( start , end ); final String realSource = Decompiler.decompile( encoded , 0 , new UintMap() ); return realSource; } private String getStringCode( String s ){ int stringId = _strings.size(); _strings.add( s ); return "_string(" + stringId + ")"; } public boolean hasReturn(){ return _hasReturn; } public int findStringId( String s ){ for ( int i=0; i<_strings.size(); i++ ){ if ( _strings.get(i).equals( s ) ){ return i; } } return -1; } String _rand(){ return String.valueOf( _random.nextInt( 1000000 ) ); } static Random _random( String name ){ return new Random( name.hashCode() ); } final Random _random; final String _name; final String _source; final String _encodedSource; final String _className; final String _fullClassName; final String _package = DEFAULT_PACKAGE; final boolean _invokedFromEval; final Language _sourceLanguage; final int _id; // these 3 variables should only be use by _append private int _currentLineNumber = 0; final Map<Integer,List<Node>> _javaCodeToLines = new TreeMap<Integer,List<Node>>(); final Map<Node,Integer> _nodeToSourceLine = new HashMap<Node,Integer>(); final Map<Node,ScriptOrFnNode> _nodeToSOR = new HashMap<Node,ScriptOrFnNode>(); final List<Pair<String,String>> _regex = new ArrayList<Pair<String,String>>(); final List<String> _strings = new ArrayList<String>(); final ScriptInfo _scriptInfo; int _preMainLines = -1; private final StringBuilder _mainJavaCode = new StringBuilder(); private boolean _hasReturn = false; private JSFunction _it; private int _methodId = 0; private final static Map<Integer,String> _2ThingThings = new HashMap<Integer,String>(); static { _2ThingThings.put( Token.ADD , "add" ); _2ThingThings.put( Token.MUL , "mul" ); _2ThingThings.put( Token.SUB , "sub" ); _2ThingThings.put( Token.DIV , "div" ); _2ThingThings.put( Token.SHEQ , "sheq" ); _2ThingThings.put( Token.SHNE , "shne" ); _2ThingThings.put( Token.EQ , "eq" ); _2ThingThings.put( Token.NE , "eq" ); _2ThingThings.put( Token.GE , "ge" ); _2ThingThings.put( Token.LE , "le" ); _2ThingThings.put( Token.LT , "lt" ); _2ThingThings.put( Token.GT , "gt" ); _2ThingThings.put( Token.BITOR , "bitor" ); _2ThingThings.put( Token.BITAND , "bitand" ); _2ThingThings.put( Token.BITXOR , "bitxor" ); _2ThingThings.put( Token.URSH , "ursh" ); _2ThingThings.put( Token.RSH , "rsh" ); _2ThingThings.put( Token.LSH , "lsh" ); _2ThingThings.put( Token.MOD , "mod" ); } private static final int _while1[] = new int[]{ Token.GOTO , Token.TARGET , 0 , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static final int _doWhile1[] = new int[]{ Token.TARGET , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static Node[] _matches( Node n , int types[] ){ Node foo[] = new Node[types.length]; for ( int i=0; i<types.length; i++ ){ foo[i] = n; if ( types[i] > 0 && n.getType() != types[i] ) return null; n = n.getNext(); } return n == null ? foo : null; } // SCRIPT INFO static class ScriptInfo implements StackTraceFixer { ScriptInfo( String name , String fullClassName , Language l , Convert c ){ _name = name; _fullClassName = fullClassName; _sourceLanguage = l; _convert = DJS ? c : null; } public void fixStack( Throwable e ){ StackTraceHolder.getInstance().fix( e ); } public StackTraceElement fixSTElement( StackTraceElement element ){ return fixSTElement( element , false ); } public StackTraceElement fixSTElement( StackTraceElement element , boolean debug ){ if ( ! element.getClassName().startsWith( _fullClassName ) ) return null; if ( debug ){ System.out.println( element ); if ( _convert != null ) _convert._debugLineNumber( element.getLineNumber() ); } Pair<Integer,String> p = _lines.get( element.getLineNumber() ); if ( p == null ) return null; return new StackTraceElement( _name , p.second , _name , p.first ); } public boolean removeSTElement( StackTraceElement element ){ String s = element.toString(); return s.contains( ".call(JSFunctionCalls" ) || s.contains( "ed.js.JSFunctionBase.call(" ) || s.contains( "ed.js.engine.JSCompiledScript.call" ); } void setup( Convert c ){ for ( int i=0; i<c._currentLineNumber + 100; i++ ){ Node n = c._getNodeFromJavaLine( i ); if ( n == null ) continue; int line = c._mapLineNumber( i ); ScriptOrFnNode sof = c._nodeToSOR.get( n ); String method = "___"; if ( sof instanceof FunctionNode ) method = ((FunctionNode)sof).getFunctionName(); _lines.put( i , new Pair<Integer,String>( line , method ) ); } } final String _name; final String _fullClassName; final Language _sourceLanguage; final Convert _convert; final Map<Integer,Pair<Integer,String>> _lines = new HashMap<Integer,Pair<Integer,String>>(); } // END SCRIPT INFO // this is class compile optimization below static synchronized int _getNumForClass( String name , String source ){ ClassInfo ci = _classes.get( name ); if ( ci == null ){ ci = new ClassInfo(); _classes.put( name , ci ); } return ci.getNum( source ); } private static Map<String,ClassInfo> _classes = Collections.synchronizedMap( new HashMap<String,ClassInfo>() ); static class ClassInfo { synchronized int getNum( String source ){ _myMd5.Init(); _myMd5.Update( source ); final String hash = _myMd5.asHex(); Integer num = _sourceToNumber.get( hash ); if ( num != null ) return num; num = ++_numSoFar; _sourceToNumber.put( hash , num ); return num; } final MD5 _myMd5 = new MD5(); final Map<String,Integer> _sourceToNumber = new TreeMap<String,Integer>(); int _numSoFar = 0; } }
// Convert.java package ed.js.engine; import java.io.*; import java.util.*; import java.util.regex.*; import com.twmacinta.util.*; import ed.ext.org.mozilla.javascript.*; import ed.js.*; import ed.io.*; import ed.lang.*; import ed.util.*; public class Convert { static boolean DJS = Boolean.getBoolean( "DEBUG.JS" ); final boolean D; public static final String DEFAULT_PACKAGE = "ed.js.gen"; public static JSFunction makeAnon( String code ){ return makeAnon( code , false ); } public static JSFunction makeAnon( String code , boolean forceEval ){ try { final String nice = code.trim(); final String name = "anon" + Math.random(); if ( nice.startsWith( "function" ) && nice.endsWith( "}" ) ){ Convert c = new Convert( name , code , true ); JSFunction func = c.get(); Scope s = Scope.newGlobal().child(); s.setGlobal( true ); func.call( s ); String keyToUse = null; int numKeys = 0; for ( String key : s.keySet() ){ if ( key.equals( "arguments" ) ) continue; keyToUse = key; numKeys++; } if ( numKeys == 1 ){ Object val = s.get( keyToUse ); if ( val instanceof JSFunction ){ JSFunction f = (JSFunction)val; f.setUsePassedInScope( forceEval ); return f; } } } Convert c = new Convert( name , nice , forceEval ); return c.get(); } catch ( IOException ioe ){ throw new RuntimeException( "should be impossible" , ioe ); } } public Convert( File sourceFile ) throws IOException { this( sourceFile.getAbsolutePath() , StreamUtil.readFully( sourceFile , "UTF-8" ) ); } public Convert( String name , String source ) throws IOException { this(name, source, false); } public Convert( String name , String source, boolean invokedFromEval) throws IOException { this( name , source , invokedFromEval , Language.JS ); } public Convert( String name , String source, boolean invokedFromEval , Language sourceLanguage ) throws IOException { D = DJS && ! name.contains( "src/main/ed/lang" ) && ! name.contains( "src_main_ed_lang" ) ; _invokedFromEval = invokedFromEval; _sourceLanguage = sourceLanguage; _name = name; _source = source; _className = cleanName( _name ) + _getNumForClass( _name , _source ); _fullClassName = _package + "." + _className; _random = _random( _fullClassName ); _id = _random.nextInt(); _scriptInfo = new ScriptInfo( _name , _fullClassName , _sourceLanguage , this ); CompilerEnvirons ce = new CompilerEnvirons(); Parser p = new Parser( ce , ce.getErrorReporter() ); ScriptOrFnNode theNode = null; try { theNode = p.parse( _source , _name , 0 ); } catch ( ed.ext.org.mozilla.javascript.EvaluatorException ee ){ throw JSCompileException.create( ee ); } _encodedSource = p.getEncodedSource(); init( theNode ); } public static String cleanName( String name ){ StringBuilder buf = new StringBuilder( name.length() + 5 ); for ( int i=0; i<name.length(); i++ ){ final char c = name.charAt(i); if ( Character.isLetter( c ) || Character.isDigit( c ) ){ buf.append( c ); continue; } if ( buf.length() == 0 ) continue; buf.append( "_" ); } return buf.toString(); } private void init( ScriptOrFnNode sn ){ if ( _it != null ) throw new RuntimeException( "too late" ); NodeTransformer nf = new NodeTransformer(); nf.transform( sn ); if ( D ){ Debug.print( sn , 0 ); } State state = new State(); _setLineNumbers( sn , sn ); _addFunctionNodes( sn , state ); if ( D ) System.out.println( "***************" ); Node n = sn.getFirstChild(); while ( n != null ){ if ( n.getType() != Token.FUNCTION ){ if ( n.getNext() == null ){ if ( n.getType() == Token.EXPR_RESULT ){ _append( "return " , n ); _hasReturn = true; } if ( n.getType() == Token.RETURN ) _hasReturn = true; } _add( n , sn , state ); _append( "\n" , n ); } n = n.getNext(); } if ( ! _hasReturn ) { _append( "return null;" , sn ); } else { int end = _mainJavaCode.length() - 1; boolean alreadyHaveOne = false; for ( ; end >= 0; end char c = _mainJavaCode.charAt( end ); if ( Character.isWhitespace( c ) ) continue; if ( c == ';' ){ if ( ! alreadyHaveOne ){ alreadyHaveOne = true; continue; } _mainJavaCode.setLength( end + 1 ); } break; } } } private void _add( Node n , State s ){ _add( n , null , s ); } private void _add( Node n , ScriptOrFnNode sn , State state ){ switch ( n.getType() ){ case Token.TYPEOF: _append( "JS_typeof( " , n ); _assertOne( n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.TYPEOFNAME: _append( "JS_typeof( " , n ); if ( state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); _append( " ) " , n ); break; case Token.REGEXP: int myId = _regex.size(); ScriptOrFnNode parent = _nodeToSOR.get( n ); if ( parent == null ) throw new RuntimeException( "how is parent null" ); int rId = n.getIntProp( Node.REGEXP_PROP , -1 ); _regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) ); _append( " _regex(" + myId + ") " , n ); break; case Token.ARRAYLIT: { _append( "( JSArray.create( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) ) " , n ); } break; case Token.OBJECTLIT: { _append( "JS_buildLiteralObject( new String[]{ " , n ); boolean first = true; Node c = n.getFirstChild(); for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){ if ( first ) first = false; else _append( " , " , n ); String name = id.toString(); if ( c.getType() == Token.GET ) name = JSObjectBase.getterName( name ); else if ( c.getType() == Token.SET ) name = JSObjectBase.setterName( name ); _append( getStringCode( name ) + ".toString()" , n ); c = c.getNext(); } _append( " } " , n ); c = n.getFirstChild(); while ( c != null ){ _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) " , n ); } break; case Token.NEW: _append( "scope.clearThisNew( " , n ); _addCall( n , state , true ); _append( " ) " , n ); break; case Token.THIS: _append( "passedIn.getThis()" , n ); break; case Token.INC: case Token.DEC: _assertOne( n ); Node tempChild = n.getFirstChild(); if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){ if ( ! state.isNumber( tempChild.getString() ) ) throw new RuntimeException( "can't increment local variable : " + tempChild.getString() ); String str = n.getType() == Token.INC ? "++ " : " _append( tempChild.getString() + str , n ); } else { _append( "JS_inc( " , n ); _createRef( n.getFirstChild() , state ); _append( " , " , n ); _append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n ); _append( " , " , n ); _append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n ); _append( ")" , n ); } break; case Token.USE_STACK: _append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n ); break; case Token.SETPROP_OP: case Token.SETELEM_OP: Node theOp = n.getFirstChild().getNext().getNext(); if ( ( theOp.getType() == Token.ADD || theOp.getType() == Token.SUB || theOp.getType() == Token.MUL || theOp.getType() == Token.DIV ) && ( theOp.getFirstChild().getType() == Token.USE_STACK || theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){ _append( "\n" , n ); _append( "JS_setDefferedOp( (JSObject) " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( theOp.getFirstChild().getType() == Token.USE_STACK ? theOp.getFirstChild().getNext() : theOp.getFirstChild() , state ); _append( " , " + theOp.getType() , n ); _append( " \n ) \n" , n ); break; } _append( "\n { \n" , n ); _append( "JSObject __tempObject = (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); String tempName = "__temp" + _rand(); state._tempOpNames.push( tempName ); _append( "Object " + tempName + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( ";\n" , n ); _append( " __tempObject.set(" , n ); _append( tempName , n ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ); \n" , n ); _append( " } \n" , n ); break; case Token.SETPROP: case Token.SETELEM: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ").set( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) " , n ); break; case Token.GETPROPNOWARN: case Token.GETPROP: case Token.GETELEM: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ").get( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.SET_REF: Node fc = n.getFirstChild(); if( fc.getType() != Token.REF_SPECIAL && fc.getType() != Token.REF_MEMBER ) throw new RuntimeException( "token is of type "+Token.name(fc.getType())+", should be of type REF_SPECIAL or REF_MEMBER."); _append( "((JSObject)" , n ); _add( n.getFirstChild().getFirstChild() , state ); _append( ").set( " , n ); _add( fc , state ); _append( " , " , n ); _add( fc.getNext() , state ); _append( " )" , n ); break; case Token.GET_REF: _append( "((JSObject)" , n ); _add( n.getFirstChild().getFirstChild() , state ); _append( ").get( " , n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.REF_SPECIAL : _append( "\"" + n.getProp( Node.NAME_PROP ).toString() + "\"" , n ); break; case Token.REF_MEMBER : _append( "\"" , n ); final int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ( ( memberTypeFlags & Node.DESCENDANTS_FLAG ) != 0 ) _append( ".." , n ); if ( ( memberTypeFlags & Node.ATTRIBUTE_FLAG ) != 0 ) _append( "@" , n ); _append( n.getFirstChild().getNext().getString() , n ); _append( "\"" , n ); break; case Token.REF_NS_MEMBER : if( ( n.getIntProp(Node.MEMBER_TYPE_PROP,0) & Node.ATTRIBUTE_FLAG ) != 0 ) { _append( "\"@\" + " , n ); } _add( n.getFirstChild().getNext() , state ); _append( " + \"::\" + ", n ); _add( n.getFirstChild().getNext().getNext() , state ); break; case Token.REF_NAME : case Token.ESCXMLTEXT : case Token.ESCXMLATTR : _add( n.getFirstChild(), state ); break; case Token.EXPR_RESULT: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.CALL: _addCall( n , state ); break; case Token.NUMBER: double d = n.getDouble(); String temp = String.valueOf( d ); if ( temp.endsWith( ".0" ) || JSNumericFunctions.couldBeInt( d ) ) temp = String.valueOf( (int)d ); _append( "JSNumber.self( " + temp + ")" , n ); break; case Token.STRING: final String theString = n.getString(); _append( getStringCode( theString ) , n ); break; case Token.TRUE: _append( " true " , n ); break; case Token.FALSE: _append( " false " , n ); break; case Token.NULL: _append( " null " , n ); break; case Token.VAR: _addVar( n , state ); break; case Token.GETVAR: if ( state.useLocalVariable( n.getString() ) ){ _append( n.getString() , n ); break; } case Token.NAME: if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); break; case Token.SETVAR: final String foo = n.getFirstChild().getString(); if ( state.useLocalVariable( foo ) ){ if ( ! state.hasSymbol( foo ) ) throw new RuntimeException( "something is wrong" ); if ( ! state.isPrimitive( foo ) ) _append( "JSInternalFunctions.self ( " , n ); _append( foo + " = " , n ); _add( n.getFirstChild().getNext() , state ); if ( ! state.isPrimitive( foo ) ) _append( " )\n" , n ); } else { _setVar( foo , n.getFirstChild().getNext() , state , true ); } break; case Token.SETNAME: _addSet( n , state ); break; case Token.GET: _addFunction( n.getFirstChild() , state ); break; case Token.SET: _addFunction( n.getFirstChild() , state ); break; case Token.FUNCTION: _addFunction( n , state ); break; case Token.BLOCK: _addBlock( n , state ); break; case Token.EXPR_VOID: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.RETURN: boolean last = n.getNext() == null; if ( ! last ) _append( "if ( true ) { " , n ); _append( "return " , n ); if ( n.getFirstChild() != null ){ _assertOne( n ); _add( n.getFirstChild() , state ); } else { _append( " null " , n ); } _append( ";" , n ); if ( ! last ) _append( "}" , n ); _append( "\n" , n ); break; case Token.BITNOT: _assertOne( n ); _append( "JS_bitnot( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.HOOK: _append( " JSInternalFunctions.self( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ? ( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) : ( " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) ) " , n ); break; case Token.POS: _assertOne( n ); _add( n.getFirstChild() , state ); break; case Token.ADD: if ( state.isNumberAndLocal( n.getFirstChild() ) && state.isNumberAndLocal( n.getFirstChild().getNext() ) ){ _append( "(" , n ); _add( n.getFirstChild() , state ); _append( " + " , n ); _add( n.getFirstChild().getNext() , state ); _append( ")" , n ); break; } case Token.NE: case Token.MUL: case Token.DIV: case Token.SUB: case Token.EQ: case Token.SHEQ: case Token.SHNE: case Token.GE: case Token.LE: case Token.LT: case Token.GT: case Token.BITOR: case Token.BITAND: case Token.BITXOR: case Token.URSH: case Token.RSH: case Token.LSH: case Token.MOD: if ( n.getType() == Token.NE ) _append( " ! " , n ); _append( "JS_" , n ); String fooooo = _2ThingThings.get( n.getType() ); if ( fooooo == null ) throw new RuntimeException( "noting for : " + n ); _append( fooooo , n ); _append( "\n( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n " , n ); break; case Token.IFNE: _addIFNE( n , state ); break; case Token.LOOP: _addLoop( n , state ); break; case Token.EMPTY: if ( n.getFirstChild() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "not really empty" ); } break; case Token.LABEL: _append( n.getString() + ":" , n ); break; case Token.BREAK: _append( "break " + n.getString() + ";\n" , n ); break; case Token.CONTINUE: _append( "if ( true ) continue " + n.getString() + ";\n" , n ); break; case Token.WHILE: _append( "while( false || JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){ " , n ); _add( n.getFirstChild().getNext() , state ); _append( " }\n" , n ); break; case Token.FOR: _addFor( n , state ); break; case Token.TARGET: break; case Token.NOT: _assertOne( n ); _append( " JS_not( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.AND: /* _append( " ( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " && " , n ); _append( " JS_evalToBool( " , n ); _add( c , state ); _append( " ) " , n ); c = c.getNext(); } _append( " ) " , n ); break; */ case Token.OR: Node cc = n.getFirstChild(); if ( cc.getNext() == null ) throw new RuntimeException( "what?" ); if ( cc.getNext().getNext() != null ) throw new RuntimeException( "what?" ); String mod = n.getType() == Token.AND ? "and" : "or"; _append( "JSInternalFunctions.self( scope." + mod + "Save( " , n ); _add( cc , state ); _append( " ) ? scope.get" + mod + "Save() : ( " , n ); _add( cc.getNext() , state ); _append( " ) ) " , n ); break; case Token.LOCAL_BLOCK: _assertOne( n ); if ( n.getFirstChild().getType() != Token.TRY ) throw new RuntimeException("only know about LOCAL_BLOCK with try" ); _addTry( n.getFirstChild() , state ); break; case Token.JSR: case Token.RETURN_RESULT: // these are handled in block break; case Token.THROW: _append( "if ( true ) _throw( " , n ); _add( n.getFirstChild() , state ); _append( " ); " , n ); break; case Token.INSTANCEOF: _append( "JS_instanceof( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); if ( n.getFirstChild().getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); break; case Token.DELPROP: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " ).removeField( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); break; case Token.DEL_REF: _append( "((JSObject)" , n ); _add( n.getFirstChild().getFirstChild() , state ); _append( ").removeField( " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.SWITCH: _addSwitch( n , state ); break; case Token.COMMA: _append( "JS_comma( " , n ); boolean first = true; Node inner = n.getFirstChild(); while ( inner != null ){ if ( first ) first = false; else _append( " , " , n ); _append( "\n ( " , n ); _add( inner , state ); _append( " )\n " , n ); inner = inner.getNext(); } _append( " ) " , n ); break; case Token.IN: _append( "((JSObject)" , n ); _add( n.getFirstChild().getNext() , state ); _append( " ).containsKey( " , n ); _add( n.getFirstChild() , state ); _append( ".toString() ) " , n ); break; case Token.NEG: _append( "JS_mul( -1 , " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.ENTERWITH: _append( "scope.enterWith( (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " );" , n ); break; case Token.LEAVEWITH: _append( "scope.leaveWith();" , n ); break; case Token.WITH: _add( n.getFirstChild() , state ); break; case Token.DOTQUERY: _append( "((JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " ).get( new ed.js.e4x.Query( " , n ); Node n2 = n.getFirstChild().getNext(); switch( n2.getFirstChild().getType() ) { case Token.GET_REF : _append( "\"@\" + " , n ); _add( n2.getFirstChild().getFirstChild() , state ); break; case Token.NAME : _append( "\"" + n2.getFirstChild().getString() + "\"" , n ); break; } _append( " , " , n ); _add( n2.getFirstChild().getNext() , state ); _append( " + \"\" , " , n ); String comp = Token.name( n2.getType() ); _append( "\"" + comp + "\" ) ) " , n ); break; case Token.DEFAULTNAMESPACE : _append( "((ed.js.e4x.ENode.Cons)scope.get( \"XML\")).setAndGetDefaultNamespace( ", n ); _add( n.getFirstChild(), state ); _append(")", n ); break; default: Debug.printTree( n , 0 ); throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() ); } } private void _addDotQuery( Node n , State state ){ _append( "(new ed.js.e4x.E4X.Query(" , n ); String s = Token.name( n.getType() ); { Node t = n.getFirstChild(); switch ( t.getType() ){ case Token.GET_REF: _append( "\"@\" + " , n ); _add( t.getFirstChild().getFirstChild() , state ); break; default: throw new RuntimeException( "don't know how to handle " + Token.name( t.getType() ) + " in a DOTQUERY" ); } } _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( "))" , n ); } private void _addSwitch( Node n , State state ){ _assertType( n , Token.SWITCH ); String ft = "ft" + _rand(); String val = "val" + _rand(); _append( "boolean " + ft + " = false;\n" , n ); _append( "do { \n " , n ); _append( " if ( false ) break; \n" , n ); Node caseArea = n.getFirstChild(); _append( "Object " + val + " = " , n ); _add( caseArea , state ); _append( " ; \n " , n ); n = n.getNext(); _assertType( n , Token.GOTO ); // this is default ? n = n.getNext().getNext(); caseArea = caseArea.getNext(); while ( caseArea != null ){ _append( "if ( " + ft + " || JS_eq( " + val + " , " , caseArea ); _add( caseArea.getFirstChild() , state ); _append( " ) ){\n " + ft + " = true; \n " , caseArea ); _assertType( n , Token.BLOCK ); _add( n , state ); n = n.getNext().getNext(); _append( " } \n " , caseArea ); caseArea = caseArea.getNext(); } if ( n != null && n.getType() == Token.BLOCK ){ _add( n , state ); } _append(" } while ( false );" , n ); } private void _createRef( Node n , State state ){ if ( n.getType() == Token.NAME || n.getType() == Token.GETVAR ){ if ( state.useLocalVariable( n.getString() ) ) throw new RuntimeException( "can't create a JSRef from a local variable : " + n.getString() ); _append( " new JSRef( scope , null , " , n ); _append( "\"" + n.getString() + "\"" , n ); _append( " ) " , n ); return; } if ( n.getType() == Token.GETPROP || n.getType() == Token.GETELEM ){ _append( " new JSRef( scope , (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); return; } throw new RuntimeException( "can't handle" ); } private void _addTry( Node n , State state ){ _assertType( n , Token.TRY ); Node mainBlock = n.getFirstChild(); _assertType( mainBlock , Token.BLOCK ); _append( "try { \n " , n ); _add( mainBlock , state ); _append( " \n } \n " , n ); n = mainBlock.getNext(); final String num = _rand(); final String javaEName = "javaEEE" + num; final String javaName = "javaEEEO" + num; while ( n != null ){ if ( n.getType() == Token.FINALLY ){ _assertType( n.getFirstChild() , Token.BLOCK ); _append( "finally { \n" , n ); _add( n.getFirstChild() , state ); _append( " \n } \n " , n ); n = n.getNext(); continue; } if ( n.getType() == Token.LOCAL_BLOCK && n.getFirstChild().getType() == Token.CATCH_SCOPE ){ _append( " \n catch ( Exception " + javaEName + " ){ \n " , n ); _append( " \n Object " + javaName + " = ( " + javaEName + " instanceof JSException ) ? " + " ((JSException)" + javaEName + ").getObject() : " + javaEName + " ; \n" , n ); _append( "try { scope.pushException( " + javaEName + " ); \n" , n ); Node catchScope = n.getFirstChild(); while ( catchScope != null ){ final Node c = catchScope; if ( c.getType() != Token.CATCH_SCOPE ) break; Node b = c.getNext(); _assertType( b , Token.BLOCK ); _assertType( b.getFirstChild() , Token.ENTERWITH ); _assertType( b.getFirstChild().getNext() , Token.WITH ); b = b.getFirstChild().getNext().getFirstChild(); _assertType( b , Token.BLOCK ); String jsName = c.getFirstChild().getString(); _append( " scope.put( \"" + jsName + "\" , " + javaName + " , true ); " , c ); b = b.getFirstChild(); boolean isIF = b.getType() == Token.IFNE; if ( isIF ){ _append( "\n if ( " + javaEName + " != null && JS_evalToBool( " , b ); _add( b.getFirstChild() , state ); _append( " ) ){ \n " , b ); b = b.getNext().getFirstChild(); } while ( b != null ){ if ( b.getType() == Token.LEAVEWITH ) break; _add( b , state ); b = b.getNext(); } _append( "if ( true ) " + javaEName + " = null ;\n" , b ); if ( isIF ){ _append( "\n } \n " , b ); } catchScope = catchScope.getNext().getNext(); } _append( "if ( " + javaEName + " != null ){ if ( " + javaEName + " instanceof RuntimeException ){ throw (RuntimeException)" + javaEName + ";} throw new JSException( " + javaEName + ");}\n" , n ); _append( " } finally { scope.popException(); } " , n ); _append( "\n } \n " , n ); // ends catch n = n.getNext(); continue; } if ( n.getType() == Token.GOTO || n.getType() == Token.TARGET || n.getType() == Token.JSR ){ n = n.getNext(); continue; } if ( n.getType() == Token.RETHROW ){ //_append( "\nthrow " + javaEName + ";\n" , n ); n = n.getNext(); continue; } throw new RuntimeException( "what : " + Token.name( n.getType() ) ); } } private void _addFor( Node n , State state ){ _assertType( n , Token.FOR ); final int numChildren = countChildren( n ); if ( numChildren == 4 ){ _append( "\n for ( " , n ); if ( n.getFirstChild().getType() == Token.BLOCK ){ Node temp = n.getFirstChild().getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.EXPR_VOID ) _add( temp.getFirstChild() , state ); else _add( temp , state ); temp = temp.getNext(); if ( temp != null ) _append( " , " , n ); } } else if ( n.getFirstChild().getType() != Token.EMPTY ) { _add( n.getFirstChild() , state ); } _append( " ; \n JS_evalToBool( " , n ); if( n.getFirstChild().getNext().getType() == Token.EMPTY ) { _append( "true" , n ); } else { _add( n.getFirstChild().getNext() , state ); } _append( " ) ; \n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " )\n " , n ); _append( " { \n " , n ); _add( n.getFirstChild().getNext().getNext().getNext() , state ); _append( " } \n " , n ); } else if ( numChildren == 3 ){ String name = n.getFirstChild().getString(); String tempName = name + "TEMP"; if( n.getFirstChild().getFirstChild() != null && n.getFirstChild().getFirstChild().getType() == Token.ENUM_INIT_VALUES ) { _append( "\n for ( Object " , n ); _append( tempName , n ); _append( " : JSInternalFunctions.JS_collForForEach( ", n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ){\n " , n ); if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ) _append( name + " = " + tempName + "; " , n ); else _append( "scope.put( \"" + name + "\" , " + tempName + " , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } else { _append( "\n for ( String " , n ); _append( tempName , n ); _append( " : JSInternalFunctions.JS_collForFor( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ){\n " , n ); if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ) _append( name + " = new JSString( " + tempName + ") ; " , n ); else _append( "scope.put( \"" + name + "\" , new JSString( " + tempName + " ) , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } } else { throw new RuntimeException( "wtf?" ); } } private void _addLoop( Node n , State state ){ _assertType( n , Token.LOOP ); final Node theLoop = n; n = n.getFirstChild(); Node nodes[] = null; if ( ( nodes = _matches( n , _while1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[5]; _append( "while ( JS_evalToBool( " , theLoop ); _add( predicate.getFirstChild() , state ); _append( " ) ) " , theLoop ); _add( main , state ); } else if ( ( nodes = _matches( n , _doWhile1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[3]; _assertType( predicate , Token.IFEQ ); _append( "do { \n " , theLoop ); _add( main , state ); _append( " } \n while ( false || JS_evalToBool( " , n ); _add( predicate.getFirstChild() , state ); _append( " ) );\n " , n ); } else { throw new RuntimeException( "what?" ); } } private void _addIFNE( Node n , State state ){ _assertType( n , Token.IFNE ); final Node.Jump theIf = (Node.Jump)n; _assertOne( n ); // this is the predicate Node ifBlock = n.getNext(); _append( "if ( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){\n" , n ); _add( ifBlock , state ); _append( "}\n" , n ); n = n.getNext().getNext(); if ( n.getType() == Token.TARGET ){ if ( n.getNext() != null ) throw new RuntimeException( "something is wrong" ); return; } _assertType( n , Token.GOTO ); _assertType( n.getNext() , Token.TARGET ); if ( theIf.target.hashCode() != n.getNext().hashCode() ) throw new RuntimeException( "hashes don't match" ); n = n.getNext().getNext(); _append( " else if ( true ) { " , n ); _add( n , state ); _append( " } \n" , n ); _assertType( n.getNext() , Token.TARGET ); if ( n.getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); } private void _addFunctionNodes( final ScriptOrFnNode sn , final State state ){ Set<Integer> baseIds = new HashSet<Integer>(); { Node temp = sn.getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.FUNCTION && temp.getString() != null ){ int prop = temp.getIntProp( Node.FUNCTION_PROP , -1 ); if ( prop >= 0 ){ baseIds.add( prop ); } } temp = temp.getNext(); } } for ( int i=0; i<sn.getFunctionCount(); i++ ){ FunctionNode fn = sn.getFunctionNode( i ); _setLineNumbers( fn , fn ); String name = fn.getFunctionName(); String anonName = "tempFunc_" + _id + "_" + i + "_" + _methodId++; boolean anon = name.length() == 0; if ( anon ) name = anonName; if ( D ){ System.out.println( "***************" ); System.out.println( i + " : " + name ); } String useName = name; if ( ! anon && ! baseIds.contains( i ) ){ useName = anonName; state._nonRootFunctions.add( i ); } state._functionIdToName.put( i , useName ); _setVar( useName , fn , state , anon ); _append( "; \n scope.getFunction( \"" + useName + "\" ).setName( \"" + name + "\" );\n\n" , fn ); } } private void _addFunction( Node n , State state ){ if ( ! ( n instanceof FunctionNode ) ){ if ( n.getString() != null && n.getString().length() != 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( state._nonRootFunctions.contains( id ) ){ _append( "scope.set( \"" + n.getString() + "\" , scope.get( \"" + state._functionIdToName.get( id ) + "\" ) );\n" , n ); } return; } _append( getFunc( n , state ) , n ); return; } _assertOne( n ); FunctionNode fn = (FunctionNode)n; FunctionInfo fi = FunctionInfo.create( fn ); state = state.child(); state._fi = fi; boolean hasArguments = fi.usesArguemnts(); _append( "new JSFunctionCalls" + fn.getParamCount() + "( scope , null ){ \n" , n ); _append( "protected void init(){ super.init(); _sourceLanguage = getFileLanguage(); \n " , n ); _append( "_arguments = new JSArray();\n" , n ); for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); _append( "_arguments.add( \"" + foo + "\" );\n" , n ); } _append( "_globals = new JSArray();\n" , n ); for ( String g : fi._globals ) _append( "_globals.add( \"" + g + "\" );\n" , n ); _append( "}\n" , n ); String callLine = "public Object call( final Scope passedIn "; String varSetup = ""; for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); callLine += " , "; callLine += " Object " + foo; if ( ! state.useLocalVariable( foo ) ){ callLine += "INNNNN"; varSetup += " \nscope.put(\"" + foo + "\"," + foo + "INNNNN , true );\n "; if ( hasArguments ) varSetup += "arguments.add( " + foo + "INNNNN );\n"; } else { state.addSymbol( foo ); if ( hasArguments ) varSetup += "arguments.add( " + foo + " );\n"; } callLine += " "; } callLine += " , Object ___extra[] ){\n" ; _append( callLine + " final Scope scope = usePassedInScope() ? passedIn : new Scope( \"func scope\" , getScope() , passedIn , getFileLanguage() ); " , n ); if ( hasArguments ){ _append( "JSArray arguments = new JSArray();\n" , n ); _append( "scope.put( \"arguments\" , arguments , true );\n" , n ); } for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); final String javaName = foo + ( state.useLocalVariable( foo ) ? "" : "INNNNN" ); final Node defArg = fn.getDefault( foo ); if ( defArg == null ) continue; _append( "if ( null == " + javaName + " ) " , defArg ); _append( javaName + " = " , defArg ); _add( defArg , state ); _append( ";\n" , defArg ); } _append( varSetup , n ); if ( hasArguments ){ _append( "if ( ___extra != null ) for ( Object TTTT : ___extra ) arguments.add( TTTT );\n" , n ); _append( "{ Integer numArgs = _lastStart.get(); _lastStart.set( null ); while( numArgs != null && arguments.size() > numArgs && arguments.get( arguments.size() -1 ) == null ) arguments.remove( arguments.size() - 1 ); }" , n ); } for ( int i=fn.getParamCount(); i<fn.getParamAndVarCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); if ( state.useLocalVariable( foo ) ){ state.addSymbol( foo ); if ( state.isNumber( foo ) ){ _append( "double " + foo + " = 0;\n" , n ); } else _append( "Object " + foo + " = null;\n" , n ); } else { _append( "scope.put( \"" + foo + "\" , null , true );\n" , n ); } } _addFunctionNodes( fn , state ); _add( n.getFirstChild() , state ); _append( "}\n" , n ); int myStringId = _strings.size(); _strings.add( getSource( fn ) ); _append( "\t public String getSourceCode(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "\t public String toString(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "}\n" , n ); } private void _addBlock( Node n , State state ){ _assertType( n , Token.BLOCK ); if ( n.getFirstChild() == null ){ _append( "{}" , n ); return; } // this is weird. look at bracing0.js boolean bogusBrace = true; Node c = n.getFirstChild(); while ( c != null ){ if ( c.getType() != Token.EXPR_VOID ){ bogusBrace = false; break; } if ( c.getFirstChild().getNext() != null ){ bogusBrace = false; break; } if ( c.getFirstChild().getType() != Token.SETVAR ){ bogusBrace = false; break; } c = c.getNext(); } bogusBrace = bogusBrace || ( n.getFirstChild().getNext() == null && n.getFirstChild().getType() == Token.EXPR_VOID && n.getFirstChild().getFirstChild() == null ); if ( bogusBrace ){ c = n.getFirstChild(); while ( c != null ){ _add( c , state ); c = c.getNext(); } return; } boolean endReturn = n.getLastChild() != null && n.getLastChild().getType() == Token.RETURN_RESULT; _append( "{" , n ); String ret = "retName" + _rand(); if ( endReturn ) _append( "\n\nObject " + ret + " = null;\n\n" , n ); Node child = n.getFirstChild(); while ( child != null ){ if ( endReturn && child.getType() == Token.LEAVEWITH ) break; if ( endReturn && child.getType() == Token.EXPR_RESULT ) _append( ret + " = " , child ); _add( child , state ); if ( child.getType() == Token.IFNE || child.getType() == Token.SWITCH ) break; child = child.getNext(); } if ( endReturn ) _append( "\n\nif ( true ){ return " + ret + "; }\n\n" , n ); _append( "}" , n ); } private void _addSet( Node n , State state ){ _assertType( n , Token.SETNAME ); Node name = n.getFirstChild(); _setVar( name.getString() , name.getNext() , state ); } private void _addVar( Node n , State state ){ _assertType( n , Token.VAR ); _assertOne( n ); Node name = n.getFirstChild(); _assertOne( name ); _setVar( name.getString() , name.getFirstChild() , state ); } private void _addCall( Node n , State state ){ _addCall( n , state , false ); } private void _addCall( Node n , State state , boolean isClass ){ Node name = n.getFirstChild(); boolean useThis = name.getType() == Token.GETPROP && ! isClass; if ( useThis ) _append( "scope.clearThisNormal( " , n ); Boolean inc[] = new Boolean[]{ true }; String f = getFunc( name , state , isClass , inc ); _append( ( inc[0] ? f : "" ) + ".call( scope" + ( isClass ? ".newThis( " + f + " )" : "" ) + " " , n ); Node param = name.getNext(); while ( param != null ){ _append( " , " , param ); _add( param , state ); param = param.getNext(); } _append( " , new Object[0] ) " , n ); if ( useThis ) _append( " ) " , n ); } private void _setVar( String name , Node val , State state ){ _setVar( name , val , state , false ); } private void _setVar( String name , Node val , State state , boolean local ){ if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ){ boolean prim = state.isPrimitive( name ); if ( ! prim ) _append( "JSInternalFunctions.self( " , val ); _append( name + " = " , val ); _add( val , state ); _append( "\n" , val ); if ( ! prim ) _append( ")\n" , val ); return; } _append( "scope.put( \"" + name + "\" , " , val); _add( val , state ); _append( " , " + local + " ) " , val ); } private int countChildren( Node n ){ int num = 0; Node c = n.getFirstChild(); while ( c != null ){ num++; c = c.getNext(); } return num; } public static void _assertOne( Node n ){ if ( n.getFirstChild() == null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "no child" ); } if ( n.getFirstChild().getNext() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "more than 1 child" ); } } public void _assertType( Node n , int type ){ _assertType( n , type , this ); } public static void _assertType( Node n , int type , Convert c ){ if ( type == n.getType() ) return; String msg = "wrong type. was : " + Token.name( n.getType() ) + " should be " + Token.name( type ); if ( c != null ) msg += " file : " + c._name + " : " + ( c._nodeToSourceLine.get( n ) + 1 ); throw new RuntimeException( msg ); } private void _setLineNumbers( final Node startN , final ScriptOrFnNode startSOF ){ final Set<Integer> seen = new HashSet<Integer>(); final List<Pair<Node,ScriptOrFnNode>> overallTODO = new LinkedList<Pair<Node,ScriptOrFnNode>>(); overallTODO.add( new Pair<Node,ScriptOrFnNode>( startN , startSOF ) ); while ( overallTODO.size() > 0 ){ final Pair<Node,ScriptOrFnNode> temp = overallTODO.remove( 0 ); Node n = temp.first; final ScriptOrFnNode sof = temp.second; final int line = n.getLineno(); if ( line < 0 ) throw new RuntimeException( "something is wrong" ); List<Node> todo = new LinkedList<Node>(); _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); while ( todo.size() > 0 ){ n = todo.remove(0); if ( seen.contains( n.hashCode() ) ) continue; seen.add( n.hashCode() ); if ( n.getLineno() > 0 ){ overallTODO.add( new Pair<Node,ScriptOrFnNode>( n , n instanceof ScriptOrFnNode ? (ScriptOrFnNode)n : sof ) ); continue; } _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); } } } private void _append( String s , Node n ){ _mainJavaCode.append( s ); if ( n == null ) return; int numLines = 0; int max = s.length(); for ( int i=0; i<max; i++ ) if ( s.charAt( i ) == '\n' ) numLines++; final int start = _currentLineNumber; int end = _currentLineNumber + numLines; for ( int i=start; i<end; i++ ){ List<Node> l = _javaCodeToLines.get( i ); if ( l == null ){ l = new ArrayList<Node>(); _javaCodeToLines.put( i , l ); } l.add( n ); } _currentLineNumber = end; } private String getFunc( Node n , State state ){ return getFunc( n , state , false , null ); } private String getFunc( Node n , State state , boolean isClass , Boolean inc[] ){ if ( n.getClass().getName().indexOf( "StringNode" ) < 0 ){ if ( n.getType() == Token.GETPROP && ! isClass ){ _append( "scope.getFunctionAndSetThis( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( ".toString() ) " , n ); return ""; } int start = _mainJavaCode.length(); _append( "((JSFunction )" , n); _add( n , state ); _append( ")" , n ); int end = _mainJavaCode.length(); if( isClass ){ if ( inc == null ) throw new RuntimeException( "inc is null and can't be here" ); inc[0] = false; return "(" + _mainJavaCode.substring( start , end ) + ")"; } return ""; } String name = n.getString(); if ( name == null || name.length() == 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( id == -1 ) throw new RuntimeException( "no name or id for this thing" ); name = state._functionIdToName.get( id ); if ( name == null || name.length() == 0 ) throw new RuntimeException( "no name for this id " ); } if ( state.hasSymbol( name ) ) return "(( JSFunction)" + name + ")"; return "scope.getFunction( \"" + name + "\" )"; } public String getClassName(){ return _className; } public String getClassString(){ StringBuilder buf = new StringBuilder(); buf.append( "package " + _package + ";\n" ); buf.append( "import ed.js.*;\n" ); buf.append( "import ed.js.func.*;\n" ); buf.append( "import ed.js.engine.Scope;\n" ); buf.append( "import ed.js.engine.JSCompiledScript;\n" ); buf.append( "public class " ).append( _className ).append( " extends JSCompiledScript {\n" ); buf.append( "\tpublic Object _call( Scope scope , Object extra[] ) throws Exception {\n" ); buf.append( "\t\t final Scope passedIn = scope; \n" ); if (_invokedFromEval) { buf.append("\t\t // not creating new scope for execution as we're being run in the context of an eval\n"); } else { String cleanName = FileUtil.clean( _name ); buf.append( "\t\t if ( ! usePassedInScope() ){\n" ); buf.append( "\t\t\t scope = new Scope( \"compiled script for:" + cleanName + "\" , scope , null , getFileLanguage() ); \n" ); buf.append( "\t\t }\n" ); buf.append( "\t\t scope.putAll( getTLScope() );\n" ); } buf.append( "\t\t JSArray arguments = new JSArray(); scope.put( \"arguments\" , arguments , true );\n " ); buf.append( "\t\t if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" ); _preMainLines = StringUtil.count( buf.toString() , "\n" ); buf.append( _mainJavaCode ); buf.append( "\n\n\t}\n\n" ); buf.append( "\n}\n\n" ); return buf.toString(); } public JSFunction get(){ if ( _it != null ) return _it; try { Class c = CompileUtil.compile( _package , getClassName() , getClassString() , this ); JSCompiledScript it = (JSCompiledScript)c.newInstance(); _scriptInfo.setup( this ); it._scriptInfo = _scriptInfo; it._regex = _regex; it._strings = new String[ _strings.size() ]; for ( int i=0; i<_strings.size(); i++ ) it._strings[i] = _strings.get( i ); it.setName( _name ); _it = it; StackTraceHolder.getInstance().set( _fullClassName , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js" , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js.func" , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js.engine" , _scriptInfo ); return _it; } catch ( RuntimeException re ){ re.printStackTrace(); fixStack( re ); throw re; } catch ( Exception e ){ e.printStackTrace(); fixStack( e ); throw new RuntimeException( e ); } } public void fixStack( Throwable e ){ StackTraceHolder.getInstance().fix( e ); } Node _getNodeFromJavaLine( int line ){ line = ( line - _preMainLines ) - 1; List<Node> nodes = _javaCodeToLines.get( line ); if ( nodes == null || nodes.size() == 0 ){ return null; } return nodes.get(0); } public int _mapLineNumber( int line ){ Node n = _getNodeFromJavaLine( line ); if ( n == null ) return -1; Integer i = _nodeToSourceLine.get( n ); if ( i == null ) return -1; return i + 1; } public void _debugLineNumber( final int line ){ System.out.println( " for ( int temp = Math.max( 0 , line - 5 ); temp < line + 5 ; temp++ ) System.out.println( "\t" + temp + "->" + _mapLineNumber( temp ) + " || " + _getNodeFromJavaLine( temp ) ); System.out.println( " } String getSource( FunctionNode fn ){ final int start = fn.getEncodedSourceStart(); final int end = fn.getEncodedSourceEnd(); final String encoded = _encodedSource.substring( start , end ); final String realSource = Decompiler.decompile( encoded , 0 , new UintMap() ); return realSource; } private String getStringCode( String s ){ int stringId = _strings.size(); _strings.add( s ); return "_string(" + stringId + ")"; } public boolean hasReturn(){ return _hasReturn; } public int findStringId( String s ){ for ( int i=0; i<_strings.size(); i++ ){ if ( _strings.get(i).equals( s ) ){ return i; } } return -1; } String _rand(){ return String.valueOf( _random.nextInt( 1000000 ) ); } static Random _random( String name ){ return new Random( name.hashCode() ); } final Random _random; final String _name; final String _source; final String _encodedSource; final String _className; final String _fullClassName; final String _package = DEFAULT_PACKAGE; final boolean _invokedFromEval; final Language _sourceLanguage; final int _id; // these 3 variables should only be use by _append private int _currentLineNumber = 0; final Map<Integer,List<Node>> _javaCodeToLines = new TreeMap<Integer,List<Node>>(); final Map<Node,Integer> _nodeToSourceLine = new HashMap<Node,Integer>(); final Map<Node,ScriptOrFnNode> _nodeToSOR = new HashMap<Node,ScriptOrFnNode>(); final List<Pair<String,String>> _regex = new ArrayList<Pair<String,String>>(); final List<String> _strings = new ArrayList<String>(); final ScriptInfo _scriptInfo; int _preMainLines = -1; private final StringBuilder _mainJavaCode = new StringBuilder(); private boolean _hasReturn = false; private JSFunction _it; private int _methodId = 0; private final static Map<Integer,String> _2ThingThings = new HashMap<Integer,String>(); static { _2ThingThings.put( Token.ADD , "add" ); _2ThingThings.put( Token.MUL , "mul" ); _2ThingThings.put( Token.SUB , "sub" ); _2ThingThings.put( Token.DIV , "div" ); _2ThingThings.put( Token.SHEQ , "sheq" ); _2ThingThings.put( Token.SHNE , "shne" ); _2ThingThings.put( Token.EQ , "eq" ); _2ThingThings.put( Token.NE , "eq" ); _2ThingThings.put( Token.GE , "ge" ); _2ThingThings.put( Token.LE , "le" ); _2ThingThings.put( Token.LT , "lt" ); _2ThingThings.put( Token.GT , "gt" ); _2ThingThings.put( Token.BITOR , "bitor" ); _2ThingThings.put( Token.BITAND , "bitand" ); _2ThingThings.put( Token.BITXOR , "bitxor" ); _2ThingThings.put( Token.URSH , "ursh" ); _2ThingThings.put( Token.RSH , "rsh" ); _2ThingThings.put( Token.LSH , "lsh" ); _2ThingThings.put( Token.MOD , "mod" ); } private static final int _while1[] = new int[]{ Token.GOTO , Token.TARGET , 0 , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static final int _doWhile1[] = new int[]{ Token.TARGET , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static Node[] _matches( Node n , int types[] ){ Node foo[] = new Node[types.length]; for ( int i=0; i<types.length; i++ ){ foo[i] = n; if ( types[i] > 0 && n.getType() != types[i] ) return null; n = n.getNext(); } return n == null ? foo : null; } // SCRIPT INFO static class ScriptInfo implements StackTraceFixer { ScriptInfo( String name , String fullClassName , Language l , Convert c ){ _name = name; _fullClassName = fullClassName; _sourceLanguage = l; _convert = DJS ? c : null; } public void fixStack( Throwable e ){ StackTraceHolder.getInstance().fix( e ); } public StackTraceElement fixSTElement( StackTraceElement element ){ return fixSTElement( element , false ); } public StackTraceElement fixSTElement( StackTraceElement element , boolean debug ){ if ( ! element.getClassName().startsWith( _fullClassName ) ) return null; if ( debug ){ System.out.println( element ); if ( _convert != null ) _convert._debugLineNumber( element.getLineNumber() ); } Pair<Integer,String> p = _lines.get( element.getLineNumber() ); if ( p == null ) return null; return new StackTraceElement( _name , p.second , _name , p.first ); } public boolean removeSTElement( StackTraceElement element ){ String s = element.toString(); return s.contains( ".call(JSFunctionCalls" ) || s.contains( "ed.js.JSFunctionBase.call(" ) || s.contains( "ed.js.engine.JSCompiledScript.call" ); } void setup( Convert c ){ for ( int i=0; i<c._currentLineNumber + 100; i++ ){ Node n = c._getNodeFromJavaLine( i ); if ( n == null ) continue; int line = c._mapLineNumber( i ); ScriptOrFnNode sof = c._nodeToSOR.get( n ); String method = "___"; if ( sof instanceof FunctionNode ) method = ((FunctionNode)sof).getFunctionName(); _lines.put( i , new Pair<Integer,String>( line , method ) ); } } final String _name; final String _fullClassName; final Language _sourceLanguage; final Convert _convert; final Map<Integer,Pair<Integer,String>> _lines = new HashMap<Integer,Pair<Integer,String>>(); } // END SCRIPT INFO // this is class compile optimization below static synchronized int _getNumForClass( String name , String source ){ ClassInfo ci = _classes.get( name ); if ( ci == null ){ ci = new ClassInfo(); _classes.put( name , ci ); } return ci.getNum( source ); } private static Map<String,ClassInfo> _classes = Collections.synchronizedMap( new HashMap<String,ClassInfo>() ); static class ClassInfo { synchronized int getNum( String source ){ _myMd5.Init(); _myMd5.Update( source ); final String hash = _myMd5.asHex(); Integer num = _sourceToNumber.get( hash ); if ( num != null ) return num; num = ++_numSoFar; _sourceToNumber.put( hash , num ); return num; } final MD5 _myMd5 = new MD5(); final Map<String,Integer> _sourceToNumber = new TreeMap<String,Integer>(); int _numSoFar = 0; } }
import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; public class Fenetre extends JFrame { public Fenetre(){ this.setTitle("Eternity Game"); this.setSize(1024, 768); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(true); setAlwaysOnTop(false); //Instanciation d'un objet JPanel JPanel pan = new JPanel(); pan.setBackground(Color.RED); this.setContentPane(pan); this.setContentPane(new Panneau()); this.setVisible(true); } }
package bean; import net.dv8tion.jda.core.EmbedBuilder; import net.dv8tion.jda.core.entities.MessageEmbed; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.json.JSONException; import org.json.JSONObject; import utils.TokenManager; import java.awt.*; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class AriyalaSet { private String job; private int coatings; private int twines; private boolean solvent; private ArrayList<String> raidPieces; public AriyalaSet() { this.job = ""; coatings = 0; twines = 0; solvent = false; this.raidPieces = new ArrayList<>(); } public void setJob(String job) { this.job = job; } public String getJob() { return job; } public int getCoatings() { return coatings; } public int addCoating() { return ++coatings; } public int getTwines() { return twines; } public int addTwine() { return ++twines; } public boolean hasSolvent() { return solvent; } public void setSolvent(boolean hasSolvent) { this.solvent = hasSolvent; } public void addRaidPiece(String raidPiece) { raidPieces.add(raidPiece); } public String getRaidPieces() { StringBuilder ret = new StringBuilder(); for (String p : raidPieces) { ret.append(p); ret.append(", "); } return ret.toString(); } public MessageEmbed getMessage() { EmbedBuilder msg = new EmbedBuilder(); msg.setColor(new Color(131, 149, 229)); msg.setAuthor("Ariyala Data", null, iconUrl + job + "_Solid.png"); msg.addField("Coatings", ""+this.getCoatings(), true); msg.addField("Twines", ""+this.getTwines(), true); msg.setTitle("Raid Pieces"); msg.setThumbnail(thumbnailUrl); msg.setDescription(this.getRaidPieces()); return msg.build(); } public static AriyalaSet getFromId(String ariyalaId) { AriyalaSet set = new AriyalaSet(); try { /* Grab ariyala item list */ Request ariyalaRequest = new Request.Builder().url(ariyalaUrl + ariyalaId).build(); Response ariyalaResponse = client.newCall(ariyalaRequest).execute(); JSONObject json = new JSONObject(ariyalaResponse.body().string()); String job = json.getString("content"); set.setJob(job); /* Iterate through item list */ JSONObject gearSet = json.getJSONObject("datasets").getJSONObject(job).getJSONObject("normal").getJSONObject("items"); Iterator<String> keys = gearSet.keys(); while (keys.hasNext()) { /* Determine current gear slot */ String slot = keys.next(); String augType = augmentTokens.get(slot); if (augType == null) continue; /* Grab XIVAPI item data */ int itemId = gearSet.getInt(slot); String xivApiUrl = baseUrl + "/Item/" + itemId + "?private_key=" + TokenManager.getXIVAPITok() + "&columns=Name"; Request itemRequest = new Request.Builder().url(xivApiUrl).build(); Response itemResponse = client.newCall(itemRequest).execute(); String itemName = new JSONObject(itemResponse.body().string()).getString("Name"); /* Determine upgrade item if the item is augmented */ if (itemName.startsWith("Augmented")) { if (augType.equals("coating")) set.addCoating(); if (augType.equals("twine")) set.addTwine(); if (augType.equals("solvent")) set.setSolvent(true); } else { if (slot.startsWith("ring")) slot = "ring"; set.addRaidPiece(slot); } } } catch (IOException ex) { return null; } catch (JSONException ex) { return null; } return set; } private static final OkHttpClient client = new OkHttpClient(); private static final String ariyalaUrl = "http://ffxiv.ariyala.com/store.app?identifier="; private static final String baseUrl = "http://xivapi.com"; private static final String thumbnailUrl = "https://i.imgur.com/WFExWBM.png"; private static final String iconUrl = "https://raw.githubusercontent.com/anoyetta/ACT.Hojoring/master/source/ACT.SpecialSpellTimer/ACT.SpecialSpellTimer.Core/resources/icon/Job/"; private static final Map<String, String> augmentTokens = new HashMap<String, String>() { { put("mainthand", "solvent"); put("head", "twine"); put("chest", "twine"); put("hands", "twine"); put("waist", "coating"); put("legs", "twine"); put("feet", "twine"); put("ears", "coating"); put("neck", "coating"); put("wrist", "coating"); put("ringLeft", "coating"); put("ringRight", "coating"); } }; }
package cliente; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Properties; import javax.swing.JOptionPane; import com.google.gson.Gson; import comandos.ComandosCliente; import frames.MenuCarga; import frames.MenuComerciar; import frames.MenuJugar; import frames.MenuMapas; import juego.Juego; import mensajeria.Comando; import mensajeria.Paquete; import mensajeria.PaqueteComerciar; import mensajeria.PaqueteMensaje; import mensajeria.PaquetePersonaje; import mensajeria.PaqueteUsuario; public class Cliente extends Thread { private Socket cliente; private String miIp; private ObjectInputStream entrada; private ObjectOutputStream salida; private final int anchoVentanaWoME = 800; private final int altoVentanaWoME = 600; // Objeto gson private final Gson gson = new Gson(); // Paquete usuario y paquete personaje private PaqueteUsuario paqueteUsuario; private PaquetePersonaje paquetePersonaje; private PaqueteComerciar paqueteComercio; private PaqueteMensaje paqueteMensaje = new PaqueteMensaje(); // Acciones que realiza el usuario private int accion; // MENU COMERCIAR private MenuComerciar m1; // Ip y puerto private String ip; private int puerto; /** * Pide la accion * @return Devuelve la accion */ public int getAccion() { return accion; } /** * Setea la accion * @param accion * accion a setear */ public void setAccion(final int accion) { this.accion = accion; } private Juego wome; private MenuCarga menuCarga; /** * Constructor del Cliente */ public Cliente() { ip = JOptionPane.showInputDialog("Ingrese IP del servidor: (default localhost)"); if (ip == null) { ip = "localhost"; } try { Properties propiedades = new Properties(); propiedades.load(new FileInputStream("archivo.properties")); puerto = Integer.parseInt(propiedades.getProperty("puerto")); cliente = new Socket(ip, puerto); miIp = cliente.getInetAddress().getHostAddress(); entrada = new ObjectInputStream(cliente.getInputStream()); salida = new ObjectOutputStream(cliente.getOutputStream()); } catch (IOException e) { JOptionPane.showMessageDialog( null, "Fallo al iniciar la aplicación." + "Revise la conexión con el servidor."); System.exit(1); } } /** * Crea el cliente con los parametros que ser reciben * @param ip del servidor * @param puerto del servidor */ public Cliente(final String ip, final int puerto) { try { cliente = new Socket(ip, puerto); miIp = cliente.getInetAddress().getHostAddress(); entrada = new ObjectInputStream(cliente.getInputStream()); salida = new ObjectOutputStream(cliente.getOutputStream()); } catch (IOException e) { JOptionPane.showMessageDialog( null, "Fallo al iniciar la aplicación." + "Revise la conexión con el servidor."); System.exit(1); } } @Override public void run() { synchronized (this) { try { ComandosCliente comand; // Creo el paquete que le voy a enviar al servidor paqueteUsuario = new PaqueteUsuario(); MenuJugar menuJugar = null; while (!paqueteUsuario.isInicioSesion()) { if (menuJugar == null) { menuJugar = new MenuJugar(this); menuJugar.setVisible(true); // Creo los paquetes que le voy a enviar al servidor paqueteUsuario = new PaqueteUsuario(); paquetePersonaje = new PaquetePersonaje(); // Espero a que el usuario seleccione alguna accion wait(); comand = (ComandosCliente) Paquete. getObjetoSet(Comando.NOMBREPAQUETE, getAccion()); comand.setCadena(null); comand.setCliente(this); comand.ejecutar(); // Le envio el paquete al servidor salida.writeObject(gson.toJson(paqueteUsuario)); } // Recibo el paquete desde el servidor String cadenaLeida = (String) entrada.readObject(); Paquete paquete = gson.fromJson(cadenaLeida, Paquete.class); comand = (ComandosCliente) paquete.getObjeto(Comando.NOMBREPAQUETE); comand.setCadena(cadenaLeida); comand.setCliente(this); comand.ejecutar(); } // Creo un paquete con el comando mostrar mapas paquetePersonaje.setComando(Comando.MOSTRARMAPAS); // Abro el menu de eleccion del mapa MenuMapas menuElegirMapa = new MenuMapas(this); menuElegirMapa.setVisible(true); // Espero a que el usuario elija el mapa wait(); // Si clickeo en la Cruz al Seleccionar mapas if (paquetePersonaje.getMapa() == 0) { paquetePersonaje.setComando(Comando.DESCONECTAR); salida.writeObject(gson.toJson(paquetePersonaje)); } else { // Establezco el mapa en el paquete personaje paquetePersonaje.setIp(miIp); // Le envio el paquete con el mapa seleccionado salida.writeObject(gson.toJson(paquetePersonaje)); // Instancio el juego y cargo los recursos wome = new Juego("World Of the Middle Earth", anchoVentanaWoME, altoVentanaWoME, this, paquetePersonaje); // Muestro el menu de carga menuCarga = new MenuCarga(this); menuCarga.setVisible(true); // Espero que se carguen todos los recursos wait(); // Inicio el juego wome.start(); // Finalizo el menu de carga menuCarga.dispose(); } } catch (IOException | InterruptedException | ClassNotFoundException e) { JOptionPane.showMessageDialog( null, "Falló la conexión con el " + "servidor durante el inicio de sesión."); System.exit(1); } } } /** * Pide el cliente. * @return Devuelve el cliente. */ public Socket getSocket() { return cliente; } /** * Setea el cliente. * @param clienteParam * cliente a setear. */ public void setSocket(final Socket clienteParam) { this.cliente = clienteParam; } /** * Pide la ip. * @return Devuelve la ip. */ public String getMiIp() { return miIp; } /** * Setea la ip. * @param miIp * ip a setear. */ public void setMiIp(final String miIp) { this.miIp = miIp; } /** * Pide la entrada. * @return Devuelve la entrada. */ public ObjectInputStream getEntrada() { return entrada; } /** * Setea la entrada. * @param entrada * entrada a setear. */ public void setEntrada(final ObjectInputStream entrada) { this.entrada = entrada; } /** * Pide la salida. * @return Devuelve la salida. */ public ObjectOutputStream getSal() { return salida; } /** * Setea la salida. * @param salida * salida a setear. */ public void setSalida(final ObjectOutputStream salida) { this.salida = salida; } /** * Pide el paquete usuario. * @return Devuelve el paquete usuario. */ public PaqueteUsuario getPaqueteUsuario() { return paqueteUsuario; } /** * Pide el paquete personaje. * @return Devuelve el paquete personaje. */ public PaquetePersonaje getPaquetePersonaje() { return paquetePersonaje; } /** * Pide el juego. * @return Devuelve el juego. */ public Juego getJuego() { return wome; } /** * Pide el menu de carga. * @return Devuelve el menu de carga. */ public MenuCarga getMenuCarga() { return menuCarga; } /** * Actualiza los items del Personaje. * @param paqueteActualizado paquete actualizado. */ public void actualizarItems(final PaquetePersonaje paqueteActualizado) { if (paquetePersonaje.getCantItems() != 0 && paquetePersonaje.getCantItems() != paqueteActualizado.getCantItems()) { paquetePersonaje.anadirItem(paqueteActualizado.getItems(). get(paqueteActualizado.getItems().size() - 1)); } } /** * Retorna la ip del Servidor. * @return ip. */ public String getIp() { return ip; } /** * Setea el PaquetePersonaje que se recibe como parametro. * @param pP PaquetePersonaje. */ public void actualizarPersonaje(final PaquetePersonaje pP) { paquetePersonaje = pP; } /** * Retorna el Juego. * @return Devuelve el juego. */ public Juego getWome() { return wome; } /** * Setea el Juego. * @param wome juego a setear. */ public void setWome(final Juego wome) { this.wome = wome; } /** * Pide el puerto. * @return devuelve el puerto. */ public int getPuerto() { return puerto; } /** * Setea el paquete Usuario. * @param paqueteUsuario a setear. */ public void setPaqueteUsuario(final PaqueteUsuario paqueteUsuario) { this.paqueteUsuario = paqueteUsuario; } /** * Setea el paquete Personaje. * @param paquetePersonaje a setear. */ public void setPaquetePersonaje(final PaquetePersonaje paquetePersonaje) { this.paquetePersonaje = paquetePersonaje; } /** * Setea la ip. * @param ip a setear. */ public void setIp(final String ip) { this.ip = ip; } /** * Setea el menu de Cargar. * @param menuCarga a setear. */ public void setMenuCarga(final MenuCarga menuCarga) { this.menuCarga = menuCarga; } /** * Pide el menu comerciar. * @return el menu comerciar. */ public MenuComerciar getM1() { return m1; } /** * Setea el menu comerciar. * @param m1 a setear. */ public void setM1(final MenuComerciar m1) { this.m1 = m1; } /** * Pide el paquete comercio. * @return el paquete Comercio. */ public PaqueteComerciar getPaqueteComercio() { return paqueteComercio; } /** * Setea el paquete comercio. * @param paqueteComercio a setear. */ public void setPaqueteComercio(final PaqueteComerciar paqueteComercio) { this.paqueteComercio = paqueteComercio; } /** * Pide el paquete mensaje. * @return el paquete mensaje. */ public PaqueteMensaje getPaqMsj() { return paqueteMensaje; } /** * Setea el paquete mensaje. * @param paqueteMensaje a setear. */ public void setPaqueteMensaje(final PaqueteMensaje paqueteMensaje) { this.paqueteMensaje = paqueteMensaje; } }
package gui; import graph.Annotation; import graph.SequenceGraph; import graph.SequenceNode; import gui.sub_controllers.ColourController; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import java.util.*; public class GraphDrawer { private static GraphDrawer drawer = new GraphDrawer(); public static final double Y_BASE = 100; public static final double RELATIVE_X_DISTANCE = 0.8; public static final double RELATIVE_Y_DISTANCE = 50; public static final double LINE_WIDTH_FACTOR = 0.1; public static final double Y_SIZE_FACTOR = 3; public static final double LOG_BASE = 2; private Canvas canvas; private double zoomLevel; private double range; private double xDifference; private double yDifference; private double stepSize; private double[] columnWidths; private GraphicsContext gc; private ArrayList<ArrayList<SequenceNode>> columns; private SequenceGraph graph; private int highlightedNode; private int[] selected = null; private ColourController colourController; private ArrayList<Annotation> allAnnotations = new ArrayList<Annotation>(); private ArrayList<Annotation> selectedAnnotations = new ArrayList<Annotation>(); private SequenceNode mostLeftNode; private SequenceNode mostRightNode; private HashMap<Integer, double[]> coordinates; private boolean rainbowView = true; public static GraphDrawer getInstance() { return drawer; } public void setEmptyCoordinates() { this.coordinates = new HashMap<>(); } public HashMap<Integer, double[]> getCoordinates() { return this.coordinates; } public void setGraph(SequenceGraph graph) { this.graph = graph; columns = graph.getColumns(); columnWidths = new double[columns.size() + 1]; initializeColumnWidths(); initializeDummyWidths(); range = columnWidths[columns.size()]; if (zoomLevel == 0) { setZoomLevel(columnWidths[columns.size()]); } if (selected == null) { selected = new int[0]; } if (mostRightNode == null) { mostRightNode = graph.getNode(graph.getRightBoundID()); } colourController = new ColourController(selected, rainbowView); highlightedNode = 0; } public void setCanvas(Canvas canvas) { this.canvas = canvas; this.gc = canvas.getGraphicsContext2D(); } /** * Function what to do on Zoom. * * @param factor Zooming factor. * @param column The Column that has to be in the centre. */ public void zoom(final double factor, final int column) { setZoomLevel(zoomLevel * factor); if (zoomLevel != range / 2) { moveShapes(column - ((column - xDifference) * factor)); } } /** * Redraw all nodes with the same coordinates. */ public void redraw() { moveShapes(xDifference); } /** * Draws the Graph. * * @param xDifference Variable to determine which column should be in the centre. */ public void moveShapes(double xDifference) { gc.clearRect(0, 0, gc.getCanvas().getWidth(), gc.getCanvas().getHeight()); this.stepSize = (gc.getCanvas().getWidth() / zoomLevel); setxDifference(xDifference); colourController = new ColourController(selected, rainbowView); drawNodes(); drawMinimap(); } /** * Initializes the widths of each column. * Using the widest node of each column. */ private void initializeColumnWidths() { for (int j = 0; j < columns.size(); j++) { ArrayList<SequenceNode> column = columns.get(j); double max = 1; for (SequenceNode aColumn : column) { if (!aColumn.isDummy()) { double length = computeNodeWidth(aColumn); if (length > max) { max = length; } } } columnWidths[j + 1] = columnWidths[j] + max; } } /** * Method to initialize dummyWidths. */ private void initializeDummyWidths() { HashMap<Integer, String> genomes; for (int j = -1; j > graph.getDummyNodeIDCounter(); j genomes = new HashMap<>(DrawableCanvas.getInstance().getAllGenomesReversed()); SequenceNode node = graph.getNode(j); if (node.isDummy()) { for (SequenceNode i : columns.get(node.getColumn())) { if (!i.isDummy()) { for (int k : i.getGenomes()) { genomes.remove(k); } } } int[] genome = new int[genomes.size()]; int i = 0; for (Object o : genomes.entrySet()) { genome[i] = (int) ((Map.Entry) o).getKey(); i++; } int[] parentGenomes = graph.getNodes().get(node.getParents().get(0)).getGenomes(); int[] childList = getChildrenGenomeList(node); ArrayList<Integer> results = new ArrayList<>(); for (int aResult : genome) { if (contains(parentGenomes, aResult) & contains(childList, aResult)) { results.add(aResult); } } int[] result = results.stream().mapToInt(q -> q).toArray(); node.setGenomes(result); } } } /** * A simple contains method. * * @param checkSet The set to check if it contains the genome. * @param genome The genome to see if it is in the check set. * @return a boolean true if it is in the set or false if it is not. */ private boolean contains(int[] checkSet, int genome) { for (int check : checkSet) { if (check == genome) { return true; } } return false; } /** * * @param child Function that returns the genomes of first child that isn't Dummy. * @return the genomesList of the child */ private int[] getChildrenGenomeList(SequenceNode child) { while (child.isDummy()) { child = graph.getNodes().get(child.getChildren().get(0)); } return child.getGenomes(); } private boolean inView(double[] coordinates) { return coordinates[0] + coordinates[2] > 0 && coordinates[0] < gc.getCanvas().getWidth(); } /** * Computes the coordinates for the given node * [x,y,width,height] * @param node the node. * @return */ private double[] computeCoordinates(SequenceNode node) { double[] coordinates = new double[4]; double width = computeNodeWidth(node) * stepSize * RELATIVE_X_DISTANCE; double height = getYSize(); double x = (columnWidths[node.getColumn()] - xDifference) * stepSize; double y = Y_BASE + (node.getIndex() * RELATIVE_Y_DISTANCE) - yDifference; if (height > width) { y += (height - width) / 2; height = width; } coordinates[0] = x; coordinates[1] = y; coordinates[2] = width; coordinates[3] = height; return coordinates; } /** * Gives all nodes the right coordinates on the canvas and draw them. * It depends on whether the dummy nodes checkbox * is checked dummy nodes are either drawn or skipped. */ private void drawNodes() { setEmptyCoordinates(); gc.setStroke(Color.BLACK); Iterator it = graph.getNodes().entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); SequenceNode node = (SequenceNode) pair.getValue(); checkExtremeNode(node); drawNode(node); drawEdges(node); } } private void drawAnnotations(SequenceNode node, double[] coordinates) { for (int i = 0; i < selectedAnnotations.size(); i++) { Annotation annotation = selectedAnnotations.get(i); int annoID = DrawableCanvas.getInstance().getAnnotationGenome(); double startXAnno = coordinates[0]; double startYAnno = coordinates[1] + coordinates[3]; double annoWidth = coordinates[2]; double annoHeight = coordinates[3] / 2; int indexOfGenome = colourController.containsPos(node.getGenomes(), annoID); if (indexOfGenome != -1) { int startOfAnno = annotation.getStart(); int endOfAnno = annotation.getEnd(); int startCorOfGenome = 0; if (node.getGenomes().length == node.getOffsets().length) { startCorOfGenome = indexOfGenome; } if (startOfAnno > (node.getOffsets()[startCorOfGenome] + node.getSequenceLength()) || endOfAnno < (node.getOffsets()[startCorOfGenome])) { continue; } double emptyAtStart = 0.0; if (startOfAnno > node.getOffsets()[startCorOfGenome]) { emptyAtStart = startOfAnno - node.getOffsets()[startCorOfGenome]; annoWidth = (annoWidth * (1 - (emptyAtStart / node.getSequenceLength()))); startXAnno = startXAnno + (coordinates[2] - annoWidth); } if (endOfAnno < (node.getOffsets()[startCorOfGenome] + node.getSequenceLength())) { int emptyAtEnd = node.getOffsets()[startCorOfGenome] + node.getSequenceLength() - endOfAnno; annoWidth = (annoWidth * (1 - (emptyAtEnd / (node.getSequenceLength() - emptyAtStart)))); } gc.setFill(Color.RED); gc.fillRect(startXAnno, startYAnno, annoWidth, annoHeight); } } } private void checkExtremeNode(SequenceNode node) { double[] coordinates = getCoordinates(node); if (coordinates[0] <= 0 && coordinates[0] + coordinates[2] > 0) { mostLeftNode = node; } if (coordinates[0] < gc.getCanvas().getWidth() && coordinates[0] + coordinates[2] >= gc.getCanvas().getWidth()) { mostRightNode = node; } } private void drawNode(SequenceNode node) { double[] coordinates = this.getCoordinates().get(node.getId()); if (coordinates[0] <= 0 && coordinates[0] + coordinates[2] / RELATIVE_X_DISTANCE > 0) { mostLeftNode = node; } if (coordinates[0] <= gc.getCanvas().getWidth() && coordinates[0] + coordinates[2] / RELATIVE_X_DISTANCE >= gc.getCanvas().getWidth()) { mostRightNode = node; } if (inView(coordinates)) { if (node.isDummy()) { this.setLineWidth(node.getGenomes().length); gc.strokeLine(coordinates[0], coordinates[1] + coordinates[3] / 2, coordinates[0] + coordinates[2], coordinates[1] + coordinates[3] /2); } else { drawColour(node, coordinates); drawAnnotations(node, coordinates); } } } private void drawColour(SequenceNode node, double[] coordinates) { ArrayList<Color> colourMeBby; if (node.isHighlighted()) { gc.setLineWidth(6); gc.strokeRect(coordinates[0], coordinates[1], coordinates[2], coordinates[3]); } colourMeBby = colourController.getColors(node.getGenomes()); double tempCoordinate = coordinates[1]; double tempHeight = coordinates[3] / colourMeBby.size(); for (Color beamColour : colourMeBby) { gc.setFill(beamColour); gc.fillRect(coordinates[0], tempCoordinate, coordinates[2], tempHeight); tempCoordinate += tempHeight; } } private double[] getCoordinates(SequenceNode node) { if (this.getCoordinates().containsKey(node.getId())) { return this.getCoordinates().get(node.getId()); } else { this.getCoordinates().put(node.getId(), computeCoordinates(node)); return this.getCoordinates().get(node.getId()); } } private void drawEdges(SequenceNode node) { int nodeID = node.getId(); SequenceNode parent = graph.getNode(nodeID); double[] coordinatesParent = getCoordinates(node); for (int j = 0; j < parent.getChildren().size(); j++) { SequenceNode child = graph.getNode(parent.getChild(j)); double[] coordinatesChild = getCoordinates(child); double startx = coordinatesParent[0] + coordinatesParent[2]; double starty = coordinatesParent[1] + (coordinatesParent[3] / 2); double endx = coordinatesChild[0]; double endy = coordinatesChild[1] + (coordinatesChild[3] / 2); setLineWidth(Math.min(child.getGenomes().length, parent.getGenomes().length)); if (edgeInView(startx, endx)) { gc.strokeLine(startx, starty, endx, endy); } } } public void drawMinimap() { Minimap.getInstance().setValue(mostLeftNode.getId()); Minimap.getInstance().setAmountVisible(mostRightNode.getId() - mostLeftNode.getId()); Minimap.getInstance().draw(gc); } public boolean edgeInView(double startx, double endx) { return startx < gc.getCanvas().getWidth() && endx > 0; } private double computeNodeWidth(SequenceNode node) { if (node.isDummy()) { return columnWidths[node.getColumn() + 1] - columnWidths[node.getColumn()]; } return Math.log(node.getSequenceLength() + (LOG_BASE - 1)) / Math.log(LOG_BASE); } /** * Check for each node if the click event is within its borders. * If so highlight the node and return it. Also all other nodes are lowlighted. * * @param xEvent The x coordinate of the click event. * @param yEvent The y coordinate of the click event. * @return The sequencenode that has been clicked or null if nothing was clicked. */ public SequenceNode clickNode(double xEvent, double yEvent) { SequenceNode click = null; try { Iterator it = graph.getNodes().entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); SequenceNode node = (SequenceNode) pair.getValue(); if (checkClick(node, xEvent, yEvent)) { click = graph.getNode(node.getId()); highlight(node.getId()); } } } catch (NullPointerException e) { System.out.println("Graph not yet intialized"); } return click; } /** * Check if a click event is within the borders of this node. * * @param xEvent x coordinate of the click event * @param yEvent y coordinate of the click event * @return True if the coordinates of the click event are within borders, false otherwise. */ public boolean checkClick(SequenceNode node, double xEvent, double yEvent) { double[] coordinates = getCoordinates(node); return (xEvent > coordinates[0] && xEvent < coordinates[0] + coordinates[2] && yEvent > coordinates[1] && yEvent < coordinates[1] + coordinates[3]); } /** * Find the column corresponding to the x coordinate. * @param xEvent x coordinate of the click event. * @return The column id of the column the x coordinate is in. */ public int findColumn(double xEvent) { try { Iterator it = graph.getNodes().entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); SequenceNode node = (SequenceNode) pair.getValue(); int nodeID = (Integer) pair.getKey(); if (checkClickX(node, xEvent)) { int column = graph.getNode(nodeID).getColumn(); for (SequenceNode displayNode: graph.getColumns().get(column)) { if (!displayNode.isDummy()) { return displayNode.getId(); } } } } } catch (NullPointerException e) { System.out.println("No graph has been loaded."); } return -1; } /** * Check if a click event is within the borders of this node. * * @param xEvent x coordinate of the click event * @return True if the coordinates of the click event are within borders, false otherwise. */ public boolean checkClickX(SequenceNode node, double xEvent) { double[] coordinates = getCoordinates(node); return (xEvent > coordinates[0] && xEvent < coordinates[0] + coordinates[2]); } /** * Set the height of the node depending on the level of zoom. */ private double getYSize() { return Math.log(stepSize + 1) / Math.log(LOG_BASE) * Y_SIZE_FACTOR; } /** * Set the width of the line depending on the level of zoom. */ public void setLineWidth(double thickness) { double zoomWidth = Math.log(stepSize + 1) / Math.log(LOG_BASE) * LINE_WIDTH_FACTOR; double relativeSize = 100 * (thickness / (double) DrawableCanvas.getInstance().getAllGenomes().size()); double genomeWidth = Math.log(relativeSize + 1) / Math.log(LOG_BASE); gc.setLineWidth(genomeWidth * zoomWidth); } /** * Gets the real Centre Column. * * @return the Centre Column. */ private ArrayList<SequenceNode> getCentreColumn() { return columns.get(columns.size() / 2); } /** * Returns the First SequenceNode (not Dummy) Object from the centre Column. * * @return The Centre Node. */ public SequenceNode getRealCentreNode() { ArrayList<SequenceNode> set = getCentreColumn(); for (SequenceNode test : set) { return test; } return null; } /** * Highlights the centre node. * * @param node The node that should be highlighted */ public void highlight(int node) { if (highlightedNode != 0) { graph.getNode(highlightedNode).lowlight(); } graph.getNode(node).highlight(); highlightedNode = node; redraw(); } //TODO: Loop over the nodes in the graph (O(n*m) > O(k)) /** * Returns the ColumnId of a Node at the users Choice. * * @param nodeId The Id of the Node you want to find the Column of. * @return The ColumnId */ public int getColumnId(final int nodeId) { for (ArrayList<SequenceNode> list : columns) { for (SequenceNode node : list) { if (node.getId() == nodeId) { return node.getColumn(); } } } return -1; } public double findZoomLevel(int centreNode, int radius) { int rightNodeID = (int) (centreNode + (double) radius / 2.0); int leftNodeID = (int) (centreNode - (double) radius / 2.0); if (rightNodeID > graph.getFullGraphRightBoundID()) { rightNodeID = graph.getFullGraphRightBoundID(); mostRightNode = graph.getNode(graph.getFullGraphRightBoundID()); } if (leftNodeID < graph.getFullGraphLeftBoundID()) { leftNodeID = graph.getFullGraphLeftBoundID(); mostLeftNode = graph.getNode(graph.getFullGraphLeftBoundID()); } int rightColumn = graph.getNode(rightNodeID).getColumn(); int leftColumn = graph.getNode(leftNodeID).getColumn(); return columnWidths[rightColumn] - columnWidths[leftColumn]; } /** * Get function for zoom level. * * @return the Zoom level. */ public double getZoomLevel() { return zoomLevel; } public double getRange() { return range; } /** * Get function for x difference. * @return The x difference. */ public double getxDifference() { return xDifference; } public double getColumnWidth(int col) { return columnWidths[col]; } public double getRightbound() { return xDifference + zoomLevel; } public double getLeftbound() { return xDifference; } /** * Return the column the mouse click is in. * * @param x The x coordinate of the mouse click event * @return The id of the column that the mouse click is in. */ public int mouseLocationColumn(double x) { return (int) ((x / stepSize) + xDifference); } public void setSelected(int[] newSelection) { this.selected = newSelection; this.colourController = new ColourController(selected, rainbowView); } public int[] getSelected() { return selected; } public void setSelectedAnnotations(ArrayList<Annotation> newAnnotations) { this.selectedAnnotations = newAnnotations; } public void setAllAnnotations(ArrayList<Annotation> newAnnotations) { this.allAnnotations = newAnnotations; } public void setxDifference(double xDifference) { if (xDifference < 0) { xDifference = 0; } if (xDifference + zoomLevel > range) { xDifference = range - zoomLevel; } this.xDifference = xDifference; } public void setZoomLevel(double zoomLevel) { if (zoomLevel < 1) { zoomLevel = 1; } if (zoomLevel > range / 2) { zoomLevel = range / 2; } this.zoomLevel = zoomLevel; } public int getRadius() { return mostRightNode.getId() - mostLeftNode.getId(); } public SequenceGraph getGraph() { return graph; } public SequenceNode getMostLeftNode() { return mostLeftNode; } public ArrayList<Annotation> getAllAnnotations() { return allAnnotations; } public ArrayList<Annotation> getSelectedAnnotations() { return selectedAnnotations; } public SequenceNode getMostRightNode() { return mostRightNode; } public void setyDifference(double yDifference) { this.yDifference = yDifference; } public void setRainbowView(boolean rainbowView) { this.rainbowView = rainbowView; this.colourController = new ColourController(selected, rainbowView); } }
package info.cukes; import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @SuppressWarnings("JpaDataSourceORMInspection") @Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name= "book") private Long book; @Column(name = "title", nullable = false) private String title; @ManyToMany @JoinTable(name = "book_authors", joinColumns = @JoinColumn(name = "book"), inverseJoinColumns = @JoinColumn(name = "author")) private List<Author> bookAuthors = new ArrayList<>(); public Book() {} public Book(String bookTitle) { setTitle(bookTitle); } @SuppressWarnings("UnusedDeclaration") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @SuppressWarnings("UnusedDeclaration") public Long getBook() { return book; } private static Function<Book, String> extractTitles = new Function<Book, String>() { @Override public String apply(Book book) { return book.getTitle(); } }; public static List<String> getListOfTitles(List<Book> bookList) { List<String> titlesOfBooks = Lists.transform(bookList, extractTitles); return titlesOfBooks; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Book)) { return false; } Book book = (Book) o; return !(bookAuthors != null ? !bookAuthors.equals(book.bookAuthors) : book.bookAuthors != null) && title.equals(book.title); } @Override public int hashCode() { int result = title.hashCode(); result = 31 * result + (bookAuthors != null ? bookAuthors.hashCode() : 0); return result; } @Override public String toString() { return "Book{" + "book=" + book + ", title='" + title + '\'' + ", bookAuthors=" + bookAuthors + '}'; } }
package moxie; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; class GroupImpl implements Group, Verifiable { private final String name; private final InstantiationStackTrace whereInstantiated; private final Set<ExpectationImpl> unorderedExpectations = new HashSet<ExpectationImpl>(); private final List<ExpectationImpl> orderedExpectations = new ArrayList<ExpectationImpl>(); private boolean defaultCardinality; private CardinalityImpl cardinality; private int cursor; private int checkCursor; private MoxieFlags flags; GroupImpl(String name, MoxieFlags flags) { this.name = name; this.whereInstantiated = new InstantiationStackTrace("sequence \"" + name + "\" was instantiated here"); reset(flags); } public Cardinality<Group> willBeCalled() { if (!flags.isStrictlyOrdered()) { throw new IllegalStateException("cannot set cardinality on an unordered method group"); } if (!defaultCardinality) { throw new IllegalStateException("already specified number of times"); } defaultCardinality = false; CardinalityImpl<Group> result = new CardinalityImpl<Group>(this); cardinality = result; return result; } public void reset(MoxieFlags flags) { this.flags = flags; unorderedExpectations.clear(); orderedExpectations.clear(); defaultCardinality = true; cardinality = new CardinalityImpl<CardinalityImpl>().once(); cursor = 0; } public Throwable getWhereInstantiated() { return whereInstantiated; } public void add(ExpectationImpl expectation) { if (flags.isStrictlyOrdered() && !expectation.isUnordered()) { orderedExpectations.add(expectation); } else { unorderedExpectations.add(expectation); } } public void verify() { for (ExpectationImpl expectation : unorderedExpectations) { if (!expectation.isSatisfied()) { // TODO nicer exception throw new MoxieError("not all methods in expectation invoked"); } } if (!orderedExpectations.isEmpty()) { if (cursor == orderedExpectations.size() - 1 && orderedExpectations.get(cursor).isSatisfied()) { cursor = 0; cardinality.incrementCount(); } if (cursor == 0 && cardinality.isSatisfied()) { return; } // TODO nicer exception throw new MoxieError("not all expected methods invoked or cardinality not satisfied"); } } public ExpectationImpl match(Method method, Object[] args, MethodBehavior behavior) { ExpectationImpl result = null; for (ExpectationImpl expectation : unorderedExpectations) { if (expectation.match(method, args, behavior)) { result = expectation; break; } } if (result == null && !orderedExpectations.isEmpty()) { if (cardinality.isViable()) { if (orderedExpectations.get(cursor).match(method, args, behavior)) { result = orderedExpectations.get(cursor); } else { cursor++; if (cursor == orderedExpectations.size()) { cursor = 0; cardinality.incrementCount(); } if (cardinality.isViable() && orderedExpectations.get(cursor).match(method, args, behavior)) { result = orderedExpectations.get(cursor); } } } } if (result != null) { for (GroupImpl group : (Set<GroupImpl>) result.getGroups()) { group.match(result); } } return result; } public void match(ExpectationImpl expectation) { if (!orderedExpectations.isEmpty()) { if (cardinality.isViable()) { if (orderedExpectations.get(cursor) == expectation) { return; } cursor++; if (cursor == orderedExpectations.size()) { cursor = 0; cardinality.incrementCount(); } if (cardinality.isViable() && orderedExpectations.get(cursor) == expectation) { return; } } // TODO nicer exception throw new MoxieError("out of sequence expectation or too many times through sequence"); } } int getCheckCursor() { return checkCursor; } void setCheckCursor(int checkCursor) { this.checkCursor = checkCursor; } boolean isStrictlyOrdered() { return flags.isStrictlyOrdered(); } }
package mtr.data; import mtr.block.BlockPSDAPGBase; import mtr.block.BlockPSDAPGDoorBase; import mtr.block.BlockPlatform; import mtr.config.CustomResources; import mtr.packet.IPacket; import mtr.path.PathData; import mtr.path.PathFinder; import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.MovementType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.sound.SoundCategory; import net.minecraft.util.Pair; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Box; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import java.util.*; import java.util.function.Consumer; public class Siding extends SavedRailBase implements IPacket { private World world; private Depot depot; private CustomResources.TrainMapping trainTypeMapping; private int trainLength; private boolean unlimitedTrains; private final float railLength; private final List<PathData> path = new ArrayList<>(); private final List<Float> distances = new ArrayList<>(); private final Set<Train> trains = new HashSet<>(); public static final float ACCELERATION = 0.01F; public static final String KEY_TRAINS = "trains"; private static final String KEY_RAIL_LENGTH = "rail_length"; private static final String KEY_TRAIN_TYPE = "train_type"; private static final String KEY_TRAIN_CUSTOM_ID = "train_custom_id"; private static final String KEY_UNLIMITED_TRAINS = "unlimited_trains"; private static final String KEY_PATH = "path"; public Siding(long id, BlockPos pos1, BlockPos pos2, float railLength) { super(id, pos1, pos2); this.railLength = railLength; setTrainDetails("", TrainType.values()[0]); } public Siding(BlockPos pos1, BlockPos pos2, float railLength) { super(pos1, pos2); this.railLength = railLength; setTrainDetails("", TrainType.values()[0]); } public Siding(NbtCompound nbtCompound) { super(nbtCompound); railLength = nbtCompound.getFloat(KEY_RAIL_LENGTH); TrainType trainType = TrainType.values()[0]; try { trainType = TrainType.valueOf(nbtCompound.getString(KEY_TRAIN_TYPE)); } catch (Exception ignored) { } setTrainDetails(nbtCompound.getString(KEY_TRAIN_CUSTOM_ID), trainType); unlimitedTrains = nbtCompound.getBoolean(KEY_UNLIMITED_TRAINS); final NbtCompound tagPath = nbtCompound.getCompound(KEY_PATH); final int pathCount = tagPath.getKeys().size(); for (int i = 0; i < pathCount; i++) { path.add(new PathData(tagPath.getCompound(KEY_PATH + i))); } generateDistances(); final NbtCompound tagTrains = nbtCompound.getCompound(KEY_TRAINS); tagTrains.getKeys().forEach(key -> trains.add(new Train(id, railLength, path, distances, tagTrains.getCompound(key)))); } public Siding(PacketByteBuf packet) { super(packet); railLength = packet.readFloat(); setTrainDetails(packet.readString(PACKET_STRING_READ_LENGTH), TrainType.values()[packet.readInt()]); unlimitedTrains = packet.readBoolean(); final int pathCount = packet.readInt(); for (int i = 0; i < pathCount; i++) { path.add(new PathData(packet)); } generateDistances(); final int trainCount = packet.readInt(); for (int i = 0; i < trainCount; i++) { trains.add(new Train(id, railLength, path, distances, packet)); } } @Override public NbtCompound toCompoundTag() { final NbtCompound nbtCompound = super.toCompoundTag(); nbtCompound.putFloat(KEY_RAIL_LENGTH, railLength); nbtCompound.putString(KEY_TRAIN_CUSTOM_ID, trainTypeMapping.customId); nbtCompound.putString(KEY_TRAIN_TYPE, trainTypeMapping.trainType.toString()); nbtCompound.putBoolean(KEY_UNLIMITED_TRAINS, unlimitedTrains); RailwayData.writeTag(nbtCompound, path, KEY_PATH); RailwayData.writeTag(nbtCompound, trains, KEY_TRAINS); return nbtCompound; } @Override public void writePacket(PacketByteBuf packet) { super.writePacket(packet); packet.writeFloat(railLength); packet.writeString(trainTypeMapping.customId); packet.writeInt(trainTypeMapping.trainType.ordinal()); packet.writeBoolean(unlimitedTrains); packet.writeInt(path.size()); path.forEach(pathData -> pathData.writePacket(packet)); packet.writeInt(trains.size()); trains.forEach(train -> train.writePacket(packet)); } @Override public void update(String key, PacketByteBuf packet) { switch (key) { case KEY_TRAIN_TYPE: setTrainDetails(packet.readString(PACKET_STRING_READ_LENGTH), TrainType.values()[packet.readInt()]); break; case KEY_UNLIMITED_TRAINS: unlimitedTrains = packet.readBoolean(); break; case KEY_TRAINS: final boolean isRemove = packet.readBoolean(); if (isRemove) { final int trainCount = packet.readInt(); final Set<Long> trainIds = new HashSet<>(); for (int i = 0; i < trainCount; i++) { trainIds.add(packet.readLong()); } trains.removeIf(train -> !trainIds.contains(train.id)); } else { final long trainId = packet.readLong(); boolean updated = false; for (final Train train : trains) { if (train.id == trainId) { train.update(KEY_TRAINS, packet); updated = true; break; } } if (!updated) { final Train newTrain = new Train(null, trainId, id, railLength, path, distances); trains.add(newTrain); newTrain.update(KEY_TRAINS, packet); } } break; case KEY_PATH: final int pathSize = packet.readInt(); path.clear(); for (int i = 0; i < pathSize; i++) { path.add(new PathData(packet)); } generateDistances(); break; default: super.update(key, packet); break; } } public void setTrainTypeMapping(String customId, TrainType trainType, Consumer<PacketByteBuf> sendPacket) { final PacketByteBuf packet = PacketByteBufs.create(); packet.writeLong(id); packet.writeString(KEY_TRAIN_TYPE); packet.writeString(customId); packet.writeInt(trainType.ordinal()); sendPacket.accept(packet); setTrainDetails(customId, trainType); } public void setUnlimitedTrains(boolean unlimitedTrains, Consumer<PacketByteBuf> sendPacket) { final PacketByteBuf packet = PacketByteBufs.create(); packet.writeLong(id); packet.writeString(KEY_UNLIMITED_TRAINS); packet.writeBoolean(unlimitedTrains); sendPacket.accept(packet); this.unlimitedTrains = unlimitedTrains; } public CustomResources.TrainMapping getTrainTypeMapping() { return trainTypeMapping; } public void setSidingData(World world, Depot depot, Map<BlockPos, Map<BlockPos, Rail>> rails) { this.world = world; this.depot = depot; if (depot == null) { trains.clear(); path.clear(); distances.clear(); } else if (path.isEmpty()) { generateDefaultPath(rails); generateDistances(); } } public int generateRoute(List<PathData> mainPath, int successfulSegmentsMain, Map<BlockPos, Map<BlockPos, Rail>> rails, SavedRailBase firstPlatform, SavedRailBase lastPlatform) { final int successfulSegments; if (firstPlatform == null || lastPlatform == null) { successfulSegments = 0; } else { final List<SavedRailBase> depotAndFirstPlatform = new ArrayList<>(); depotAndFirstPlatform.add(this); depotAndFirstPlatform.add(firstPlatform); PathFinder.findPath(path, rails, depotAndFirstPlatform, 0); if (path.isEmpty()) { successfulSegments = 1; } else if (mainPath.isEmpty()) { path.clear(); successfulSegments = successfulSegmentsMain + 1; } else { PathFinder.appendPath(path, mainPath); final List<SavedRailBase> lastPlatformAndDepot = new ArrayList<>(); lastPlatformAndDepot.add(lastPlatform); lastPlatformAndDepot.add(this); final List<PathData> pathLastPlatformToDepot = new ArrayList<>(); PathFinder.findPath(pathLastPlatformToDepot, rails, lastPlatformAndDepot, successfulSegmentsMain); if (pathLastPlatformToDepot.isEmpty()) { successfulSegments = successfulSegmentsMain + 1; path.clear(); } else { PathFinder.appendPath(path, pathLastPlatformToDepot); successfulSegments = successfulSegmentsMain + 2; } } } if (path.isEmpty()) { generateDefaultPath(rails); } generateDistances(); final PacketByteBuf packet = PacketByteBufs.create(); packet.writeLong(id); packet.writeString(KEY_PATH); packet.writeInt(path.size()); path.forEach(pathData -> pathData.writePacket(packet)); if (packet.readableBytes() <= MAX_PACKET_BYTES) { world.getPlayers().forEach(player -> ServerPlayNetworking.send((ServerPlayerEntity) player, PACKET_UPDATE_SIDING, packet)); } return successfulSegments; } public void simulateTrain(PlayerEntity clientPlayer, float ticksElapsed, List<Set<UUID>> trainPositions, RenderTrainCallback renderTrainCallback, RenderConnectionCallback renderConnectionCallback, SpeedCallback speedCallback, AnnouncementCallback announcementCallback, WriteScheduleCallback writeScheduleCallback) { if (depot == null) { return; } int trainsAtDepot = 0; boolean spawnTrain = true; final Set<Integer> railProgressSet = new HashSet<>(); final Set<Train> trainsToRemove = new HashSet<>(); for (final Train train : trains) { train.simulateTrain(world, clientPlayer, ticksElapsed, depot, trainTypeMapping, trainLength, trainPositions == null ? null : trainPositions.get(0), renderTrainCallback, renderConnectionCallback, speedCallback, announcementCallback, writeScheduleCallback); if (train.closeToDepot(trainTypeMapping.trainType.getSpacing() * trainLength)) { spawnTrain = false; } if (!train.isOnRoute) { trainsAtDepot++; if (trainsAtDepot > 1) { trainsToRemove.add(train); } } final int roundedRailProgress = Math.round(train.railProgress * 10); if (railProgressSet.contains(roundedRailProgress)) { trainsToRemove.add(train); } railProgressSet.add(roundedRailProgress); if (trainPositions != null) { train.writeTrainPositions(trainPositions.get(1), trainTypeMapping, trainLength); } } if (world != null && !world.isClient()) { if (trains.isEmpty() || unlimitedTrains && spawnTrain) { trains.add(new Train(world, new Random().nextLong(), id, railLength, path, distances)); } if (!trainsToRemove.isEmpty()) { trainsToRemove.forEach(trains::remove); final PacketByteBuf packet = PacketByteBufs.create(); packet.writeLong(id); packet.writeString(KEY_TRAINS); packet.writeBoolean(true); packet.writeInt(trains.size()); trains.forEach(train -> packet.writeLong(train.id)); world.getPlayers().forEach(serverPlayer -> ServerPlayNetworking.send((ServerPlayerEntity) serverPlayer, PACKET_UPDATE_SIDING, packet)); } } } public boolean getUnlimitedTrains() { return unlimitedTrains; } private void setTrainDetails(String customId, TrainType trainType) { trainTypeMapping = new CustomResources.TrainMapping(customId, trainType); trainLength = (int) Math.floor(railLength / trainTypeMapping.trainType.getSpacing()); } private void generateDefaultPath(Map<BlockPos, Map<BlockPos, Rail>> rails) { trains.clear(); final List<BlockPos> orderedPositions = getOrderedPositions(new BlockPos(0, 0, 0), false); final BlockPos pos1 = orderedPositions.get(0); final BlockPos pos2 = orderedPositions.get(1); if (RailwayData.containsRail(rails, pos1, pos2)) { path.add(new PathData(rails.get(pos1).get(pos2), id, 0, pos1, pos2, -1)); } if (depot != null) { depot.clientPathGenerationSuccessfulSegments = 0; } trains.add(new Train(null, 0, id, railLength, path, distances)); } private void generateDistances() { distances.clear(); float sum = 0; for (final PathData pathData : path) { sum += pathData.rail.getLength(); distances.add(sum); } if (path.size() != 1) { trains.removeIf(train -> (train.id == 0) == unlimitedTrains); } } private static class Train extends NameColorDataBase implements IPacket, IGui { private float speed; private float railProgress; private float stopCounter; private int nextStoppingIndex; private boolean reversed; private boolean isOnRoute = false; private float clientPercentageX; private float clientPercentageZ; private float clientPrevYaw; private final long sidingId; private final float railLength; private final List<PathData> path; private final List<Float> distances; private final Set<UUID> ridingEntities = new HashSet<>(); private static final String KEY_SPEED = "speed"; private static final String KEY_RAIL_PROGRESS = "rail_progress"; private static final String KEY_STOP_COUNTER = "stop_counter"; private static final String KEY_NEXT_STOPPING_INDEX = "next_stopping_index"; private static final String KEY_REVERSED = "reversed"; private static final String KEY_IS_ON_ROUTE = "is_on_route"; private static final String KEY_RIDING_ENTITIES = "riding_entities"; private static final int DOOR_DELAY = 20; private static final int DOOR_MOVE_TIME = 64; private static final int DOOR_MAX_DISTANCE = 32; private static final float INNER_PADDING = 0.5F; private static final int BOX_PADDING = 3; private static final float CONNECTION_HEIGHT = 2.25F; private static final float CONNECTION_Z_OFFSET = 0.5F; private static final float CONNECTION_X_OFFSET = 0.25F; private Train(World world, long id, long sidingId, float railLength, List<PathData> path, List<Float> distances) { super(id); this.sidingId = sidingId; this.railLength = railLength; this.path = path; this.distances = distances; syncTrainToClient(world, null, 0, 0); } private Train(long sidingId, float railLength, List<PathData> path, List<Float> distances, NbtCompound nbtCompound) { super(nbtCompound); this.sidingId = sidingId; this.railLength = railLength; this.path = path; this.distances = distances; speed = nbtCompound.getFloat(KEY_SPEED); railProgress = nbtCompound.getFloat(KEY_RAIL_PROGRESS); stopCounter = nbtCompound.getFloat(KEY_STOP_COUNTER); nextStoppingIndex = nbtCompound.getInt(KEY_NEXT_STOPPING_INDEX); reversed = nbtCompound.getBoolean(KEY_REVERSED); isOnRoute = nbtCompound.getBoolean(KEY_IS_ON_ROUTE); final NbtCompound tagRidingEntities = nbtCompound.getCompound(KEY_RIDING_ENTITIES); tagRidingEntities.getKeys().forEach(key -> ridingEntities.add(tagRidingEntities.getUuid(key))); } private Train(long sidingId, float railLength, List<PathData> path, List<Float> distances, PacketByteBuf packet) { super(packet); this.sidingId = sidingId; this.railLength = railLength; this.path = path; this.distances = distances; speed = packet.readFloat(); railProgress = packet.readFloat(); stopCounter = packet.readFloat(); nextStoppingIndex = packet.readInt(); reversed = packet.readBoolean(); isOnRoute = packet.readBoolean(); final int ridingEntitiesCount = packet.readInt(); for (int i = 0; i < ridingEntitiesCount; i++) { ridingEntities.add(packet.readUuid()); } } @Override public NbtCompound toCompoundTag() { final NbtCompound nbtCompound = super.toCompoundTag(); nbtCompound.putFloat(KEY_SPEED, speed); nbtCompound.putFloat(KEY_RAIL_PROGRESS, railProgress); nbtCompound.putFloat(KEY_STOP_COUNTER, stopCounter); nbtCompound.putInt(KEY_NEXT_STOPPING_INDEX, nextStoppingIndex); nbtCompound.putBoolean(KEY_REVERSED, reversed); nbtCompound.putBoolean(KEY_IS_ON_ROUTE, isOnRoute); final NbtCompound tagRidingEntities = new NbtCompound(); ridingEntities.forEach(uuid -> tagRidingEntities.putUuid(KEY_RIDING_ENTITIES + uuid, uuid)); nbtCompound.put(KEY_RIDING_ENTITIES, tagRidingEntities); return nbtCompound; } @Override public void writePacket(PacketByteBuf packet) { super.writePacket(packet); writeMainPacket(packet); } @Override public void update(String key, PacketByteBuf packet) { if (key.equals(Siding.KEY_TRAINS)) { speed = packet.readFloat(); final float tempRailProgress = packet.readFloat(); if (speed <= ACCELERATION) { railProgress = tempRailProgress; } stopCounter = packet.readFloat(); nextStoppingIndex = packet.readInt(); reversed = packet.readBoolean(); isOnRoute = packet.readBoolean(); ridingEntities.clear(); final int ridingEntitiesCount = packet.readInt(); for (int i = 0; i < ridingEntitiesCount; i++) { ridingEntities.add(packet.readUuid()); } final float percentageX = packet.readFloat(); final float percentageZ = packet.readFloat(); if (percentageX != 0) { clientPercentageX = percentageX; clientPercentageZ = percentageZ; } } else { super.update(key, packet); } } private boolean closeToDepot(int trainDistance) { return !isOnRoute || railProgress < trainDistance + railLength; } private void writeTrainPositions(Set<UUID> trainPositions, CustomResources.TrainMapping trainTypeMapping, int trainLength) { if (!path.isEmpty()) { final int trainSpacing = trainTypeMapping.trainType.getSpacing(); final int headIndex = getIndex(0, trainSpacing, true); final int tailIndex = getIndex(trainLength, trainSpacing, false); for (int i = tailIndex; i <= headIndex; i++) { if (i > 0 && path.get(i).savedRailBaseId != sidingId) { trainPositions.add(path.get(i).getRailProduct()); } } } } private void simulateTrain(World world, PlayerEntity clientPlayer, float ticksElapsed, Depot depot, CustomResources.TrainMapping trainTypeMapping, int trainLength, Set<UUID> trainPositions, RenderTrainCallback renderTrainCallback, RenderConnectionCallback renderConnectionCallback, SpeedCallback speedCallback, AnnouncementCallback announcementCallback, WriteScheduleCallback writeScheduleCallback) { if (world == null) { return; } final int oldStoppingIndex = nextStoppingIndex; final int oldPassengerCount = ridingEntities.size(); try { final int trainSpacing = trainTypeMapping.trainType.getSpacing(); final float oldRailProgress = railProgress; final float oldSpeed = speed; final float oldDoorValue; final float doorValueRaw; if (!isOnRoute) { railProgress = (railLength + trainLength * trainSpacing) / 2; oldDoorValue = 0; doorValueRaw = 0; speed = 0; if (path.size() > 1 && depot != null && depot.deployTrain(world)) { if (!world.isClient()) { isOnRoute = true; nextStoppingIndex = 0; startUp(world, trainLength, trainSpacing); } } } else { oldDoorValue = nextStoppingIndex < path.size() ? Math.abs(getDoorValue()) : 0; final float newAcceleration = ACCELERATION * ticksElapsed; if (railProgress >= distances.get(distances.size() - 1) - (railLength - trainLength * trainSpacing) / 2) { isOnRoute = false; ridingEntities.clear(); doorValueRaw = 0; } else { if (speed <= 0) { speed = 0; final int dwellTicks = path.get(nextStoppingIndex).dwellTime * 10; if (dwellTicks == 0) { doorValueRaw = 0; } else { stopCounter += ticksElapsed; doorValueRaw = getDoorValue(); } if (stopCounter >= dwellTicks && !railBlocked(trainPositions, getIndex(0, trainSpacing, true) + (isOppositeRail() ? 2 : 1))) { startUp(world, trainLength, trainSpacing); } } else { if (!world.isClient()) { final int checkIndex = getIndex(0, trainSpacing, true) + 1; if (railBlocked(trainPositions, checkIndex)) { nextStoppingIndex = checkIndex - 1; } } final float stoppingDistance = distances.get(nextStoppingIndex) - railProgress; if (stoppingDistance < 0.5F * speed * speed / ACCELERATION) { speed = Math.max(speed - (0.5F * speed * speed / stoppingDistance) * ticksElapsed, ACCELERATION); } else { final float railSpeed = path.get(getIndex(0, trainSpacing, false)).rail.railType.maxBlocksPerTick; if (speed < railSpeed) { speed = Math.min(speed + newAcceleration, railSpeed); } else if (speed > railSpeed) { speed = Math.max(speed - newAcceleration, railSpeed); } } doorValueRaw = 0; } railProgress += speed * ticksElapsed; if (railProgress > distances.get(nextStoppingIndex)) { railProgress = distances.get(nextStoppingIndex); speed = 0; } } } final Pos3f[] positions = new Pos3f[trainLength + 1]; for (int i = 0; i <= trainLength; i++) { positions[i] = getRoutePosition(reversed ? trainLength - i : i, trainSpacing); } if (!path.isEmpty() && depot != null) { final List<Vec3d> offset = new ArrayList<>(); if (clientPlayer != null && ridingEntities.contains(clientPlayer.getUuid())) { final int headIndex = getIndex(0, trainSpacing, false); if (speedCallback != null) { speedCallback.speedCallback(speed * 20, path.get(headIndex).stopIndex - 1, depot.routeIds); } if (announcementCallback != null) { float targetProgress = distances.get(getPreviousStoppingIndex(headIndex)) + (trainLength + 1) * trainSpacing; if (oldRailProgress < targetProgress && railProgress >= targetProgress) { announcementCallback.announcementCallback(path.get(headIndex).stopIndex - 1, depot.routeIds); } } calculateRender(world, positions, (int) Math.floor(clientPercentageZ), Math.abs(doorValueRaw), (x, y, z, yaw, pitch, realSpacing, doorLeftOpen, doorRightOpen) -> { final Vec3d movement = new Vec3d(clientPlayer.sidewaysSpeed * ticksElapsed / 4, 0, clientPlayer.forwardSpeed * ticksElapsed / 4).rotateY((float) -Math.toRadians(clientPlayer.yaw) - yaw); final boolean shouldRenderConnection = trainTypeMapping.trainType.shouldRenderConnection; clientPercentageX += movement.x / trainTypeMapping.trainType.width; clientPercentageZ += movement.z / realSpacing; clientPercentageX = MathHelper.clamp(clientPercentageX, doorLeftOpen ? -1 : 0, doorRightOpen ? 2 : 1); clientPercentageZ = MathHelper.clamp(clientPercentageZ, (shouldRenderConnection ? 0 : (int) Math.floor(clientPercentageZ) + 0.05F) + 0.01F, (shouldRenderConnection ? trainLength : (int) Math.floor(clientPercentageZ) + 0.95F) - 0.01F); clientPlayer.fallDistance = 0; clientPlayer.setVelocity(0, 0, 0); final Vec3d playerOffset = new Vec3d(getValueFromPercentage(clientPercentageX, trainTypeMapping.trainType.width), 0, getValueFromPercentage(MathHelper.fractionalPart(clientPercentageZ), realSpacing)).rotateX(pitch).rotateY(yaw).add(x, y, z); clientPlayer.move(MovementType.SELF, playerOffset.subtract(clientPlayer.getPos())); if (speed > 0) { clientPlayer.yaw -= Math.toDegrees(yaw - clientPrevYaw); offset.add(playerOffset.add(0, clientPlayer.getStandingEyeHeight(), 0)); } clientPrevYaw = yaw; }); } render(world, positions, doorValueRaw, oldSpeed, oldDoorValue, trainTypeMapping, trainLength, renderTrainCallback, renderConnectionCallback, offset.isEmpty() ? null : offset.get(0)); } if (world.isClient() && depot != null && writeScheduleCallback != null) { writeArrivalTimes(writeScheduleCallback, depot.routeIds, trainTypeMapping, trainSpacing); } } catch (Exception ignored) { } if (oldPassengerCount > ridingEntities.size() || oldStoppingIndex != nextStoppingIndex) { syncTrainToClient(world, null, 0, 0); } } private void startUp(World world, int trainLength, int trainSpacing) { if (!world.isClient()) { stopCounter = 0; speed = ACCELERATION; if (isOppositeRail()) { railProgress += trainLength * trainSpacing; reversed = !reversed; } nextStoppingIndex = getNextStoppingIndex(trainSpacing); } } private void render(World world, Pos3f[] positions, float doorValueRaw, float oldSpeed, float oldDoorValue, CustomResources.TrainMapping trainTypeMapping, int trainLength, RenderTrainCallback renderTrainCallback, RenderConnectionCallback renderConnectionCallback, Vec3d offset) { final TrainType trainType = trainTypeMapping.trainType; final float doorValue = Math.abs(doorValueRaw); final boolean opening = doorValueRaw > 0; final float[] xList = new float[trainLength]; final float[] yList = new float[trainLength]; final float[] zList = new float[trainLength]; final float[] yawList = new float[trainLength]; final float[] pitchList = new float[trainLength]; final float[] realSpacingList = new float[trainLength]; final boolean[] doorLeftOpenList = new boolean[trainLength]; final boolean[] doorRightOpenList = new boolean[trainLength]; for (int i = 0; i < trainLength; i++) { final int ridingCar = i; calculateRender(world, positions, i, doorValue, (x, y, z, yaw, pitch, realSpacing, doorLeftOpen, doorRightOpen) -> { xList[ridingCar] = x; yList[ridingCar] = y; zList[ridingCar] = z; yawList[ridingCar] = yaw; pitchList[ridingCar] = pitch; realSpacingList[ridingCar] = realSpacing; doorLeftOpenList[ridingCar] = doorLeftOpen; doorRightOpenList[ridingCar] = doorRightOpen; }); } for (int i = 0; i < xList.length; i++) { final int ridingCar = i; final float x = xList[i]; final float y = yList[i]; final float z = zList[i]; final float yaw = yawList[i]; final float pitch = pitchList[i]; final float realSpacing = realSpacingList[i]; final boolean doorLeftOpen = doorLeftOpenList[i]; final boolean doorRightOpen = doorRightOpenList[i]; final float halfSpacing = realSpacing / 2; final float halfWidth = trainType.width / 2F; if (world.isClient()) { final float newX = x - (offset == null ? 0 : (float) offset.x); final float newY = y - (offset == null ? 0 : (float) offset.y); final float newZ = z - (offset == null ? 0 : (float) offset.z); if (renderTrainCallback != null) { renderTrainCallback.renderTrainCallback(newX, newY, newZ, yaw, pitch, trainTypeMapping.customId, trainType, i == 0, i == trainLength - 1, !reversed, doorLeftOpen ? doorValue : 0, doorRightOpen ? doorValue : 0, opening, isOnRoute, offset != null); } if (renderConnectionCallback != null && i > 0 && trainType.shouldRenderConnection) { final float prevCarX = xList[i - 1] - (offset == null ? 0 : (float) offset.x); final float prevCarY = yList[i - 1] - (offset == null ? 0 : (float) offset.y); final float prevCarZ = zList[i - 1] - (offset == null ? 0 : (float) offset.z); final float prevCarYaw = yawList[i - 1]; final float prevCarPitch = pitchList[i - 1]; final float xStart = halfWidth - CONNECTION_X_OFFSET; final float zStart = trainType.getSpacing() / 2F - CONNECTION_Z_OFFSET; final Pos3f prevPos1 = new Pos3f(xStart, SMALL_OFFSET, zStart).rotateX(prevCarPitch).rotateY(prevCarYaw).add(prevCarX, prevCarY, prevCarZ); final Pos3f prevPos2 = new Pos3f(xStart, CONNECTION_HEIGHT + SMALL_OFFSET, zStart).rotateX(prevCarPitch).rotateY(prevCarYaw).add(prevCarX, prevCarY, prevCarZ); final Pos3f prevPos3 = new Pos3f(-xStart, CONNECTION_HEIGHT + SMALL_OFFSET, zStart).rotateX(prevCarPitch).rotateY(prevCarYaw).add(prevCarX, prevCarY, prevCarZ); final Pos3f prevPos4 = new Pos3f(-xStart, SMALL_OFFSET, zStart).rotateX(prevCarPitch).rotateY(prevCarYaw).add(prevCarX, prevCarY, prevCarZ); final Pos3f thisPos1 = new Pos3f(-xStart, SMALL_OFFSET, -zStart).rotateX(pitch).rotateY(yaw).add(newX, newY, newZ); final Pos3f thisPos2 = new Pos3f(-xStart, CONNECTION_HEIGHT + SMALL_OFFSET, -zStart).rotateX(pitch).rotateY(yaw).add(newX, newY, newZ); final Pos3f thisPos3 = new Pos3f(xStart, CONNECTION_HEIGHT + SMALL_OFFSET, -zStart).rotateX(pitch).rotateY(yaw).add(newX, newY, newZ); final Pos3f thisPos4 = new Pos3f(xStart, SMALL_OFFSET, -zStart).rotateX(pitch).rotateY(yaw).add(newX, newY, newZ); renderConnectionCallback.renderConnectionCallback(prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, newX, newY, newZ, trainType, isOnRoute, offset != null); } } else { final BlockPos soundPos = new BlockPos(x, y, z); trainType.playSpeedSoundEffect(world, soundPos, oldSpeed, speed); if (doorLeftOpen || doorRightOpen) { if (oldDoorValue <= 0 && doorValue > 0 && trainType.doorOpenSoundEvent != null) { world.playSound(null, soundPos, trainType.doorOpenSoundEvent, SoundCategory.BLOCKS, 1, 1); } else if (oldDoorValue >= trainType.doorCloseSoundTime && doorValue < trainType.doorCloseSoundTime && trainType.doorCloseSoundEvent != null) { world.playSound(null, soundPos, trainType.doorCloseSoundEvent, SoundCategory.BLOCKS, 1, 1); } final float margin = halfSpacing + BOX_PADDING; world.getEntitiesByClass(PlayerEntity.class, new Box(x + margin, y + margin, z + margin, x - margin, y - margin, z - margin), player -> !player.isSpectator() && !ridingEntities.contains(player.getUuid())).forEach(player -> { final Vec3d positionRotated = player.getPos().subtract(x, y, z).rotateY(-yaw).rotateX(-pitch); if (Math.abs(positionRotated.x) < halfWidth + INNER_PADDING && Math.abs(positionRotated.y) < 1.5 && Math.abs(positionRotated.z) <= halfSpacing) { ridingEntities.add(player.getUuid()); syncTrainToClient(world, player, (float) (positionRotated.x / trainType.width + 0.5), (float) (positionRotated.z / realSpacing + 0.5) + ridingCar); } }); } final RailwayData railwayData = RailwayData.getInstance(world); final Set<UUID> entitiesToRemove = new HashSet<>(); ridingEntities.forEach(uuid -> { final PlayerEntity player = world.getPlayerByUuid(uuid); if (player != null) { final Vec3d positionRotated = player.getPos().subtract(x, y, z).rotateY(-yaw).rotateX(-pitch); if (player.isSpectator() || player.isSneaking() || (doorLeftOpen || doorRightOpen) && Math.abs(positionRotated.z) <= halfSpacing && (Math.abs(positionRotated.x) > halfWidth + INNER_PADDING || Math.abs(positionRotated.y) > 1.5)) { entitiesToRemove.add(uuid); } if (railwayData != null) { railwayData.updatePlayerRiding(player); } } }); if (!entitiesToRemove.isEmpty()) { entitiesToRemove.forEach(ridingEntities::remove); } } } } private void calculateRender(World world, Pos3f[] positions, int index, float doorValue, CalculateRenderCallback calculateRenderCallback) { final Pos3f pos1 = positions[index]; final Pos3f pos2 = positions[index + 1]; if (pos1 != null && pos2 != null) { final float x = getAverage(pos1.x, pos2.x); final float y = getAverage(pos1.y, pos2.y) + 1; final float z = getAverage(pos1.z, pos2.z); final float realSpacing = pos2.getDistanceTo(pos1); final float yaw = (float) MathHelper.atan2(pos2.x - pos1.x, pos2.z - pos1.z); final float pitch = realSpacing == 0 ? 0 : (float) Math.asin((pos2.y - pos1.y) / realSpacing); final boolean doorLeftOpen = openDoors(world, x, y, z, (float) Math.PI + yaw, pitch, realSpacing / 2, doorValue) && doorValue > 0; final boolean doorRightOpen = openDoors(world, x, y, z, yaw, pitch, realSpacing / 2, doorValue) && doorValue > 0; calculateRenderCallback.calculateRenderCallback(x, y, z, yaw, pitch, realSpacing, doorLeftOpen, doorRightOpen); } } private boolean railBlocked(Set<UUID> trainPositions, int checkIndex) { if (trainPositions != null && checkIndex < path.size()) { return trainPositions.contains(path.get(checkIndex).getRailProduct()); } else { return false; } } private boolean isOppositeRail() { return path.size() > nextStoppingIndex + 1 && path.get(nextStoppingIndex).isOppositeRail(path.get(nextStoppingIndex + 1)); } private float getRailProgress(int car, int trainSpacing) { return railProgress - car * trainSpacing; } private int getIndex(int car, int trainSpacing, boolean roundDown) { for (int i = 0; i < path.size(); i++) { final float tempRailProgress = getRailProgress(car, trainSpacing); final float tempDistance = distances.get(i); if (tempRailProgress < tempDistance || roundDown && tempRailProgress == tempDistance) { return i; } } return path.size() - 1; } private Pos3f getRoutePosition(int car, int trainSpacing) { final int index = getIndex(car, trainSpacing, false); return path.get(index).rail.getPosition(getRailProgress(car, trainSpacing) - (index == 0 ? 0 : distances.get(index - 1))); } private int getNextStoppingIndex(int trainSpacing) { final int headIndex = getIndex(0, trainSpacing, false); for (int i = headIndex; i < path.size(); i++) { if (path.get(i).dwellTime > 0) { return i; } } return path.size() - 1; } private int getPreviousStoppingIndex(int headIndex) { for (int i = headIndex; i >= 0; i if (path.get(i).dwellTime > 0 && path.get(i).rail.railType == RailType.PLATFORM) { return i; } } return 0; } private void syncTrainToClient(World world, PlayerEntity player, float percentageX, float percentageZ) { if (world != null && !world.isClient()) { final PacketByteBuf packet = PacketByteBufs.create(); packet.writeLong(sidingId); packet.writeString(Siding.KEY_TRAINS); packet.writeBoolean(false); packet.writeLong(id); writeMainPacket(packet); packet.writeFloat(percentageX); packet.writeFloat(percentageZ); if (player == null) { world.getPlayers().forEach(serverPlayer -> ServerPlayNetworking.send((ServerPlayerEntity) serverPlayer, PACKET_UPDATE_SIDING, packet)); } else { ServerPlayNetworking.send((ServerPlayerEntity) player, PACKET_UPDATE_SIDING, packet); } } } private void writeMainPacket(PacketByteBuf packet) { packet.writeFloat(speed); packet.writeFloat(railProgress); packet.writeFloat(stopCounter); packet.writeInt(nextStoppingIndex); packet.writeBoolean(reversed); packet.writeBoolean(isOnRoute); packet.writeInt(ridingEntities.size()); ridingEntities.forEach(packet::writeUuid); } private float getDoorValue() { final int dwellTicks = path.get(nextStoppingIndex).dwellTime * 10; final float maxDoorMoveTime = Math.min(DOOR_MOVE_TIME, dwellTicks / 2 - DOOR_DELAY); final float stage1 = DOOR_DELAY; final float stage2 = DOOR_DELAY + maxDoorMoveTime; final float stage3 = dwellTicks - DOOR_DELAY - maxDoorMoveTime; final float stage4 = dwellTicks - DOOR_DELAY; if (stopCounter < stage1 || stopCounter >= stage4) { return 0; } else if (stopCounter >= stage2 && stopCounter < stage3) { return 1; } else if (stopCounter >= stage1 && stopCounter < stage2) { return (stopCounter - stage1) / DOOR_MOVE_TIME; } else if (stopCounter >= stage3 && stopCounter < stage4) { return -(stage4 - stopCounter) / DOOR_MOVE_TIME; } else { return 0; } } private boolean openDoors(World world, float trainX, float trainY, float trainZ, float checkYaw, float pitch, float halfSpacing, float doorValue) { if (!world.isClient() && world.getClosestPlayer(trainX, trainY, trainZ, DOOR_MAX_DISTANCE, entity -> true) == null) { return false; } boolean hasPlatform = false; final Vec3d offsetVec = new Vec3d(1, 0, 0).rotateY(checkYaw).rotateX(pitch); final Vec3d traverseVec = new Vec3d(0, 0, 1).rotateY(checkYaw).rotateX(pitch); for (int checkX = 1; checkX <= 3; checkX++) { for (int checkY = -1; checkY <= 0; checkY++) { for (float checkZ = -halfSpacing; checkZ <= halfSpacing; checkZ++) { final BlockPos checkPos = new BlockPos(trainX + offsetVec.x * checkX + traverseVec.x * checkZ, trainY + checkY, trainZ + offsetVec.z * checkX + traverseVec.z * checkZ); final Block block = world.getBlockState(checkPos).getBlock(); if (block instanceof BlockPlatform || block instanceof BlockPSDAPGBase) { if (world.isClient()) { return true; } else if (block instanceof BlockPSDAPGDoorBase) { for (int i = -1; i <= 1; i++) { final BlockPos doorPos = checkPos.up(i); final BlockState state = world.getBlockState(doorPos); final Block doorBlock = state.getBlock(); if (doorBlock instanceof BlockPSDAPGDoorBase) { final int doorStateValue = (int) MathHelper.clamp(doorValue * DOOR_MOVE_TIME, 0, BlockPSDAPGDoorBase.MAX_OPEN_VALUE); world.setBlockState(doorPos, state.with(BlockPSDAPGDoorBase.OPEN, doorStateValue)); if (doorStateValue > 0 && !world.getBlockTickScheduler().isScheduled(checkPos.up(), doorBlock)) { world.getBlockTickScheduler().schedule(new BlockPos(doorPos), doorBlock, 20); } } } } hasPlatform = true; } } } } return hasPlatform; } private void writeArrivalTimes(WriteScheduleCallback writeScheduleCallback, List<Long> routeIds, CustomResources.TrainMapping trainTypeMapping, int trainSpacing) { final int index = getIndex(0, trainSpacing, true); final Pair<Float, Float> firstTimeAndSpeed = writeArrivalTime(writeScheduleCallback, routeIds, trainTypeMapping, index, index == 0 ? railProgress : railProgress - distances.get(index - 1), 0, speed); float currentTicks = firstTimeAndSpeed.getLeft(); float currentSpeed = firstTimeAndSpeed.getRight(); for (int i = index + 1; i < path.size(); i++) { final Pair<Float, Float> timeAndSpeed = writeArrivalTime(writeScheduleCallback, routeIds, trainTypeMapping, i, 0, currentTicks, currentSpeed); currentTicks += timeAndSpeed.getLeft(); currentSpeed = timeAndSpeed.getRight(); } } private Pair<Float, Float> writeArrivalTime(WriteScheduleCallback writeScheduleCallback, List<Long> routeIds, CustomResources.TrainMapping trainTypeMapping, int index, float progress, float currentTicks, float currentSpeed) { final PathData pathData = path.get(index); final Pair<Float, Float> timeAndSpeed = calculateTicksAndSpeed(pathData.rail, progress, currentSpeed, pathData.dwellTime > 0 || index == nextStoppingIndex); if (pathData.dwellTime > 0) { final float stopTicksRemaining = Math.max(pathData.dwellTime * 10 - (index == nextStoppingIndex ? stopCounter : 0), 0); if (pathData.savedRailBaseId != 0) { final float arrivalTicks = currentTicks + timeAndSpeed.getLeft(); writeScheduleCallback.writeScheduleCallback(pathData.savedRailBaseId, arrivalTicks * 50, (arrivalTicks + stopTicksRemaining) * 50, trainTypeMapping.trainType, pathData.stopIndex - 1, routeIds); } return new Pair<>(timeAndSpeed.getLeft() + stopTicksRemaining, timeAndSpeed.getRight()); } else { return timeAndSpeed; } } public static float getAverage(float a, float b) { return (a + b) / 2; } public static float getValueFromPercentage(float percentage, float total) { return (percentage - 0.5F) * total; } private static Pair<Float, Float> calculateTicksAndSpeed(Rail rail, float progress, float initialSpeed, boolean shouldStop) { final float distance = rail.getLength() - progress; if (distance <= 0) { return new Pair<>(0F, initialSpeed); } if (shouldStop) { if (initialSpeed * initialSpeed / (2 * distance) >= ACCELERATION) { return new Pair<>(2 * distance / initialSpeed, 0F); } final float maxSpeed = Math.min(rail.railType.maxBlocksPerTick, (float) Math.sqrt(ACCELERATION * distance + initialSpeed * initialSpeed / 2)); final float ticks = (2 * ACCELERATION * distance + initialSpeed * initialSpeed - 2 * initialSpeed * maxSpeed + 2 * maxSpeed * maxSpeed) / (2 * ACCELERATION * maxSpeed); return new Pair<>(ticks, 0F); } else { final float railSpeed = rail.railType.maxBlocksPerTick; if (initialSpeed == railSpeed) { return new Pair<>(distance / initialSpeed, initialSpeed); } else { final float accelerationDistance = (railSpeed * railSpeed - initialSpeed * initialSpeed) / (2 * ACCELERATION); if (accelerationDistance > distance) { final float finalSpeed = (float) Math.sqrt(2 * ACCELERATION * distance + initialSpeed * initialSpeed); return new Pair<>((finalSpeed - initialSpeed) / ACCELERATION, finalSpeed); } else { final float accelerationTicks = (railSpeed - initialSpeed) / ACCELERATION; final float coastingTicks = (distance - accelerationDistance) / railSpeed; return new Pair<>(accelerationTicks + coastingTicks, railSpeed); } } } } } @FunctionalInterface public interface RenderTrainCallback { void renderTrainCallback(float x, float y, float z, float yaw, float pitch, String customId, TrainType trainType, boolean isEnd1Head, boolean isEnd2Head, boolean head1IsFront, float doorLeftValue, float doorRightValue, boolean opening, boolean lightsOn, boolean offsetRender); } @FunctionalInterface public interface RenderConnectionCallback { void renderConnectionCallback(Pos3f prevPos1, Pos3f prevPos2, Pos3f prevPos3, Pos3f prevPos4, Pos3f thisPos1, Pos3f thisPos2, Pos3f thisPos3, Pos3f thisPos4, float x, float y, float z, TrainType trainType, boolean lightsOn, boolean offsetRender); } @FunctionalInterface public interface SpeedCallback { void speedCallback(float speed, int stopIndex, List<Long> routeIds); } @FunctionalInterface public interface AnnouncementCallback { void announcementCallback(int stopIndex, List<Long> routeIds); } @FunctionalInterface public interface WriteScheduleCallback { void writeScheduleCallback(long platformId, float arrivalMillis, float departureMillis, TrainType trainType, int stopIndex, List<Long> routeIds); } @FunctionalInterface private interface CalculateRenderCallback { void calculateRenderCallback(float x, float y, float z, float yaw, float pitch, float realSpacing, boolean doorLeftOpen, boolean doorRightOpen); } }
package org.jdbdt; import java.io.File; import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * JDBDT facade. * * <p> * This utility class defines the front-end API for database * assertions, setup operations, and creation of associated * object instances. * </p> * * @since 0.1 */ public final class JDBDT { /** * Private constructor to avoid unintended instantiation. */ private JDBDT() { } /** * Get JDBDT version identifier. * @return An identifier for the JDBDT version. */ public static String version() { return VersionInfo.ID; } /** * Create a new database handle. * * <p>The given connection is associated to the handle. * A reference to the connection can later be retrieved * using {@link DB#getConnection()}.</p> * * @param c Connection. * @return A new database handle for the given connection. */ public static DB database(Connection c) { return new DB(c); } /** * Create a new database handle for given database URL. * * <p>Calling this method is shorthand for:<br> * &nbsp;&nbsp;&nbsp;&nbsp; * <code>database( DriverManager.getConnection(url) )</code>. * </p> * * @param url Database URL. * @return A new database handle for the given connection. * @throws SQLException If the connection cannot be created. * @see #database(Connection) * @see DriverManager#getConnection(String) */ public static DB database(String url) throws SQLException { return database(DriverManager.getConnection(url)); } /** * Create a new database handle for given database * URL, user and password . * * <p>Calling this method is shorthand for:<br> * &nbsp;&nbsp;&nbsp;&nbsp; * <code>database( DriverManager.getConnection(url, user, pass) )</code>. * </p> * * @param url Database URL. * @param user Database user. * @param pass Database password. * @return A new database handle for the given connection. * @throws SQLException If the connection cannot be created. * @see #database(Connection) * @see DriverManager#getConnection(String, String, String) */ public static DB database(String url, String user, String pass) throws SQLException { return database(DriverManager.getConnection(url, user, pass)); } /** * Tear-down a database handle. * * <p>Calling this method releases any associated resources * to the given database handle. The database handle should * not be used after a call to this method is made. * </p> * <p> * The freed-up resources include any save points, * prepared statements, and opened log files. * The second parameter specifies if the * underlying database connection should be closed * as well or not. * </p> * * @param db Database handle * @param closeConn Indicates * if underlying connection should be closed. */ public static void teardown(DB db, boolean closeConn) { db.teardown(CallInfo.create(), closeConn); } /** * Create a builder for a fresh data set. * @param source Data source. * @return A new data set builder. */ public static DataSetBuilder builder(DataSource source) { return new DataSet(source).build(); } /** * Get empty data set constant for given data source. * * <p> * This convenience method is useful to denote the empty data set for * a data source. It always returns an empty, read-only data set, * and one that is guaranteed to be unique and for the given * data source instance. * </p> * * @param source Data source. * @return A new data set for the given source. * @see DataSet#isEmpty() * @see DataSet#isReadOnly() */ public static DataSet empty(DataSource source) { return source.theEmptySet(); } /** * Create a new data set. * @param source Data source. * @return A new data set for the given source. */ public static DataSet data(DataSource source) { return new DataSet(source); } /** * Create a new typed data set. * @param <T> Type of objects. * @param source Data source. * @param conv Conversion function. * @return A new typed data set for the given source. */ public static <T> TypedDataSet<T> data(DataSource source, Conversion<T> conv) { return new TypedDataSet<>(source, conv); } /** * Create a table builder. * * <p> * A call to this method is equivalent to creating * a {@link TableBuilder} instance as follows: * </p> * <code> * &nbsp;&nbsp;new TableBuilder().name(tableName) * </code> * * @param tableName Table name. * @return A new {@link Table} instance. */ public static TableBuilder table(String tableName) { return new TableBuilder().name(tableName); } /** * Create a query data source from given SQL code. * @param db Database handle. * @param sql SQL code. * @param args Optional query arguments. * @return A new query data source. */ @SafeVarargs public static Query query(DB db, String sql, Object... args) { return new Query(db, sql, args); } /** * Create a query builder. * <p> * A call to this method is equivalent to * creating a {@link QueryBuilder} as follows: * </p> * <code> * &nbsp;&nbsp;new QueryBuilder().columns(columns) * </code> * * @param columns Columns for query. * @return A new query builder. */ @SafeVarargs public static QueryBuilder select(String... columns) { return new QueryBuilder().columns(columns); } /** * Take a database snapshot. * * <p> * The method takes a snapshot of the current database state * for the given data source. A fresh query will be issued, * yielding a new data set that is recorded internally * as the latest snapshot for the data source. * The snapshot is used as the base reference for any subsequent * delta assertions, until a new snapshot is defined with * a new call to this method or to {@link #populate(DataSet)}; * </p> * * <p> * Note that the method returns the data set instance representing the snapshot, * but subsequent use of assertion methods does not require any book-keeping * by the caller. Also, the returned data set is read-only (see {@link DataSet#isReadOnly()}). * </p> * * @param source Data source. * @throws DBExecutionException if a database error occurs * @return Data set representing the snapshot. * * @see #assertDelta(DataSet, DataSet) * @see #assertDeleted(DataSet) * @see #assertInserted(DataSet) * @see #assertUnchanged(DataSource) */ public static DataSet takeSnapshot(DataSource source) { return source.executeQuery(CallInfo.create(), true); } /** * Query the data source, without setting a snapshot. * @param source Data source. * @return Query result. */ static DataSet executeQuery(DataSource source) { return source.executeQuery(CallInfo.create(), false); } /** * Assert that two data sets are equivalent (error message variant). * * <p> * Note that the executed data set comparison is insensitive * to the order of rows in both data sets. * </p> * * @param expected Expected data. * @param actual Actual data. * @throws DBAssertionError if the assertion fails. * @see #assertEquals(String,DataSet,DataSet) */ public static void assertEquals(DataSet expected, DataSet actual) throws DBAssertionError { DBAssert.dataSetAssertion(CallInfo.create(), expected, actual); } /** * Assert that two data sets are equivalent (error message variant). * * <p> * Note that the executed data set comparison is insensitive * to the order of rows in both data sets. * </p> * * @param message Assertion error message. * @param expected Expected data. * @param actual Actual data. * @throws DBAssertionError if the assertion fails. * @see #assertEquals(DataSet,DataSet) */ public static void assertEquals(String message, DataSet expected, DataSet actual) throws DBAssertionError { DBAssert.dataSetAssertion(CallInfo.create(message), expected, actual); } /** * Assert that no changes occurred for the given data source * (error message variant). * * @param message Assertion error message. * @param source Data source. * @throws DBAssertionError if the assertion fails. * @see #assertDelta(DataSet,DataSet) * @see #assertDeleted(String, DataSet) * @see #assertInserted(String, DataSet) */ public static void assertUnchanged(String message, DataSource source) throws DBAssertionError { DataSet emptyDataSet = empty(source); DBAssert.deltaAssertion(CallInfo.create(message), emptyDataSet, emptyDataSet); } /** * Assert that no changes occurred for the given data source. * * @param source Data source. * @throws DBAssertionError if the assertion fails. * @see #assertDelta(DataSet,DataSet) * @see #assertDeleted(DataSet) * @see #assertInserted(DataSet) */ public static void assertUnchanged(DataSource source) throws DBAssertionError { DataSet emptyDataSet = empty(source); DBAssert.deltaAssertion(CallInfo.create(), emptyDataSet, emptyDataSet); } /** * Assert that database changed only by removal of a given * data set (error message variant). * * @param message The message for the assertion error. * @param data Data set. * @throws DBAssertionError if the assertion fails. * @see #assertDelta(String, DataSet,DataSet) * @see #assertInserted(String, DataSet) * @see #assertUnchanged(String, DataSource) */ public static void assertDeleted(String message, DataSet data) throws DBAssertionError { DBAssert.deltaAssertion(CallInfo.create(message), data, empty(data.getSource())); } /** * Assert that database changed only by removal of a given * data set. * * @param data Data set. * @throws DBAssertionError if the assertion fails. * @see #assertUnchanged(DataSource) * @see #assertInserted(DataSet) */ public static void assertDeleted(DataSet data) throws DBAssertionError { DBAssert.deltaAssertion(CallInfo.create(), data, empty(data.getSource())); } /** * Assert that database changed only by addition of a given * data set (error message variant). * * @param message Assertion error message. * @param data Data set. * @throws DBAssertionError if the assertion fails. * @see #assertUnchanged(DataSource) * @see #assertDeleted(DataSet) * @see #assertDelta(DataSet,DataSet) */ public static void assertInserted(String message, DataSet data) throws DBAssertionError { DBAssert.deltaAssertion(CallInfo.create(message), empty(data.getSource()), data); } /** * Assert that database changed only by addition of a given * data set. * * @param data data set. * @throws DBAssertionError if the assertion fails. * @see #assertUnchanged(DataSource) * @see #assertDeleted(DataSet) * @see #assertDelta(DataSet,DataSet) */ public static void assertInserted(DataSet data) throws DBAssertionError { DBAssert.deltaAssertion(CallInfo.create(), empty(data.getSource()), data); } /** * Assert database delta expressed by 'old' * and 'new' data sets (error message variant). * * @param message The error message for the assertion error. * @param oldData Expected 'old' data. * @param newData Expected 'new' data. * @throws DBAssertionError if the assertion fails. * * @see #assertUnchanged(DataSource) * @see #assertDeleted(DataSet) * @see #assertInserted(DataSet) */ public static void assertDelta(String message, DataSet oldData, DataSet newData) throws DBAssertionError { DBAssert.deltaAssertion(CallInfo.create(message), oldData, newData); } /** * Assert database delta expressed by 'old' * and 'new' data sets. * * @param oldData Expected 'old' data. * @param newData Expected 'new' data. * @throws DBAssertionError if the assertion fails. * * @see #assertUnchanged(DataSource) * @see #assertDeleted(DataSet) * @see #assertInserted(DataSet) */ public static void assertDelta(DataSet oldData, DataSet newData) throws DBAssertionError { DBAssert.deltaAssertion(CallInfo.create(), oldData, newData); } /** * Assert that the database state matches the given data set * (error message variant). * @param message Assertion error message. * @param data Data set. * @throws DBAssertionError if the assertion fails. */ public static void assertState(String message, DataSet data) throws DBAssertionError { DBAssert.stateAssertion(CallInfo.create(message), data); } /** * Assert that the database state matches the given data set. * @param data Data set. * @throws DBAssertionError if the assertion fails. */ public static void assertState(DataSet data) throws DBAssertionError { DBAssert.stateAssertion(CallInfo.create(), data); } /** * Assert that the given data source * has no rows (error message variant). * * <p>A call to this method is equivalent to * <code>assertState(message, empty(source))</code>. * * @param message Assertion error message. * @param source Data source. * @throws DBAssertionError if the assertion fails. * @see #assertState(String,DataSet) * @see #empty(DataSource) */ public static void assertEmpty(String message, DataSource source) throws DBAssertionError { DBAssert.stateAssertion(CallInfo.create(message), empty(source)); } /** * Assert that the given data source has no rows. * * <p>A call to this method is equivalent to * <code>assertState(empty(source))</code>. * @param source Data source. * @throws DBAssertionError if the assertion fails. * @see #assertState(DataSet) * @see #empty(DataSource) */ public static void assertEmpty(DataSource source) throws DBAssertionError { DBAssert.stateAssertion(CallInfo.create(), empty(source)); } /** * Insert a data set onto database. * * @param data Data set for insertion. * @throws DBExecutionException If a database error occurs. * */ public static void insert(DataSet data) throws DBExecutionException { DBSetup.insert(CallInfo.create(), data); } /** * Populate database with given data set. * * @param data Data set for insertion. * @throws DBExecutionException If a database error occurs. */ public static void populate(DataSet data) throws DBExecutionException { DBSetup.populate(CallInfo.create(), data); } /** * Populate database with given data set if the associated * table is seen as changed. * * <p>A call to this method is functionally equivalent to * <br> * &nbsp;&nbsp;&nbsp;&nbsp; * <code>if ( changed(data.getSource()) ) populate(data);</code> * </p> * @param data Data set for insertion. * @throws DBExecutionException If a database error occurs. * @see #changed(DataSource...) */ public static void populateIfChanged(DataSet data) throws DBExecutionException { DBSetup.populateIfChanged(CallInfo.create(), data); } /** * Delete all data from a table. * * @param table Table. * @return Number of deleted entries. * @throws DBExecutionException if a database error occurs. * @see #truncate(Table) * @see #deleteAllWhere(Table,String,Object...) */ public static int deleteAll(Table table) throws DBExecutionException { return DBSetup.deleteAll(CallInfo.create(), table); } /** * Delete all data from a table, subject to a <code>WHERE</code> * clause. * * * @param table Table. * @param where <code>WHERE</code> clause * @param args <code>WHERE</code> clause arguments, if any. * @return Number of deleted entries. * @throws DBExecutionException if a database error occurs. * @see #deleteAll(Table) * @see #truncate(Table) */ @SafeVarargs public static int deleteAllWhere(Table table, String where, Object... args) throws DBExecutionException { return DBSetup.deleteAll(CallInfo.create(), table, where, args); } /** * Truncate table. * @param table Table. * @throws DBExecutionException if a database error occurs. * @see #deleteAll(Table) * @see #deleteAllWhere(Table,String,Object...) * @throws DBExecutionException if a database error occurs. */ public static void truncate(Table table) throws DBExecutionException { DBSetup.truncate(CallInfo.create(), table); } /** * Set JDBDT save-point for database. * * <p> * This method creates a save-point (through an internal * {@link java.sql.Savepoint}) which can later * be restored (rolled back to) using {@link #restore(DB)}. * Note that JDBDT maintains only one save-point per database * handle, hence successive calls to this method discard the previous * save-point set (if any). * </p> * * @param db Database handle. * @throws UnsupportedOperationException if save-points are not supported for the database. * @throws InvalidOperationException if database has auto-commit turned on. * @throws DBExecutionException if a database error occurs. */ public static void save(DB db) throws DBExecutionException, InvalidOperationException, UnsupportedOperationException { db.save(CallInfo.create()); } /** * Restore database state to the last JDBDT save-point. * * <p> * A call to this method restores (rolls back) the state * to the last JDBDT save-point set using {@link #save(DB)}. * The save-point cannot be subsequently restored, i.e., only * one call to this method is allowed after each call to * {@link #save(DB)}. * </p> * * @param db Database handle. * @throws DBExecutionException if a database error occurs. * @throws InvalidOperationException if a save-point has not been set with {@link JDBDT#save(DB)} * @throws UnsupportedOperationException if save-points are not supported for the database. */ public static void restore(DB db) throws DBExecutionException, InvalidOperationException, UnsupportedOperationException { db.restore(CallInfo.create()); } /** * Commit changes in current transaction. * * <p> * In database terms the method is simply a shorthand * for <code>db.getConnection().commit()</code>. * Any database save-points will be discarded, * including the JDBDT save-point, if set through * {@link #save(DB)}. * </p> * * @param db Database handle. * @throws DBExecutionException if a database error occurs. * @see Connection#commit() */ public static void commit(DB db) throws DBExecutionException { db.commit(CallInfo.create()); } /** * Check if given data sources are seen as changed. * * <p> * A data source is marked as unchanged by a successful assertion * through * {@link #assertUnchanged(DataSource)} * or {@link #assertUnchanged(String,DataSource)}. * Every other setup or assertion method will mark the associated * data source as changed. * </p> * <p> * This method may be useful for conditional setup code that * is executed only if the database needs to be reinitialized, * as illustrated below. * </p> * <pre> * DataSource ds = ...; * * if ( changed(ds) ) { * // Setup initial state again * ... * } * </pre> * * @param dataSources Data sources. * @return <code>true</code> if at least one of the given data sources * is marked as changed. * @see #populateIfChanged(DataSet) */ @SafeVarargs public static boolean changed(DataSource... dataSources) { if (dataSources == null || dataSources.length == 0) { throw new InvalidOperationException("No data sources specified"); } for (DataSource ds : dataSources) { if (ds.getDirtyStatus()) { return true; } } return false; } /** * Dump the contents of a data set. * @param data Data set. * @param out Output stream. */ public static void dump(DataSet data, PrintStream out) { try (Log log = Log.create(out);) { log.write(CallInfo.create(), data); } } /** * Dump the contents of a data set (output file variant). * @param data Data set. * @param outputFile Output file. */ public static void dump(DataSet data, File outputFile) { try (Log log = Log.create(outputFile);) { log.write(CallInfo.create(), data); } } /** * Dump the database contents for a data source. * @param source Data source. * @param out Output stream. * @throws DBExecutionException if a database error occurs. */ public static void dump(DataSource source, PrintStream out) throws DBExecutionException { try (Log log = Log.create(out);) { log.write(CallInfo.create(), executeQuery(source)); } } /** * Dump the database contents for a data source (file variant). * @param source Data source. * @param outputFile Output file. * @throws DBExecutionException if a database error occurs. */ public static void dump(DataSource source, File outputFile) throws DBExecutionException { try (Log log = Log.create(outputFile);) { log.write(CallInfo.create(), executeQuery(source)); } } }
package org.osgl.http; import org.apache.commons.codec.Charsets; import org.osgl._; import org.osgl.cache.CacheService; import org.osgl.exception.NotAppliedException; import org.osgl.exception.UnexpectedIOException; import org.osgl.http.util.Path; import org.osgl.logging.L; import org.osgl.logging.Logger; import org.osgl.util.*; import org.osgl.web.util.UserAgent; import java.io.*; import java.nio.charset.Charset; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.osgl.http.H.Header.Names.*; /** * The namespace to access Http features. * Alias of {@link org.osgl.http.Http} */ public class H { protected static final Logger logger = L.get(Http.class); public static enum Method { GET, HEAD, POST, DELETE, PUT, PATCH, TRACE, OPTIONS, CONNECT; private String id; private Method() { id = name().intern(); } private static EnumSet<Method> unsafeMethods = EnumSet.of(POST, DELETE, PUT, PATCH); private static EnumSet<Method> actionMethods = EnumSet.of(GET, POST, PUT, DELETE); /** * Returns if this http method is safe, meaning it * won't change the state of the server * * @see #unsafe() */ public boolean safe() { return !unsafe(); } /** * Returns if this http method is unsafe, meaning * it will change the state of the server * * @see #safe() */ public boolean unsafe() { return unsafeMethods.contains(this); } public static Method valueOfIgnoreCase(String method) { return valueOf(method.toUpperCase()); } public static EnumSet<Method> actionMethods() { return actionMethods.clone(); } } // eof Method /** * The HTTP Status constants */ public static enum Status { // 1xx Informational CONTINUE(100), SWITCHING_PROTOCOLS(101), PROCESSING(102), CHECKPOINT(103), // 2xx Success OK(200), CREATED(201), ACCEPTED(202), NON_AUTHORITATIVE_INFORMATION(203), NO_CONTENT(204), RESET_CONTENT(205), PARTIAL_CONTENT(206), MULTI_STATUS(207), ALREADY_REPORTED(208), IM_USED(226), // 3xx Redirection MULTIPLE_CHOICES(300), FOUND_AJAX(278), MOVED_PERMANENTLY(301), FOUND(302), @Deprecated MOVED_TEMPORARILY(302), SEE_OTHER(303), NOT_MODIFIED(304), USE_PROXY(305), TEMPORARY_REDIRECT(307), RESUME_INCOMPLETE(308), BAD_REQUEST(400), UNAUTHORIZED(401), PAYMENT_REQUIRED(402), FORBIDDEN(403), NOT_FOUND(404), METHOD_NOT_ALLOWED(405), NOT_ACCEPTABLE(406), PROXY_AUTHENTICATION_REQUIRED(407), REQUEST_TIMEOUT(408), CONFLICT(409), GONE(410), LENGTH_REQUIRED(411), PRECONDITION_FAILED(412), REQUEST_ENTITY_TOO_LARGE(413), REQUEST_URI_TOO_LONG(414), UNSUPPORTED_MEDIA_TYPE(415), REQUESTED_RANGE_NOT_SATISFIABLE(416), EXPECTATION_FAILED(417), I_AM_A_TEAPOT(418), @Deprecated INSUFFICIENT_SPACE_ON_RESOURCE(419), @Deprecated METHOD_FAILURE(420), @Deprecated DESTINATION_LOCKED(421), UNPROCESSABLE_ENTITY(422), LOCKED(423), FAILED_DEPENDENCY(424), UPGRADE_REQUIRED(426), PRECONDITION_REQUIRED(428), TOO_MANY_REQUESTS(429), REQUEST_HEADER_FIELDS_TOO_LARGE(431), INTERNAL_SERVER_ERROR(500), NOT_IMPLEMENTED(501), BAD_GATEWAY(502), SERVICE_UNAVAILABLE(503), GATEWAY_TIMEOUT(504), HTTP_VERSION_NOT_SUPPORTED(505), VARIANT_ALSO_NEGOTIATES(506), INSUFFICIENT_STORAGE(507), LOOP_DETECTED(508), /** * {@code 509 Bandwidth Limit Exceeded} */ BANDWIDTH_LIMIT_EXCEEDED(509), NOT_EXTENDED(510), NETWORK_AUTHENTICATION_REQUIRED(511); private final int code; private Status(int code) { this.code = code; } /** * Return the integer code of this status code. */ public int code() { return this.code; } /** * Returns true if the status is a client error or server error * * @see #isServerError() * @see #isClientError() */ public boolean isError() { return isClientError() || isServerError(); } /** * Returns true if the status is server error (5xx) */ public boolean isServerError() { return code / 100 == 5; } /** * Returns true if the status is client error (4xx) */ public boolean isClientError() { return code / 100 == 4; } /** * Returns true if the status is success series (2xx) */ public boolean isSuccess() { return code / 100 == 2; } /** * Returns true if the status is redirect series (3xx) */ public boolean isRedirect() { return code / 100 == 3; } /** * Returns true if the status is informational series (1xx) */ public boolean isInformational() { return code / 100 == 1; } /** * Return a string representation of this status code. */ @Override public String toString() { return Integer.toString(code); } public static Status valueOf(int statusCode) { for (Status status : values()) { if (status.code == statusCode) { return status; } } throw new IllegalArgumentException("No matching constant for [" + statusCode + "]"); } } // eof Status public static final class Header { public static final class Names { /** * {@code "Accept"} */ public static final String ACCEPT = "accept"; /** * {@code "Accept-Charset"} */ public static final String ACCEPT_CHARSET = "accept-charset"; /** * {@code "Accept-Encoding"} */ public static final String ACCEPT_ENCODING = "accept-encoding"; /** * {@code "Accept-Language"} */ public static final String ACCEPT_LANGUAGE = "accept-language"; /** * {@code "Accept-Ranges"} */ public static final String ACCEPT_RANGES = "accept-ranges"; /** * {@code "Accept-Patch"} */ public static final String ACCEPT_PATCH = "accept-patch"; /** * {@code "Age"} */ public static final String AGE = "age"; /** * {@code "Allow"} */ public static final String ALLOW = "allow"; /** * {@code "Authorization"} */ public static final String AUTHORIZATION = "authorization"; /** * {@code "Cache-Control"} */ public static final String CACHE_CONTROL = "cache-control"; /** * {@code "Connection"} */ public static final String CONNECTION = "connection"; /** * {@code "Content-Base"} */ public static final String CONTENT_BASE = "content-base"; /** * {@code "Content-Disposition"} */ public static final String CONTENT_DISPOSITION = "content-disposition"; /** * {@code "Content-Encoding"} */ public static final String CONTENT_ENCODING = "content-encoding"; /** * {@code "Content-Language"} */ public static final String CONTENT_LANGUAGE = "content-language"; /** * {@code "Content-Length"} */ public static final String CONTENT_LENGTH = "content-length"; /** * {@code "Content-Location"} */ public static final String CONTENT_LOCATION = "content-location"; /** * {@code "Content-Transfer-Encoding"} */ public static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; /** * {@code "Content-MD5"} */ public static final String CONTENT_MD5 = "content-md5"; /** * {@code "Content-Range"} */ public static final String CONTENT_RANGE = "content-range"; /** * {@code "Content-Type"} */ public static final String CONTENT_TYPE = "content-type"; /** * {@code "Cookie"} */ public static final String COOKIE = "cookie"; /** * {@code "Date"} */ public static final String DATE = "date"; /** * {@code "ETag"} */ public static final String ETAG = "etag"; /** * {@code "Expect"} */ public static final String EXPECT = "expect"; /** * {@code "Expires"} */ public static final String EXPIRES = "expires"; /** * {@code "From"} */ public static final String FROM = "from"; /** * {@code "Front-End-Https"} */ public static final String FRONT_END_HTTPS = "front-end-https"; /** * {@code "Host"} */ public static final String HOST = "host"; /** * {@code "If-Match"} */ public static final String IF_MATCH = "if-match"; /** * {@code "If-Modified-Since"} */ public static final String IF_MODIFIED_SINCE = "if-modified-since"; /** * {@code "If-None-Match"} */ public static final String IF_NONE_MATCH = "if-none-natch"; /** * {@code "If-Range"} */ public static final String IF_RANGE = "if-range"; /** * {@code "If-Unmodified-Since"} */ public static final String IF_UNMODIFIED_SINCE = "if-unmodified-since"; /** * {@code "Last-Modified"} */ public static final String LAST_MODIFIED = "last-modified"; /** * {@code "Location"} */ public static final String LOCATION = "location"; /** * {@code "Max-Forwards"} */ public static final String MAX_FORWARDS = "max-forwards"; /** * {@code "Origin"} */ public static final String ORIGIN = "origin"; /** * {@code "Pragma"} */ public static final String PRAGMA = "pragma"; /** * {@code "Proxy-Authenticate"} */ public static final String PROXY_AUTHENTICATE = "proxy-authenticate"; /** * {@code "Proxy-Authorization"} */ public static final String PROXY_AUTHORIZATION = "proxy-authorization"; /** * {@code "Proxy-Connection"} */ public static final String PROXY_CONNECTION = "proxy_connection"; /** * {@code "Range"} */ public static final String RANGE = "range"; /** * {@code "Referer"} */ public static final String REFERER = "referer"; /** * {@code "Retry-After"} */ public static final String RETRY_AFTER = "retry-after"; /** * {@code "sec-websocket-Key1"} */ public static final String SEC_WEBSOCKET_KEY1 = "sec-websocket-key1"; /** * {@code "sec-websocket-Key2"} */ public static final String SEC_WEBSOCKET_KEY2 = "sec-websocket-key2"; /** * {@code "sec-websocket-Location"} */ public static final String SEC_WEBSOCKET_LOCATION = "sec-websocket-location"; /** * {@code "sec-websocket-Origin"} */ public static final String SEC_WEBSOCKET_ORIGIN = "sec-websocket-origin"; /** * {@code "sec-websocket-Protocol"} */ public static final String SEC_WEBSOCKET_PROTOCOL = "sec-websocket-protocol"; /** * {@code "sec-websocket-Version"} */ public static final String SEC_WEBSOCKET_VERSION = "sec-websocket-version"; /** * {@code "sec-websocket-Key"} */ public static final String SEC_WEBSOCKET_KEY = "sec-websocket-key"; /** * {@code "sec-websocket-Accept"} */ public static final String SEC_WEBSOCKET_ACCEPT = "sec-websocket-accept"; /** * {@code "Server"} */ public static final String SERVER = "server"; /** * {@code "Set-Cookie"} */ public static final String SET_COOKIE = "set-cookie"; /** * {@code "Set-Cookie2"} */ public static final String SET_COOKIE2 = "set-cookie2"; /** * {@code "TE"} */ public static final String TE = "te"; /** * {@code "Trailer"} */ public static final String TRAILER = "trailer"; /** * {@code "Transfer-Encoding"} */ public static final String TRANSFER_ENCODING = "transfer-encoding"; /** * {@code "Upgrade"} */ public static final String UPGRADE = "upgrade"; /** * {@code "User-Agent"} */ public static final String USER_AGENT = "user-agent"; /** * {@code "Vary"} */ public static final String VARY = "vary"; /** * {@code "Via"} */ public static final String VIA = "via"; /** * {@code "Warning"} */ public static final String WARNING = "warning"; /** * {@code "WebSocket-Location"} */ public static final String WEBSOCKET_LOCATION = "websocket-location"; /** * {@code "WebSocket-Origin"} */ public static final String WEBSOCKET_ORIGIN = "webwocket-origin"; /** * {@code "WebSocket-Protocol"} */ public static final String WEBSOCKET_PROTOCOL = "websocket-protocol"; /** * {@code "WWW-Authenticate"} */ public static final String WWW_AUTHENTICATE = "www-authenticate"; /** * {@code "X_Requested_With"} */ public static final String X_REQUESTED_WITH = "x-requested-with"; /** * {@code "X-Forwarded-Host"} */ public static final String X_FORWARDED_HOST = "x-forwarded-host"; /** * {@code "X_Forwared_For"} */ public static final String X_FORWARDED_FOR = "x-forwarded-for"; /** * {@code "X_Forwared_Proto"} */ public static final String X_FORWARDED_PROTO = "x-forwarded-proto"; /** * {@code "X-Forwarded-Ssl"} */ public static final String X_FORWARDED_SSL = "x-forwarded-ssl"; /** * {@code "X-Http-Method-Override"} */ public static final String X_HTTP_METHOD_OVERRIDE = "x-http-method-override"; /** * {@code "X-Url-Scheme"} */ public static final String X_URL_SCHEME = "x-url-scheme"; private Names() { super(); } } private String name; private C.List<String> values; public Header(String name, String value) { E.NPE(name); this.name = name; this.values = C.list(value); } public Header(String name, String... values) { E.NPE(name); this.name = name; this.values = C.listOf(values); } public Header(String name, Iterable<String> values) { E.NPE(name); this.name = name; this.values = C.list(values); } public String name() { return name; } public String value() { return values.get(0); } public C.List<String> values() { return values; } @Override public String toString() { return values.toString(); } } // eof Header /** * Specify the format of the requested content type */ public static enum Format { /** * The "text/html" content format */ html { @Override public String toContentType() { return "text/html"; } }, /** * The "text/xml" content format */ xml { @Override public String toContentType() { return "text/xml"; } }, /** * The "application/json" content format */ json { @Override public String toContentType() { return "application/json"; } /** * Returns {@code {"error": "[error-message]"}} string * @param message the error message * @return the error message in JSON formatted string */ @Override public String errorMessage(String message) { return S.fmt("{\"error\": \"%s\"}", message); } }, /** * The "application/vnd.ms-excel" content format */ xls { @Override public String toContentType() { return "application/vnd.ms-excel"; } }, /** * The "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" content format */ xlsx { @Override public String toContentType() { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } }, /** * The "application/vnd.ms-word" content format */ doc { @Override public String toContentType() { return "application/vnd.ms-word"; } }, /** * The "application/vnd.openxmlformats-officedocument.wordprocessingml.document" content format */ docx { @Override public String toContentType() { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } }, /** * The "text/csv" content format */ csv { @Override public String toContentType() { return "text/csv"; } }, /** * The "text/plain" content format */ txt { @Override public String toContentType() { return "text/plain"; } }, /** * The "application/pdf" content format */ pdf { @Override public String toContentType() { return "application/pdf"; } }, /** * The "application/rtf" content format */ rtf { @Override public String toContentType() { return "application/rtf"; } }, /** * The "application/x-www-form-urlencoded" post content type */ form_url_encoded { @Override public String toContentType() { return "application/x-www-form-urlencoded"; } }, /** * The "multipart/form-data" post content type */ form_multipart_data { @Override public String toContentType() { return "multipart/form-data"; } }, unknown { @Override public String toContentType() { String s = Current.format(); if (!S.blank(s)) { return toContentType(s); } return "text/html"; } @Override public String toString() { String s = Current.format(); return null == s ? name() : s; } }; /** * Returns the content type string * * @return the content type string of this format */ public abstract String toContentType(); private static volatile Properties types; public static String toContentType(String fmt) { if (null == types) { synchronized (Format.class) { if (null == types) { try { InputStream is = H.class.getResourceAsStream("mime-types.properties"); types = new Properties(); types.load(is); } catch (IOException e) { throw E.ioException(e); } } } } return types.getProperty(fmt, "text/html"); } public static Format of(String fmt) { return valueOfIgnoreCase(fmt); } public static Format valueOfIgnoreCase(String fmt) { fmt = fmt.toLowerCase(); if (fmt.startsWith(".")) fmt = S.afterLast(fmt, "."); try { return valueOf(fmt); } catch (Exception e) { Current.format(fmt); return unknown; } } /** * Returns the error message * * @param message * @return the message directly */ public String errorMessage(String message) { return message; } /** * Resolve {@code Format} instance out of an http "Accept" header. * * @param accept the value of http "Accept" header * @return an {@code Format} instance */ public static Format resolve(String accept) { return resolve_(Format.unknown, accept); } public static String fmtToContentType(String fmt) { return unknown.toContentType(fmt); } public static Format resolve(Format def, String accept) { E.NPE(def); return resolve_(def, accept); } private static Format resolve_(Format def, String contentType) { Format fmt = def; if (S.blank(contentType)) { fmt = html; } else if (contentType.contains("application/xhtml") || contentType.contains("text/html") || contentType.startsWith("*/*")) { fmt = html; } else if (contentType.contains("application/xml") || contentType.contains("text/xml")) { fmt = xml; } else if (contentType.contains("application/json") || contentType.contains("text/javascript")) { fmt = json; } else if (contentType.contains("application/x-www-form-urlencoded")) { fmt = form_url_encoded; } else if (contentType.contains("multipart/form-data") || contentType.contains("multipart/mixed")) { fmt = form_multipart_data; } else if (contentType.contains("text/plain")) { fmt = txt; } else if (contentType.contains("csv") || contentType.contains("comma-separated-values")) { fmt = csv; } else if (contentType.contains("ms-excel")) { fmt = xls; } else if (contentType.contains("spreadsheetml")) { fmt = xlsx; } else if (contentType.contains("pdf")) { fmt = pdf; } else if (contentType.contains("msword")) { fmt = doc; } else if (contentType.contains("wordprocessingml")) { fmt = docx; } else if (contentType.contains("rtf")) { fmt = rtf; } return fmt; } public static Format resolve(Iterable<String> accepts) { return resolve(Format.html, accepts); } public static Format resolve(Format def, Iterable<String> accepts) { Format retval; for (String s : accepts) { retval = resolve_(null, s); if (null != retval) { return retval; } } return _.ifNullThen(def, Format.html); } public static Format resolve(String... accepts) { return resolve(Format.html, accepts); } public static Format resolve(Format def, String... accepts) { Format retval; for (String s : accepts) { retval = resolve_(null, s); if (null != retval) { return retval; } } return _.ifNullThen(def, Format.html); } } // eof Format /** * The HTTP cookie */ public static class Cookie { private String name; // default is non-persistent cookie private int maxAge = -1; private boolean secure; private String path; private String domain; private String value; private boolean httpOnly; private int version; private Date expires; private String comment; public Cookie(String name) { this(name, ""); } public Cookie(String name, String value) { E.NPE(name); this.name = name; this.value = null == value ? "" : value; } public Cookie(String name, String value, int maxAge, boolean secure, String path, String domain, boolean httpOnly) { this(name, value); this.maxAge = maxAge; this.secure = secure; this.path = path; this.domain = domain; this.httpOnly = httpOnly; } /** * Returns the name of the cookie. Cookie name * cannot be changed after created */ public String name() { return name; } /** * Returns the value of the cookie */ public String value() { return value; } /** * Set a value to a cookie and the return {@code this} cookie * * @param value the value to be set to the cookie * @return this cookie */ public Cookie value(String value) { this.value = value; return this; } /** * Returns the domain of the cookie */ public String domain() { return domain; } /** * Set the domain of the cookie * * @param domain the domain string * @return this cookie */ public Cookie domain(String domain) { this.domain = domain; return this; } /** * Returns the path on the server * to which the browser returns this cookie. The * cookie is visible to all subpaths on the server. * * @see #path(String) */ public String path() { return path; } /** * Specifies a path for the cookie * to which the client should return the cookie. * <p/> * <p>The cookie is visible to all the pages in the directory * you specify, and all the pages in that directory's subdirectories. * <p/> * <p>Consult RFC 2109 (available on the Internet) for more * information on setting path names for cookies. * * @param uri a <code>String</code> specifying a path * @return this cookie after path is set * @see #path */ public Cookie path(String uri) { this.path = uri; return this; } /** * Returns the maximum age of cookie specified in seconds. If * maxAge is set to {@code -1} then the cookie will persist until * browser shutdown */ public int maxAge() { return maxAge; } /** * Set the max age of the cookie in seconds. * <p>A positive value indicates that the cookie will expire * after that many seconds have passed. Note that the value is * the <i>maximum</i> age when the cookie will expire, not the cookie's * current age. * <p/> * <p>A negative value means * that the cookie is not stored persistently and will be deleted * when the Web browser exits. A zero value causes the cookie * to be deleted. * * @see #maxAge() */ public Cookie maxAge(int maxAge) { this.maxAge = maxAge; return this; } public Date expires() { if (null != expires) { return expires; } if (maxAge < 0) { return null; } return new Date(_.ms() + maxAge * 1000); } public Cookie expires(Date expires) { this.expires = expires; if (null != expires && -1 == maxAge) { maxAge = (int) ((expires.getTime() - _.ms()) / 1000); } return this; } /** * Returns <code>true</code> if the browser is sending cookies * only over a secure protocol, or <code>false</code> if the * browser can send cookies using any protocol. * * @see #secure(boolean) */ public boolean secure() { return secure; } /** * Indicates to the browser whether the cookie should only be sent * using a secure protocol, such as HTTPS or SSL. * <p/> * <p>The default value is <code>false</code>. * * @param secure the cookie secure requirement * @return this cookie instance */ public Cookie secure(boolean secure) { this.secure = secure; return this; } /** * Returns the version of the protocol this cookie complies * with. Version 1 complies with RFC 2109, * and version 0 complies with the original * cookie specification drafted by Netscape. Cookies provided * by a browser use and identify the browser's cookie version. * * @return 0 if the cookie complies with the * original Netscape specification; 1 * if the cookie complies with RFC 2109 * @see #version(int) */ public int version() { return version; } /** * Sets the version of the cookie protocol that this Cookie complies * with. * <p/> * <p>Version 0 complies with the original Netscape cookie * specification. Version 1 complies with RFC 2109. * <p/> * <p>Since RFC 2109 is still somewhat new, consider * version 1 as experimental; do not use it yet on production sites. * * @param v 0 if the cookie should comply with the original Netscape * specification; 1 if the cookie should comply with RFC 2109 * @see #version() */ public Cookie version(int v) { this.version = v; return this; } public boolean httpOnly() { return httpOnly; } public Cookie httpOnly(boolean httpOnly) { this.httpOnly = httpOnly; return this; } public String comment() { return comment; } public Cookie comment(String comment) { this.comment = comment; return this; } private static void ensureInit() { if (!Current.cookieMapInitialized()) { Request req = Request.current(); E.illegalStateIf(null == req); req._initCookieMap(); } } /** * Add a cookie to the current context * * @param cookie */ public static void set(Cookie cookie) { ensureInit(); Current.setCookie(cookie.name(), cookie); } /** * Get a cookie from current context by name * * @param name * @return a cookie with the name specified */ public static Cookie get(String name) { ensureInit(); return Current.getCookie(name); } /** * Returns all cookies from current context */ public static Collection<Cookie> all() { ensureInit(); return Current.cookies(); } /** * The function object namespace */ public static enum F { ; public static final _.F2<Cookie, Response, Void> ADD_TO_RESPONSE = new _.F2<Cookie, Response, Void>() { @Override public Void apply(Cookie cookie, Response response) throws NotAppliedException, _.Break { response.addCookie(cookie); return null; } }; } } // eof Cookie public static class KV<T extends KV> { protected Map<String, String> data = C.newMap(); private boolean dirty = false; private KV() {} private KV(Map<String, String> data) { E.NPE(data); this.data = data; } /** * Associate a string value with the key specified during * initialization. The difference between calling {@code load} * and {@link #put(String, String)} is the former will not change * the dirty tag */ public T load(String key, String val) { E.illegalArgumentIf(key.contains(":")); data.put(key, val); return me(); } /** * Associate a string value with the key specified. */ public T put(String key, String val) { E.illegalArgumentIf(key.contains(":")); dirty = true; return load(key, val); } /** * Associate an Object value's String representation with the * key specified. If the object is {@code null} then {@code null} * is associated with the key specified */ public T put(String key, Object val) { String valStr = null == val ? null : val.toString(); return put(key, valStr); } /** * Returns the string value associated with the key specified */ public String get(String key) { return data.get(key); } /** * Returns the key set of internal data map */ public Set<String> keySet() { return data.keySet(); } /** * Returns {@code true} if internal data map is empty */ public boolean isEmpty() { return data.isEmpty(); } /** * Indicate if the KV has been changed * * @return {@code true} if this instance has been changed */ public boolean dirty() { return dirty; } /** * Alias of {@link #dirty()} */ public boolean changed() { return dirty; } /** * Returns true if the internal data map is empty */ public boolean empty() { return data.isEmpty(); } /** * Returns true if an association with key specified exists in * the internal map */ public boolean containsKey(String key) { return data.containsKey(key); } /** * Alias of {@link #containsKey(String)} */ public boolean contains(String key) { return containsKey(key); } /** * Returns the number of assoications stored in the internal map */ public int size() { return data.size(); } /** * Release an association with key specified * @param key specify the k-v pair that should be removed from internal map * @return this instance */ public T remove(String key) { data.remove(key); return me(); } /** * Clear the internal data map. In other words, all * Key/Value association stored in this instance has been * release * * @return this instance */ public T clear() { data.clear(); return me(); } @Override public String toString() { return data.toString(); } protected T me() { return (T) this; } } /** * Defines a data structure to encapsulate a stateless session which * accept only {@code String} type value, and will be persisted at * client side as a cookie. This means the entire size of the * information stored in session including names and values shall * not exceed 4096 bytes. * <p/> * <p>To store typed value or big value, use the cache methods * of the session class. However it is subject to the implementation * to decide whether cache methods are provided and how it is * implemented</p> */ public static final class Session extends KV<Session> { /** * Session identifier */ public static final String KEY_ID = "___ID"; /** * Stores the expiration date in the session */ public static final String KEY_EXPIRATION = "___TS"; /** * Stores the authenticity token in the session */ public static final String KEY_AUTHENTICITY_TOKEN = "___AT"; /** * Used to mark if a session has just expired */ public static final String KEY_EXPIRE_INDICATOR = "___expired"; /** * Stores the fingerprint to the session */ public static final String KEY_FINGER_PRINT = "__FP"; private String id; public Session() { } /** * Returns the session identifier */ public String id() { if (null == id) { id = data.get(KEY_ID); if (null == id) { id = UUID.randomUUID().toString(); put(KEY_ID, id()); } } return id; } /** * Returns {@code true} if the session is empty. e.g. * does not contain anything else than the timestamp */ public boolean empty() { return super.empty() || (containsKey(KEY_EXPIRATION) && size() == 1); } /** * Check if the session is expired. A session is considered * to be expired if it has a timestamp and the timestamp is * non negative number and is less than {@link System#currentTimeMillis()} * * @return {@code true} if the session is expired */ public boolean expired() { long expiry = expiry(); if (expiry < 0) return false; return (expiry < System.currentTimeMillis()); } /** * Returns the expiration time in milliseconds of this session. If * there is no expiration set up, then this method return {@code -1} * * @return the difference, measured in milliseconds, between * the expiry of the session and midnight, January 1, * 1970 UTC, or {@code -1} if the session has no * expiry */ public long expiry() { String s = get(KEY_EXPIRATION); if (S.blank(s)) return -1; return Long.parseLong(s); } /** * Set session expiry in milliseconds * * @param expiry the difference, measured in milliseconds, between * the expiry and midnight, January 1, 1970 UTC. * @return the session instance */ public Session expireOn(long expiry) { put(KEY_EXPIRATION, S.string(expiry)); return this; } /* * Attach session id to a cache key */ private String k(String key) { return S.builder(id()).append(key).toString(); } private static volatile CacheService cs; private static CacheService cs() { if (null != cs) return cs; synchronized (H.class) { if (null == cs) { cs = HttpConfig.cacheService(); } return cs; } } /** * Store an object into cache using key specified. The key will be * appended with session id, so that it distinct between caching * using the same key but in different user sessions. * <p/> * <p>The object is cached for {@link org.osgl.cache.CacheService#setDefaultTTL(int) default} ttl</p> * * @param key the key to cache the object * @param obj the object to be cached * @return this session instance */ public Session cache(String key, Object obj) { cs().put(k(key), obj); return this; } /** * Store an object into cache with expiration specified * * @param key the key to cache the object * @param obj the object to be cached * @param expiration specify the cache expiration in seconds * @return this session instance * @see #cache(String, Object) */ public Session cache(String key, Object obj, int expiration) { cs().put(k(key), obj, expiration); return this; } /** * Store an object into cache for 1 hour * * @param key the key to cache the object * @param obj the object to be cached * @return the session instance */ public Session cacheFor1Hr(String key, Object obj) { return cache(key, obj, 60 * 60); } /** * Store an object into cache for 30 minutes * * @param key the key to cache the object * @param obj the object to be cached * @return the session instance */ public Session cacheFor30Min(String key, Object obj) { return cache(key, obj, 30 * 60); } /** * Store an object into cache for 10 minutes * * @param key the key to cache the object * @param obj the object to be cached * @return the session instance */ public Session cacheFor10Min(String key, Object obj) { return cache(key, obj, 10 * 60); } /** * Store an object into cache for 1 minutes * * @param key the key to cache the object * @param obj the object to be cached * @return the session instance */ public Session cacheFor1Min(String key, Object obj) { return cache(key, obj, 60); } /** * Evict an object from cache * * @param key the key to cache the object * @return this session instance */ public Session evict(String key) { cs().evict(k(key)); return this; } /** * Retrieve an object from cache by key. The key * will be attached with session id * * @param key the key to get the cached object * @param <T> the object type * @return the object in the cache, or {@code null} * if it cannot find the object by key * specified * @see #cache(String, Object) */ public <T> T cached(String key) { return cs.get(k(key)); } /** * Retrieve an object from cache by key. The key * will be attached with session id * * @param key the key to get the cached object * @param clz the class to specify the return type * @param <T> the object type * @return the object in the cache, or {@code null} * if it cannot find the object by key * specified * @see #cache(String, Object) */ public <T> T cached(String key, Class<T> clz) { return cs.get(k(key)); } /** * Return a session instance of the current execution context, * For example from a {@link java.lang.ThreadLocal} * * @return the current session instance */ public static Session current() { return Current.session(); } /** * Set a session instance into the current execution context, * for example into a {@link java.lang.ThreadLocal} * * @param session the session to be set to current execution context */ public static void current(Session session) { Current.session(session); } // used to parse session data persisted in the cookie value private static final Pattern _PARSER = Pattern.compile(S.HSEP + "([^:]*):([^" + S.HSEP + "]*)" + S.HSEP); /** * Resolve a Session instance from a session cookie * * @param sessionCookie the cookie corresponding to a session * @param ttl session time to live in seconds * @return a Session instance * @see #serialize(String) */ public static Session resolve(Cookie sessionCookie, int ttl) { Session session = new Session(); long expiration = System.currentTimeMillis() + ttl * 1000; boolean hasTtl = ttl > -1; String value = null == sessionCookie ? null : sessionCookie.value(); if (S.blank(value)) { if (hasTtl) { session.expireOn(expiration); } } else { int firstDashIndex = value.indexOf("-"); if (firstDashIndex > -1) { String signature = value.substring(0, firstDashIndex); String data = value.substring(firstDashIndex + 1); if (S.eq(signature, sign(data))) { String sessionData = Codec.decodeUrl(data, Charsets.UTF_8); Matcher matcher = _PARSER.matcher(sessionData); while (matcher.find()) { session.put(matcher.group(1), matcher.group(2)); } } } if (hasTtl && session.expired()) { session = new Session().expireOn(expiration); } } return session; } /** * Serialize this session into a cookie. Note the cookie * returned has only name, value maxAge been set. It's up * to the caller to set the secure, httpOnly and path * attributes * * @param sessionKey the cookie name for the session cookie * @return a cookie captures this session's information or {@code null} if * this session is empty or this session hasn't been changed and * there is no expiry * @see #resolve(org.osgl.http.H.Cookie, int) */ public Cookie serialize(String sessionKey) { long expiry = expiry(); boolean hasTtl = expiry > -1; boolean expired = !hasTtl && expiry < System.currentTimeMillis(); if (!changed() && !hasTtl) return null; if (empty() || expired) { // empty session, delete the session cookie return new H.Cookie(sessionKey).maxAge(0); } StringBuilder sb = S.builder(); for (String k : keySet()) { sb.append(S.HSEP); sb.append(k); sb.append(":"); sb.append(get(k)); sb.append(S.HSEP); } String data = Codec.encodeUrl(sb.toString(), Charsets.UTF_8); String sign = sign(data); String value = S.builder(sign).append("-").append(data).toString(); Cookie cookie = new Cookie(sessionKey).value(value); if (expiry > -1L) { int ttl = (int) ((expiry - System.currentTimeMillis()) / 1000); cookie.maxAge(ttl); } return cookie; } private static String sign(String s) { return Crypto.sign(s, s.getBytes(Charsets.UTF_8)); } } // eof Session /** * A Flash represent a storage scope that attributes inside is valid only * for one session interaction. This feature of flash makes it very good * for server to pass one time information to client, e.g. form submission * error message etc. * <p/> * <p>Like {@link org.osgl.http.H.Session}, you can store only String type * information to flash, and the total number of information stored * including keys and values shall not exceed 4096 bytes as flash is * persisted as cookie in browser</p> */ public static final class Flash extends KV<Flash> { // used to parse flash data persisted in the cookie value private static final Pattern _PARSER = Session._PARSER; /** * Stores the data that will be output to cookie so next time the user's request income * they will be available for the application to access */ private Map<String, String> out = C.newMap(); /** * Add an attribute to the flash scope. The data is * added to both data buffer and the out buffer * * @param key the key to index the attribute * @param value the value of the attribute * @return the flash instance */ public Flash put(String key, String value) { out.put(key, value); return super.put(key, value); } /** * Add an attribute to the flash scope. The value is in Object * type, however it will be convert to its {@link Object#toString() string * representation} before put into the flash * * @param key the key to index the attribute * @param value the value to be put into the flash * @return this flash instance */ public Flash put(String key, Object value) { return put(key, null == value ? null : value.toString()); } /** * Add an attribute to the flash's current scope. Meaning when next time * the user request to the server, the attribute will not be there anymore. * * @param key the attribute key * @param value the attribute value * @return the flash instance */ public Flash now(String key, String value) { return super.put(key, value); } /** * Add an "error" message to the flash scope * * @param message the error message * @return the flash instance * @see #put(String, Object) */ public Flash error(String message) { return put("error", message); } /** * Add an "error" message to the flash scope, with * optional format arguments * * @param message the message template * @param args the format arguments * @return this flash instance */ public Flash error(String message, Object... args) { return put("error", S.fmt(message, args)); } /** * Get the "error" message that has been added to * the flash scope. * * @return the "error" message or {@code null} if * no error message has been added to the flash */ public String error() { return get("error"); } /** * Add a "success" message to the flash scope * * @param message the error message * @return the flash instance * @see #put(String, Object) */ public Flash success(String message) { return put("success", message); } /** * Add a "success" message to the flash scope, with * optional format arguments * * @param message the message template * @param args the format arguments * @return this flash instance */ public Flash success(String message, Object... args) { return put("success", S.fmt(message, args)); } /** * Get the "success" message that has been added to * the flash scope. * * @return the "success" message or {@code null} if * no success message has been added to the flash */ public String success() { return get("success"); } /** * Discard a data from the output buffer of the flash but * the data buffer is remain untouched. Meaning * the app can still get the data {@link #put(String, Object)} * into the flash scope, however they will NOT * be write to the client cookie, thus the next * time client request the server, the app will * not be able to get the info anymore * * @param key the key to the data to be discarded * @return the flash instance */ public Flash discard(String key) { out.remove(key); return this; } /** * Discard the whole output buffer of the flash but * the data buffer is remain untouched. Meaning * the app can still get the data {@link #put(String, Object)} * into the flash scope, however they will NOT * be write to the client cookie, thus the next * time client request the server, the app will * not be able to get those info anymore * * @return the flash instance */ public Flash discard() { out.clear(); return this; } /** * Keep a data that has been {@link #put(String, Object) put} * into the flash for one time. The data that has been kept * will be persistent to client cookie for one time, thus * the next time when user request the server, the app * can still get the data, but only for one time unless * the app call {@code keep} method again * * @param key the key to identify the data to be kept * @see #keep() */ public Flash keep(String key) { if (super.containsKey(key)) { out.put(key, get(key)); } return this; } /** * Keep all data that has been {@link #put(String, Object) put} * into the flash for one time. The data that has been kept * will be persistent to client cookie for one time, thus * the next time when user request the server, the app * can still get the data, but only for one time unless * the app call {@code keep} method again * * @return the flash instance */ public Flash keep() { out.putAll(data); return this; } public KV out() { return new KV(out); } /** * Return a flash instance of the current execution context, * For example from a {@link java.lang.ThreadLocal} * * @return the current flash instance */ public static Flash current() { return Current.flash(); } /** * Set a flash instance into the current execution context, * for example into a {@link java.lang.ThreadLocal} * * @param flash the flash to be set to current execution context */ public static void current(Flash flash) { Current.flash(flash); } /** * Resolve a Flash instance from a cookie. If the cookie supplied * is {@code null} then an empty Flash instance is returned * * @param flashCookie the flash cookie * @return a Flash instance * @see #serialize(String) */ public static Flash resolve(Cookie flashCookie) { Flash flash = new Flash(); if (null != flashCookie) { String value = flashCookie.value(); if (S.notBlank(value)) { String s = Codec.decodeUrl(value, Charsets.UTF_8); Matcher m = _PARSER.matcher(s); while (m.find()) { flash.data.put(m.group(1), m.group(2)); } } } return flash; } /** * Serialize this Flash instance into a Cookie. Note * the cookie returned has only name, value and max Age * been set. It's up to the caller to set secure, path * and httpOnly attributes. * * @param flashKey the cookie name * @return a Cookie represent this flash instance * @see #resolve(org.osgl.http.H.Cookie) */ public Cookie serialize(String flashKey) { if (out.isEmpty()) { return new Cookie(flashKey).maxAge(0); } StringBuilder sb = S.builder(); for (String key : out.keySet()) { sb.append(S.HSEP); sb.append(key); sb.append(":"); sb.append(out.get(key)); sb.append(S.HSEP); } String value = Codec.encodeUrl(sb.toString(), Charsets.UTF_8); return new Cookie(flashKey).value(value); } } // eof Flash /** * Defines the HTTP request trait * * @param <T> the type of the implementation class */ public static abstract class Request<T extends Request> { private static SimpleDateFormat dateFormat; static { dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } /** * Returns the class of the implementation. Not to be used * by application */ protected abstract Class<T> _impl(); private Format accept; private Format contentType; private String ip; private int port = -1; private State state = State.NONE; protected volatile InputStream inputStream; protected volatile Reader reader; private Map<String, Cookie> cookies = C.newMap(); /** * Returns the HTTP method of the request */ public abstract Method method(); /** * Returns the header content by name. If there are * multiple headers with the same name, then the first * one is returned. If there is no header has the name * then {@code null} is returned * <p/> * <p>Note header name is case insensitive</p> * * @param name the name of the header * @return the header content */ public abstract String header(String name); /** * Returns all header content by name. This method returns * content of all header with the same name specified in * an {@link java.lang.Iterable} of {@code String}. If there * is no header has the name specified, then an empty iterable * is returned. * <p/> * <p>Note header name is case insensitive</p> * * @param name the name of the header * @return all values of the header */ public abstract Iterable<String> headers(String name); /** * Return the request {@link org.osgl.http.H.Format accept} * * @return the request accept */ public Format accept() { if (null == accept) { resolveAcceptFormat(); } return accept; } /** * Set {@link org.osgl.http.H.Format accept} to the request * @param fmt * @return this request */ public Request accept(Format fmt) { E.NPE(fmt); this.accept = fmt; return this; } /** * Check if the request is an ajax call * * @return {@code true} if it is an ajax call */ public boolean isAjax() { return S.eq(header(X_REQUESTED_WITH), "XMLHttpRequest"); } /** * Returns the path of the request. This does not include the * context path. The path is a composite of * {@link javax.servlet.http.HttpServletRequest#getServletPath()} * and {@link javax.servlet.http.HttpServletRequest#getPathInfo()} * <p/> * <p> * The path starts with "/" but not end with "/" * </p> */ public abstract String path(); /** * Returns the context path of the request. * The context path starts with "/" but not end * with "/". If there is no context path * then and empty "" is returned */ public abstract String contextPath(); /** * Returns the full URI path. It's composed of * {@link #contextPath()} and {@link #path()} * The full path starts with "/" */ public String fullPath() { return Path.url(path(), this); } /** * Alias of {@link #fullPath()} * * @return the full URL path of the request */ public String url() { return fullPath(); } /** * Returns the full URL including scheme, domain, port and * full request path plus query string * * @return the absolute URL */ public String fullUrl() { return Path.fullUrl(path(), this); } /** * Returns query string or an empty String if the request * doesn't contains a query string */ public abstract String query(); /** * Check if the request was made on a secure channel * * @return {@code true} if this is a secure request */ public abstract boolean secure(); /** * Returns the scheme of the request, specifically one of the * "http" and "https" * * @return the scheme of the request */ public String scheme() { return secure() ? "https" : "http"; } protected void _setCookie(String name, Cookie cookie) { cookies.put(name, cookie); } private String domain; /** * Returns the domain of the request */ public String domain() { if (null == domain) resolveIp(); return domain; } /** * Returns the port */ public int port() { if (-1 == port) resolveIp(); return port; } /** * Returns remote ip address */ protected abstract String _ip(); private void resolveIp() { // remoteAddress String rmt = _ip(); if (!HttpConfig.isXForwardedAllowed(rmt)) { ip = rmt; } String s = header(X_FORWARDED_FOR); ip = S.blank(s) ? rmt : s; // host and port String host = header(X_FORWARDED_HOST); if (S.empty(host)) { host = header(HOST); } if (null != host) { FastStr fs = FastStr.unsafeOf(host); if (fs.contains(':')) { domain = fs.beforeFirst(':').toString(); try { port = Integer.parseInt(fs.afterFirst(':').toString()); } catch (NumberFormatException e) { port = defPort(); logger.error(e, "Error parsing port number: %s", S.after(host, ":")); } } else { domain = host; port = defPort(); } } else { domain = ""; port = defPort(); } } private int defPort() { return secure() ? 80 : 443; } public String ip() { if (null == ip) { resolveIp(); } return ip; } public String userAgentStr() { return header(USER_AGENT); } public UserAgent userAgent() { return UserAgent.parse(userAgentStr()); } protected abstract void _initCookieMap(); /** * Returns cookie by it's name * * @param name the cookie name * @return the cookie or {@code null} if not found */ public H.Cookie cookie(String name) { if (cookies.isEmpty()) { _initCookieMap(); } return cookies.get(name); } /** * Returns all cookies of the request in Iterable */ public List<H.Cookie> cookies() { if (cookies.isEmpty()) { _initCookieMap(); } return C.list(cookies.values()); } /** * resolve the request accept * * @return this request instance */ private T resolveAcceptFormat() { String accept = header(ACCEPT); this.accept = Format.resolve(accept); return (T) this; } /** * Check if the requested resource is modified with etag and * last timestamp (usually the timestamp of a static file e.g.) * * @param etag the etag to compare with "If_None_Match" * header in browser * @param since the last timestamp to compare with * "If_Modified_Since" header in browser * @return {@code true} if the resource has changed * or {@code false} otherwise */ public boolean isModified(String etag, long since) { String browserEtag = header(IF_NONE_MATCH); if (null == browserEtag) return true; if (!S.eq(browserEtag, etag)) { return true; } String s = header(IF_MODIFIED_SINCE); if (null == s) return true; try { Date browserDate = dateFormat.parse(s); if (browserDate.getTime() >= since) { return false; } } catch (ParseException ex) { logger.error(ex, "Can't parse date: %s", s); } return true; } private void parseContentTypeAndEncoding() { String type = header(CONTENT_TYPE); if (null == type) { contentType = Format.html; encoding = "utf-8"; } else { String[] contentTypeParts = type.split(";"); String _contentType = contentTypeParts[0].trim().toLowerCase(); String _encoding = "utf-8"; // check for encoding-info if (contentTypeParts.length >= 2) { String[] encodingInfoParts = contentTypeParts[1].split(("=")); if (encodingInfoParts.length == 2 && encodingInfoParts[0].trim().equalsIgnoreCase("charset")) { // encoding-info was found in request _encoding = encodingInfoParts[1].trim(); if (S.notBlank(_encoding) && ((_encoding.startsWith("\"") && _encoding.endsWith("\"")) || (_encoding.startsWith("'") && _encoding.endsWith("'"))) ) { _encoding = _encoding.substring(1, _encoding.length() - 1).trim(); } } } contentType = Format.resolve(_contentType); encoding = _encoding; } } /** * Return content type of the request */ public Format contentType() { if (null == contentType) { parseContentTypeAndEncoding(); } return contentType; } private String encoding; /** * Returns encoding of the request */ public String characterEncoding() { if (null == encoding) { parseContentTypeAndEncoding(); } return encoding; } private C.List<Locale> locales; private void parseLocales() { String s = header(ACCEPT_LANGUAGE); if (S.blank(s)) { locales = C.list(HttpConfig.defaultLocale()); return; } // preprocess to remove all blanks s = S.str(s).remove(new _.F1<Character, Boolean>() { @Override public Boolean apply(Character character) { char c = character; return c == ' ' || c == '\t'; } }).toString(); ListBuilder<Locale> lb = ListBuilder.create(); // parse things like "da,en-gb;q=0.8,en;q=0.7" String[] sa = s.split(","); for (String s0 : sa) { // just ignore q=xx s0 = S.beforeFirst(s0, ";"); String[] sa1 = s0.split("-"); String lang = sa1[0]; String country = ""; String variant = ""; if (sa1.length > 1) { country = sa[1]; } if (sa1.length > 2) { variant = sa[2]; } lb.add(new Locale(lang, country, variant)); } if (lb.isEmpty()) lb.add(HttpConfig.defaultLocale()); locales = lb.toList(); } /** * Returns locale of the request */ public Locale locale() { if (null == locales) parseLocales(); return locales.get(0); } /** * Returns all locales of the request */ public C.List<Locale> locales() { if (null == locales) parseLocales(); return locales; } private long len = -2; /** * Returns the content length of the request */ public long contentLength() { if (len > -2) return len; String s = header(CONTENT_LENGTH); if (S.blank(s)) { len = -1; } else { try { len = Long.parseLong(s); } catch (NumberFormatException e) { len = -1; logger.error("Error parsing content-length: %s", s); } } return len; } public boolean readerCreated() { return state == State.READER; } protected abstract InputStream createInputStream(); public InputStream inputStream() throws IllegalStateException { return state.inputStream(this); } private void createReader() { if (null != reader) { return; } synchronized (this) { if (null != reader) { return; } createInputStream(); String charset = characterEncoding(); Charset cs = null == charset ? Charsets.UTF_8 : Charset.forName(charset); reader = new InputStreamReader(inputStream(), cs); } } public Reader reader() throws IllegalStateException { return state.reader(this); } /** * Return a request parameter value by name. If there is no parameter * found with the name specified, then {@code null} is returned. If * there are multiple values associated with the name, then the * first one is returned * * @param name the parameter name * @return the parameter value of {@code null} if not found */ public abstract String paramVal(String name); /** * Returns all values associated with the name specified in the * http request. If there is no parameter found with the name, * then {@code new String[0]} shall be returned * * @param name the parameter name * @return all values of the parameter */ public abstract String[] paramVals(String name); /** * Return all parameter names * * @return an {@link java.lang.Iterable} of parameter names */ public abstract Iterable<String> paramNames(); private void parseAuthorization() { if (null != user) return; user = ""; password = ""; String s = header(AUTHORIZATION); if (null != s && s.startsWith("Basic")) { String data = s.substring(6); String[] decodedData = new String(Codec.decodeBASE64(data)).split(":"); user = decodedData.length > 0 ? decodedData[0] : null; password = decodedData.length > 1 ? decodedData[1] : null; } } private String user; /** * The Http Basic user */ public String user() { if (null == user) parseAuthorization(); return user; } private String password; /** * the Http Basic password */ public String password() { if (null == password) parseAuthorization(); return password; } /** * Return a request instance of the current execution context, * For example from a {@link java.lang.ThreadLocal} * * @return the current request instance */ @SuppressWarnings("unchecked") public static <T extends Request> T current() { return (T) Current.request(); } /** * Set a request instance into the current execution context, * for example into a {@link java.lang.ThreadLocal} * * @param request the request to be set to current execution context */ public static <T extends Request> void current(T request) { Current.request(request); } private enum State { NONE, STREAM() { @Override Reader reader(Request req) { throw new IllegalStateException("reader() already called"); } }, READER() { @Override InputStream inputStream(Request req) { throw new IllegalStateException("inputStream() already called"); } }; InputStream inputStream(Request req) { req.inputStream = req.createInputStream(); req.state = STREAM; return req.inputStream; } Reader reader(Request req) { req.createReader(); req.state = READER; return req.reader; } } } // eof Request /** * Defines the HTTP response trait */ public static abstract class Response<T extends Response> { private State state = State.NONE; protected volatile OutputStream outputStream; protected volatile Writer writer; /** * Returns the class of the implementation. Not to be used * by application */ protected abstract Class<T> _impl(); public boolean writerCreated() { return state == State.WRITER; } protected abstract OutputStream createOutputStream(); private void createWriter() { if (null != writer) { return; } synchronized (this) { if (null != writer) { return; } outputStream = createOutputStream(); String charset = characterEncoding(); Charset cs = null == charset ? Charsets.UTF_8 : Charset.forName(charset); writer = new OutputStreamWriter(outputStream, cs); } } public OutputStream outputStream() throws IllegalStateException, UnexpectedIOException { return state.outputStream(this); } public Writer writer() throws IllegalStateException, UnexpectedIOException { return state.writer(this); } public PrintWriter printWriter() { Writer w = writer(); if (w instanceof PrintWriter) { return (PrintWriter) w; } else { return new PrintWriter(w); } } public abstract String characterEncoding(); /** * Returns the content type used for the MIME body * sent in this response. The content type proper must * have been specified using {@link #contentType(String)} * before the response is committed. If no content type * has been specified, this method returns null. * If a content type has been specified, and a * character encoding has been explicitly or implicitly * specified as described in {@link #characterEncoding()} * or {@link #writer()} has been called, * the charset parameter is included in the string returned. * If no character encoding has been specified, the * charset parameter is omitted. * * @return a <code>String</code> specifying the * content type, for example, * <code>text/html; charset=UTF-8</code>, * or null */ public abstract T characterEncoding(String encoding); /** * Set the length of the content to be write to the response * * @param len an long value specifying the length of the * content being returned to the client; sets * the Content-Length header * @return the response it self * @see #outputStream * @see #writer */ public abstract T contentLength(long len); /** * Sub class to overwrite this method to set content type to * the response * * @param type a <code>String</code> specifying the MIME * type of the content */ protected abstract void _setContentType(String type); private String contentType; /** * Sets the content type of the response being sent to * the client. The content type may include the type of character * encoding used, for example, <code>text/html; charset=ISO-8859-4</code>. * If content type has already been set to the response, this method * will update the content type with the new value * <p/> * <p>this method must be called before calling {@link #writer()} * or {@link #outputStream()}</p> * * @param type a <code>String</code> specifying the MIME * type of the content * @return the response it self * @see #outputStream * @see #writer * @see #initContentType(String) */ public T contentType(String type) { _setContentType(type); contentType = type; return (T) this; } /** * This method set the content type to the response if there * is no content type been set already. * * @param type a <code>String</code> specifying the MIME * type of the content * @return the response it self * @see #contentType(String) */ public T initContentType(String type) { return (null == contentType) ? contentType(type) : (T) this; } /** * Sets the locale of the response, setting the headers (including the * Content-Type's charset) as appropriate. This method should be called * before a call to {@link #writer()}. By default, the response locale * is the default locale for the server. * * @param loc the locale of the response * @see #locale() */ protected abstract void _setLocale(Locale loc); public T locale(Locale locale) { _setLocale(locale); return (T) this; } /** * Returns the locale assigned to the response. * * @see #locale(java.util.Locale) */ public abstract Locale locale(); /** * Adds the specified cookie to the response. This method can be called * multiple times to add more than one cookie. * * @param cookie the Cookie to return to the client */ public abstract void addCookie(H.Cookie cookie); /** * Returns a boolean indicating whether the named response header * has already been set. * * @param name the header name * @return <code>true</code> if the named response header * has already been set; * <code>false</code> otherwise */ public abstract boolean containsHeader(String name); public abstract T sendError(int sc, String msg); public T sendError(int sc, String msg, Object... args) { return sendError(sc, S.fmt(msg, args)); } public abstract T sendError(int sc); public abstract T sendRedirect(String location); public abstract T header(String name, String value); /** * Sets the status code for this response. This method is used to * set the return status code when there is no error (for example, * for the status codes SC_OK or SC_MOVED_TEMPORARILY). If there * is an error, and the caller wishes to invoke an error-page defined * in the web application, the <code>sendError</code> method should be used * instead. * <p> The container clears the buffer and sets the Location header, preserving * cookies and other headers. * * @param sc the status code * @return the response itself * @see #sendError * @see #status(org.osgl.http.H.Status) */ public abstract T status(int sc); /** * Sets the status for this response. This method is used to * set the return status code when there is no error (for example, * for the status OK or MOVED_TEMPORARILY). If there * is an error, and the caller wishes to invoke an error-page defined * in the web application, the <code>sendError</code> method should be used * instead. * <p> The container clears the buffer and sets the Location header, preserving * cookies and other headers. * * @param s the status * @return the response itself * @see #sendError */ public T status(Status s) { status(s.code); return (T) this; } public abstract T addHeader(String name, String value); /** * Write a string to the response * * @param s the string to write to the response * @return this response itself */ public T writeContent(String s) { try { IO.write(s.getBytes(characterEncoding()), outputStream()); } catch (UnsupportedEncodingException e) { throw E.encodingException(e); } return (T) this; } /** * Write content to the response * * @param content the content to write * @return the response itself */ public T writeText(String content) { _setContentType(Format.txt.toContentType()); return writeContent(content); } /** * Write content to the response * * @param content the content to write * @return the response itself */ public T writeHtml(String content) { _setContentType(Format.html.toContentType()); return writeContent(content); } /** * Write content to the response * * @param content the content to write * @return the response itself */ public T writeJSON(String content) { _setContentType(Format.json.toContentType()); return writeContent(content); } /** * Calling this method commits the response, meaning the status * code and headers will be written to the client */ public abstract void commit(); /** * Return a request instance of the current execution context, * For example from a {@link java.lang.ThreadLocal} * * @return the current request instance */ @SuppressWarnings("unchecked") public static <T extends Response> T current() { return (T) Current.response(); } /** * Set a request instance into the current execution context, * for example into a {@link java.lang.ThreadLocal} * * @param response the request to be set to current execution context */ public static <T extends Response> void current(T response) { Current.response(response); } private enum State { NONE, STREAM() { @Override Writer writer(Response resp) { throw new IllegalStateException("writer() already called"); } }, WRITER() { @Override OutputStream outputStream(Response resp) { throw new IllegalStateException("outputStream() already called"); } }; OutputStream outputStream(Response resp) { resp.outputStream = resp.createOutputStream(); resp.state = STREAM; return resp.outputStream; } Writer writer(Response resp) { resp.createWriter(); resp.state = WRITER; return resp.writer; } } } // eof Response H() { } /** * Clear all current context */ public static void cleanUp() { Current.clear(); } }
package slieb.kute; import slieb.kute.api.Resource; import slieb.kute.providers.FilteredResourceProvider; import slieb.kute.providers.MappedResourceProvider; import slieb.kute.providers.URLArrayResourceProvider; import slieb.kute.resources.*; import slieb.kute.utils.KuteIO; import slieb.kute.utils.KuteLambdas; import slieb.kute.utils.SupplierWithIO; import java.io.*; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class Kute { /** * Provides the {@link ClassLoader} instance. Found from {@code Thread.currentThread().getContextClassLoader()} * or {@code Kute.class.getClassLoader()} * * @return The default classloader. */ public static ClassLoader getDefaultClassLoader() { try { return Thread.currentThread().getContextClassLoader(); } catch (Exception ignored) { return Kute.class.getClassLoader(); } } /** * Provides a {@link slieb.kute.api.Resource.Provider} that wraps around the default classLoader. * * @return A default provider that wraps a resource provider around a classLoader. * @see Kute#getDefaultClassLoader() * @see Kute#getProvider(ClassLoader) */ public static Resource.Provider getDefaultProvider() { return getProvider(getDefaultClassLoader()); } /** * @param urls An array of urls where the provider can search for resources. Only jar and directory urls are * supported. * @return An {@link URLArrayResourceProvider} class that will provide all the resources in the array of urls. */ public static URLArrayResourceProvider getProvider(List<URL> urls) { return new URLArrayResourceProvider(urls); } /** * @param classLoader The classloader from which to search for resources. Currently only implementations of * {@link URLClassLoader} are scanned. * @return A Resource provider that will scan the classloader. */ public static Resource.Provider getProvider(ClassLoader classLoader) { List<URL> urls = new ArrayList<>(); while (classLoader != null) { if (classLoader instanceof URLClassLoader) { Collections.addAll(urls, ((URLClassLoader) classLoader).getURLs()); } classLoader = classLoader.getParent(); } return getProvider(urls); } /** * Returns a empty resource provider. * * @return a resource provider that returns nothing. */ public static Resource.Provider emptyProvider() { return Stream::empty; } /** * @param resources A var_arg array of resources that the provider will contain. * @return A {@link slieb.kute.api.Resource.Provider} that contains all of the specified resources. */ public static Resource.Provider providerOf(Resource.Readable... resources) { return providerOf(Arrays.asList(resources)); } /** * @param resources A collection of resources that the provider will contain. * @return A {@link slieb.kute.api.Resource.Provider} that contains all of the specified resources. */ public static Resource.Provider providerOf(Collection<Resource.Readable> resources) { return resources::stream; } /** * Group ResourceProviders together into one resources Resource Provider. * <p> * {@code * Resource.Provider providerA = Kute.directoryProvider(new File("images/")); * Resource.Provider classpathProvider = Kute.getDefaultProvider(); * Resource.Provider provider = Kute.group(providerA, classpathProvider); * } * * @param providers The resource providers to group. * @return A resource provider that providers resources for all the given resource providers. */ public static Resource.Provider group(Resource.Provider... providers) { return group(() -> Arrays.stream(providers)); } public static Resource.Provider group(Collection<Resource.Provider> providers) { return group(providers::stream); } public static Resource.Provider group(Supplier<Stream<Resource.Provider>> providers) { return () -> distinctPath(providers.get().flatMap(Resource.Provider::stream)); } public static Resource.Readable memoryResource(Resource.Readable readable) throws IOException { return Kute.resourceWithBytes(readable.getPath(), KuteIO.readBytes(readable)); } /** * Create a file Resource * * @param file A file that will provide the contents and path of this resource. * @return A file resource that will provide the file contents when needed. */ public static FileResource fileResource(File file) { return new FileResource(file); } /** * Create a file resource. * * @param file A file that will provide the contents of this resource. * @param path The path this resource should be available at. * @return A file resource that will provide the file contents when needed. */ public static FileResource fileResource(String path, File file) { return new FileResource(path, file); } /** * Create a resource with alternate name * * @param resource Any resource. * @param path The new path location for this resource. * @return A resource of type A extends Resource that is a copy of the old resource, but with a new name. */ public static RenamedPathResource renameResource(String path, Resource.Readable resource) { return new RenamedPathResource(path, resource); } /** * Create resources from input stream. * * @param supplier The input stream to supply content. * @param path The path name for this resource. * @return a readable resource that reads from provided input stream. */ public static InputStreamResource inputStreamResource(String path, SupplierWithIO<InputStream> supplier) { return new InputStreamResource(path, supplier); } /** * Create resources from input stream. * * @param supplier The input stream to supply content. * @param path The path name for this resource. * @return a readable resource that reads from provided input stream. */ public static OutputStreamResource outputStreamResource(final String path, final SupplierWithIO<OutputStream> supplier) { return new OutputStreamResource(path, supplier); } public static Resource.Readable resourceWithBytes(final String path, final byte[] bytes) { return resourceWithByteSupplier(path, SupplierWithIO.ofInstance(bytes)); } public static Resource.Readable resourceWithByteSupplier(final String path, final SupplierWithIO<byte[]> byteSupplier) { return inputStreamResource(path, () -> new ByteArrayInputStream(byteSupplier.getWithIO())); } /** * Create a resource that cache's its response. * * @param resource A readable resource instance. * @return A readable resource that will cache the contents of another readable resource, to speed things up. Use * with caution. */ public static CachedResource cacheResource(Resource.Readable resource) { return new CachedResource(resource); } public static Resource.Readable stringResource(String path, String content) { return resourceWithBytes(path, content.getBytes()); } public static Resource.Readable stringResource(String path, Supplier<String> supplier) { return resourceWithByteSupplier(path, () -> supplier.get().getBytes()); } public static URLResource urlResource(final String path, final URL url) { return new URLResource(path, url); } public static RenamedPathResource zipEntryResource(String path, ZipFile zipFile, ZipEntry zipEntry) { return renameResource(path, zipEntryResource(zipFile, zipEntry)); } public static Resource.Provider mapResources(final Resource.Provider provider, final Function<Resource.Readable, Resource.Readable> function) { return new MappedResourceProvider(provider, function); } public static Resource.Provider filterResources(Resource.Provider provider, Predicate<? super Resource> predicate) { return new FilteredResourceProvider(provider, (Serializable & Predicate<? super Resource>) predicate); } public static Resource.Readable zipEntryResource(final ZipFile zipFile, ZipEntry zipEntry) { return inputStreamResource(zipEntry.getName(), () -> zipFile.getInputStream(zipEntry)); } public static <R extends Resource> Optional<R> findFirstResource(Stream<R> stream) { return stream.filter(KuteLambdas.nonNull()).findFirst(); } public static <R extends Resource> Optional<R> findFirstOptionalResource(Stream<Optional<R>> optionalStream) { return optionalStream.filter(Optional::isPresent).map(Optional::get).findFirst(); } /** * Finds the first resource in stream that matches given path. * * @param stream A stream of resources. * @param path The path to search for. * @param <R> The resource implementation. * @return A matching resource, if found. */ public static <R extends Resource> Optional<R> findResource(Stream<R> stream, String path) { return findFirstResource(stream.filter(r -> r.getPath().equals(path))); } /** * @param stream The unfiltered resource stream. * @param function A function to map resources into values that we will check for duplicates on. * @param <R> The generic resource implementation. * @param <X> The generic value type. * @return A stream without resource duplicates as determined by the passed function. */ public static <R extends Resource, X> Stream<R> distinct(final Stream<R> stream, final Function<R, X> function) { return stream.filter(KuteLambdas.distinctFilter(function)); } /** * @param stream The resource stream. * @param <R> The resource implementation. * @return A stream that has been filtered from resources with duplicate paths. */ public static <R extends Resource> Stream<R> distinctPath(Stream<R> stream) { return distinct(stream, Resource::getPath); } public static MutableResource mutableResource(String s, String s1) { return new MutableResource(s, s1.getBytes()); } }
package com.RoboWars; import java.util.Observable; import java.util.Observer; import com.RoboWars.opengl.MediaClient; import com.RoboWars.opengl.OpenGLRenderer; import com.RoboWars.opengl.Point3D; import com.RoboWars.opengl.mesh.Cube; import com.RoboWars.opengl.mesh.SimplePlane; import robowars.server.controller.ClientCommand; import robowars.shared.model.GameEntity; import robowars.shared.model.GameModel; import robowars.shared.model.Obstacle; import robowars.shared.model.Posture; import robowars.shared.model.Vector; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; public class RoboWars extends Activity implements SensorEventListener, Observer { /** The minimum interval at which orientation updates should be pushed to the server */ public static final long ORIENTATION_MINIMUM_INTERVAL_MS = 300; /** The maximum interval at which orientation updates should be pushed to the server */ public static final long ORIENTATION_MAXIMUM_INTERVAL_MS = 2000; /** * The threshold for input change that should prompt an immediate update * to the server (all orientations are scaled to a range of -1 to 1 before * this comparison is applied). */ public static final float ORIENTATION_DELTA_THRESHOLD = (float)0.10; /* The TabHost. */ TabHost tabHost; /* Views invoked by the application. */ private TextView chat, users; private EditText entry, server, port, user; private Button launch; private CheckBox spectatorButton, readyButton; /* Check if we're ready/spectator. */ private boolean spectator, ready; /** The time at which the reading of the orientation sensor was last updated */ private long lastOrientationUpdate; private LobbyModel lobbyModel; // Model for the lobby. private com.RoboWars.ClientGameModel gameModel; // Model for the game. private TcpClient tcp; // TCP controller. private String userlist; // Users currently in the lobby. private SensorManager mSensorManager; // Manages the accelerometer and other sensors. TextView mTextViewAcc; // Text view for accelerometer. TextView mTextViewMag; // Text view for magnetic field. TextView mTextViewOri; // Text view for orientation. private static final int MAX_LINES = 12; // Max lines to show in the chat lobby. /** MediaPlayer used to display streaming video */ private MediaClientTab mediaClient; /** The last values for each orientation vector that were sent to the server */ private double lastAzimuth, lastPitch, lastRoll; // OpenGL Variables. private boolean inOpenGL; private OpenGLRenderer renderer; private MediaClient mClient; private SimplePlane plane; private Point3D currentDrawCoords; /** * Creates a tab view. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); tabHost=(TabHost)findViewById(R.id.tabHost); tabHost.setCurrentTab(0); tabHost.setup(); tabHost.setKeepScreenOn(true); /* First tab (Webcam interface; control the robot from here). */ TabSpec spec1=tabHost.newTabSpec("Main"); spec1.setIndicator("Main"); spec1.setContent(R.id.tab1); /* Second tab (Lobby interface, contains chat and userlist). */ TabSpec spec2=tabHost.newTabSpec("Lobby"); spec2.setIndicator("Lobby"); spec2.setContent(R.id.tab2); /* Third tab (Configuration, contains username and server information). */ TabSpec spec3=tabHost.newTabSpec("Config"); spec3.setIndicator("Config"); spec3.setContent(R.id.tab3); /* Fourth tab (MediaPlayer). */ TabSpec spec4=tabHost.newTabSpec("Video"); spec4.setIndicator("Video"); spec4.setContent(R.id.tab4); /* Add the tabs to the tabHost. */ tabHost.addTab(spec1); tabHost.addTab(spec2); tabHost.addTab(spec3); tabHost.addTab(spec4); /* Instantiate the model and add the view as an observer. */ lobbyModel = new LobbyModel(); gameModel = new ClientGameModel(); lobbyModel.addObserver(this); gameModel.addObserver(this); lobbyModel.setVersion(getString(R.string.version)); /* Reference to the application's widgets. */ chat = (TextView) findViewById(R.id.chat); users = (TextView) findViewById(R.id.users); entry = (EditText) findViewById(R.id.entry); server = (EditText) findViewById(R.id.server); port = (EditText) findViewById(R.id.port); user = (EditText) findViewById(R.id.username); launch = (Button) findViewById(R.id.launchButton); spectatorButton = (CheckBox) findViewById(R.id.spectatorCheckBox); readyButton = (CheckBox) findViewById(R.id.readyCheckBox); /* Setup the sensor manager. */ // Use these lines if using Android emulator. //mSensorManager = SensorManagerSimulator.getSystemService(this, SENSOR_SERVICE); //mSensorManager.connectSimulator(); // Use this line if using phone application. mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); /* Allow scrolling of the chat and user list. */ chat.setMovementMethod(new ScrollingMovementMethod()); users.setMovementMethod(new ScrollingMovementMethod()); lastOrientationUpdate = 0; /* Setup the media client */ ImageStreamView mediaView = (ImageStreamView) findViewById(R.id.mediaSurface); TextView mediaStatus = (TextView) findViewById(R.id.mediaStatus); mediaClient = new MediaClientTab(mediaView, mediaStatus); lastAzimuth = 0; lastPitch = 0; lastRoll = 0; /* Initially blank user list. */ userlist = ""; /* Initially not ready and not spectator. */ ready = spectator = false; inOpenGL = false; launch.setEnabled(false); } /** * Print a message in the chat lobby. * @param msg */ public void printMessage(final String msg, int type) { this.runOnUiThread(new Runnable(){ public void run(){ chat.append(msg + "\n"); if (chat.getLineCount() > MAX_LINES) chat.scrollBy(0, chat.getLineHeight()); } }); } /** * Refreshes the lobby user list. */ public void updateUsers() { this.runOnUiThread(new Runnable(){ public void run(){ users.setText(""); users.append(userlist); } }); } /** * Method called whenever a button is pressed. * Determines which button was pressed by getting the * view's ID, then act accordingly. */ public void buttonClicked(View view) { ClientCommand cmd; switch (view.getId()) { /* Connect (to TCP server) button. */ case (R.id.connect): // Obtain login information. String username = user.getText().toString(); String address = server.getText().toString(); int portNumber = Integer.parseInt(port.getText().toString()); // Disable the 'Connect' button. view.setEnabled(false); // Establish connection. lobbyModel.setMyUser(new User(username)); tcp = new TcpClient(lobbyModel, gameModel); tcp.connect(address, portNumber); mediaClient.launchMediaStream(portNumber + 1); break; /* Send button. */ case (R.id.send): // Get the text and set the entry field blank. String message = entry.getText().toString(); entry.setText(""); // Try to generate a client command, send the string as a // chat message if command generation fails //ClientCommand cmd = ClientCommand.parse(message); if (tcp != null) { cmd = new ClientCommand(ClientCommand.CHAT_MESSAGE); cmd.setStringData(message); tcp.sendClientCommand(cmd); } break; /* Spectator checkbox. If there is a TCP connection, inform the server * of the status change. */ case (R.id.spectatorCheckBox): if (spectator == true) spectator = false; else spectator = true; if (tcp != null) { cmd = new ClientCommand(ClientCommand.SPECTATOR_STATUS); cmd.setBoolData(spectator); tcp.sendClientCommand(cmd); } break; /* Ready checkbox. If there is a TCP connection, inform the server * of the status change.*/ case (R.id.readyCheckBox): if (ready) { ready = false; launch.setEnabled(false); } else { ready = true; launch.setEnabled(true); } if (tcp != null) { cmd = new ClientCommand(ClientCommand.READY_STATUS); cmd.setBoolData(ready); tcp.sendClientCommand(cmd); } break; /* Launch button. */ case (R.id.launchButton): if (tcp != null) { cmd = new ClientCommand(ClientCommand.LAUNCH_GAME); cmd.setBoolData(true); tcp.sendClientCommand(cmd); ready = false; spectator = false; spectatorButton.setChecked(false); readyButton.setChecked(false); tabHost.setCurrentTab(R.id.tab4); } break; case (R.id.goOpenGL): if (!inOpenGL) goToOpenGLView(); break; default: printMessage("Unknown button pressed.", LobbyModel.ERROR); } } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME); } @Override protected void onStop() { mSensorManager.unregisterListener(this); super.onStop(); } /** * Updates based on changes to the model. */ public void update(Observable observable, Object data) { // OpenGL change. if (data instanceof GameModel) { // Check if the game finished. If so, stop the game. if (!gameModel.gameInProgress()) { goToLobbyView(); return; } // Check if we're in OpenGL... If not, go into OpenGL and draw the walls. if (!inOpenGL) { goToOpenGLView(); for (Obstacle e : gameModel.getObstacles()) drawGameEntity(e, 20f); } // Draw the players and projectiles. else { } } // Check for new chat message. if (lobbyModel.newChatMessage()) { printMessage(lobbyModel.getChatBuffer(), lobbyModel.getChatBufferType()); } // Check for changes in the user list. if (lobbyModel.usersUpdated()) { userlist = lobbyModel.getUsers(); updateUsers(); } } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { // TODO: Currently assumes orientation events are the only events // that will be received. // Scale all values to 1 to -1 range float azimuth = (event.values[0] - 180) / 180; // Azimuth sensor standard range 0 to 360 float pitch = (clamp(-event.values[2], -45, 45) / 45); // Pitch sensor standard range -90 to 90 float roll = (clamp(event.values[1], -45, 45) / 45); // Roll sensor standard range -180 to 180 // Set the text display on client side /* mTextViewOri.setText("Orientation:\n" + "Azimuth: " + azimuth + " (" + event.values[0] + ")\n" + "Pitch: " + pitch + " (" + event.values[2] + ")\n" + "Roll: " + roll + " (" + event.values[1] + ")\n"); */ if(System.currentTimeMillis() - lastOrientationUpdate > ORIENTATION_MAXIMUM_INTERVAL_MS || (System.currentTimeMillis() - lastOrientationUpdate > ORIENTATION_MINIMUM_INTERVAL_MS && (Math.abs(azimuth - lastAzimuth) > ORIENTATION_DELTA_THRESHOLD || Math.abs(pitch - lastPitch) > ORIENTATION_DELTA_THRESHOLD || Math.abs(roll - lastRoll) > ORIENTATION_DELTA_THRESHOLD))) { // Send the new orientation to the server if(tcp != null) { ClientCommand cmd = new ClientCommand(ClientCommand.GAMEPLAY_COMMAND); cmd.setOrientation(azimuth, pitch, roll); tcp.sendClientCommand(cmd); lastAzimuth = azimuth; lastRoll = roll; lastPitch = pitch; lastOrientationUpdate = System.currentTimeMillis(); } } } /** * Clamps an input value between a provided minimum and maximum, and returns * the value * @param input The input value * @param min The minimum output value * @param max The maximum output value * @return The input value, clamped to the provided minimum and maximum */ private float clamp(float value, float min, float max) { if(value > max) return max; if(value < min) return min; return value; } /** * Call this function to change the view into the OpenGL view. */ private void goToOpenGLView() { if (inOpenGL) return; else inOpenGL = true; // Remove the title bar from the window. //this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Make the windows into full screen mode. //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); // Create a OpenGL view. GLSurfaceView view = new GLSurfaceView(this); // Creating and attaching the renderer. renderer = new OpenGLRenderer(); view.setRenderer(renderer); setContentView(view); // Create and init the media streamer. // mClient = new MediaClient(this); // mClient.launchMediaStream(33331); // Create a new plane. plane = new SimplePlane(GameModel.DEFAULT_ARENA_SIZE, GameModel.DEFAULT_ARENA_SIZE); plane.rx = -45; plane.loadBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.logo)); // Set the default drawing location (initially center of the plane). currentDrawCoords = new Point3D(GameModel.DEFAULT_ARENA_SIZE / 2, GameModel.DEFAULT_ARENA_SIZE / 2, 0.0f); renderer.addMesh(plane); } /** * Call this method to change the view into the lobby/settings view. */ private void goToLobbyView() { if (!inOpenGL) return; else inOpenGL = false; } /* Methods called when in the OpenGL perspective. */ /** * Sets the plane to texturize the incoming video image. * * @param image */ public synchronized void setVideoImage(Bitmap image) { plane.loadBitmap(image); } /** * Renders the given 2D game entity with a supplied height as a 3D * rectangle. * * @param entity * The game entity to render. * @param height * The height of the entity in 3D. */ public void drawGameEntity(GameEntity entity, float height) { Vector vertices[] = entity.getVertices(); float x1, x2, y1, y2; // The min and max values for x and y coordinates. x1 = x2 = y1 = y2 = 0; // Initially 0. // Get the endpoints of the obstacle. for (int i = 0; i < vertices.length; i++) { // Initially set the min and max as the first vertex found. if (i == 0) { x1 = x2 = vertices[i].getX(); y1 = y2 = vertices[i].getY(); } // Continue cycling through until the min and max values are // found. else { x1 = Math.min(x1, vertices[i].getX()); x2 = Math.max(x2, vertices[i].getX()); y1 = Math.min(y1, vertices[i].getY()); y2 = Math.max(y2, vertices[i].getY()); } } // Now get the size of the entity and construct it. float length = Math.abs(x2 - x1); float width = Math.abs(y2 - y1); // Log.e("RoboWarsOpenGL", "Got obstacle parameters: l:" + length + // ", w:" + width + ", h:" + height); Cube cube = new Cube(length, width, height); currentDrawCoords.setX(entity.getPosture().getX()); currentDrawCoords.setY(entity.getPosture().getY()); currentDrawCoords.setZ(height / 2); cube.x = currentDrawCoords.getX(); cube.y = currentDrawCoords.getY(); cube.z = currentDrawCoords.getZ(); //cube.setColor(100f, 150f, 200f, 0f); // Log.e("RoboWarsOpenGL", "Successfully created the obstacle."); // Render the entity. renderer.addMesh(cube); // Log.e("RoboWarsOpenGL", "Obstacle rendered."); } /** * Renders a game entity onto the plane as a series of cubes. The height of * the entity will be half of the smallest dimension (length or width) for * now. * * @param entity * The entity we're drawing. */ public void drawGameEntityInParts(GameEntity entity) { Vector vertices[] = entity.getVertices(); float x1, x2, y1, y2; // The min and max values for x and y coordinates. x1 = x2 = y1 = y2 = 0; // Initially 0. // Get the endpoints of the obstacle. for (int i = 0; i < vertices.length; i++) { // Initially set the min and max as the first vertex found. if (i == 0) { x1 = x2 = vertices[i].getX(); y1 = y2 = vertices[i].getY(); } // Continue cycling through until the min and max values are // found. else { x1 = Math.min(x1, vertices[i].getX()); x2 = Math.max(x2, vertices[i].getX()); y1 = Math.min(y1, vertices[i].getY()); y2 = Math.max(y2, vertices[i].getY()); } } // Now we get the size of cubes to draw, which is either the length or // the width found previously, depending on which one is smaller. float length = Math.abs(x2 - x1); float width = Math.abs(y2 - y1); float cubeSize = Math.min(length, width); // Now find out how many cubes to draw... int numberOfCubes = (int) (Math.max(length, width) / cubeSize); // Now render the cubes on to the plane. for (int i = 0; i < numberOfCubes; i++) { // Make a new cube. Cube cube = new Cube(cubeSize); cube.setColor(100, 200, 150, 0); // since we're drawing from the center, the bottom half needs to be // placed above the plane. currentDrawCoords.setZ(cubeSize / 2); if (length > width) // Draw from left to right { // The cube is located at the minimum, plus half the length of a // cube (drawn from center), plus we need to offset by the // number of cubes already drawn. currentDrawCoords.setX(x1 + (cubeSize / 2) + (i * cubeSize)); currentDrawCoords.setY((y1 + y2) / 2); } else if (width > length) // Draw from bottom to top { // The cube is located at the minimum, plus half the width of a // cube (drawn from center), plus we need to offset by the // number of cubes already drawn. currentDrawCoords.setY(y1 + (cubeSize / 2) + (i * cubeSize)); currentDrawCoords.setX((x1 + x2) / 2); } else // The cube has a square base. { // Create one big cube and render it instead of a bunch of small // cubes. The height (z) is half of the length. cube = new Cube(length, width, length / 2); cube.setColor(100, 200, 150, 0); currentDrawCoords.setX((x1 + x2) / 2); // Center of length currentDrawCoords.setY((y1 + y2) / 2); // Center of width // This one may be tricky to imagine; the z coordinate // is 1/2 of the height of the cube (because we're drawing // from center, and we don't want half of the cube below the // plane). The height of the cube is already 1/2 of the length, // so we actually need 1/4 of the length to properly render // right on top of the plane. currentDrawCoords.setZ((x2 - x1) / 4); } // Now we have our location, so place the cube there. cube.x = currentDrawCoords.getX(); cube.y = currentDrawCoords.getY(); cube.z = currentDrawCoords.getZ(); // Now render it. renderer.addMesh(cube); } } }
package com.gallatinsystems.common.util; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.gallatinsystems.notification.NotificationRequest; import com.google.appengine.api.mail.MailService; import com.google.appengine.api.mail.MailService.Attachment; import com.google.appengine.api.mail.MailServiceFactory; public class MailUtil { private static final String RECIPIENT_LIST_STRING = "recipientListString"; private static final Logger log = Logger .getLogger(MailUtil.class.getName()); public static Boolean sendMail(String fromAddress, String fromName, TreeMap<String, String> recipientList, String subject, String messageBody) { try { Message msg = createMessage(); msg.setFrom(new InternetAddress(fromAddress, fromName)); for (Map.Entry<String, String> recipientMap : recipientList .entrySet()) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress( recipientMap.getKey(), recipientMap.getValue())); } msg.setSubject(subject); msg.setText(messageBody); Transport.send(msg); return true; } catch (Exception e) { log.log(Level.SEVERE, "Could not send mail subj:" + subject + " ", e.getMessage()); return false; } } public static TreeMap<String, String> loadRecipientList() { TreeMap<String, String> recipientList = new TreeMap<String, String>(); String recipientListString = com.gallatinsystems.common.util.PropertyUtil .getProperty(RECIPIENT_LIST_STRING); StringTokenizer st = new StringTokenizer(recipientListString, "|"); while (st.hasMoreTokens()) { String[] emailParts = st.nextToken().split(";"); recipientList.put(emailParts[0], emailParts[1]); } return recipientList; } private static Message createMessage() { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); return new MimeMessage(session); } /** * sends an html email to 1 or more recipients with an optional attachment * * @param fromAddr * @param toAddressList * @param toDelimiter * @param subject * @param body * @param attachmentBytes * @param attachmentName * @param mimeType * @return */ public static Boolean sendMail(String fromAddr, String toAddressList, String toDelimiter, String subject, String body, byte[] attachmentBytes, String attachmentName, String mimeType) { try { //Message msg = createMessage(); MailService service = MailServiceFactory.getMailService(); MailService.Attachment attachment = new MailService.Attachment(attachmentName,attachmentBytes); com.google.appengine.api.mail.MailService.Message msg = new MailService.Message(); msg.setSender(fromAddr); msg.setTextBody(body); //msg.setFrom(new InternetAddress(fromAddr)); // TODO: parse and handle multiple destinations if (toDelimiter != null) { StringTokenizer strTok = new StringTokenizer(toAddressList, NotificationRequest.DELIMITER); while (strTok.hasMoreTokens()) { // msg.addRecipient(Message.RecipientType.TO, // new InternetAddress(strTok.nextToken())); msg.setTo(strTok.nextToken()); } } else { // msg.addRecipient(Message.RecipientType.TO, new InternetAddress( // toAddressList)); msg.setTo(toAddressList); } // msg.setSubject(subject); Multipart mp = new MimeMultipart(); // MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(body, "text/html"); // mp.addBodyPart(htmlPart); // msg.setText(body); // if (attachmentName != null && attachmentBytes != null) { // MimeBodyPart attachment = new MimeBodyPart(); // attachment.setFileName(attachmentName); // attachment.setContent(attachmentBytes, mimeType); // mp.addBodyPart(attachment); // msg.setContent(mp); msg.setSubject(subject); msg.setTextBody(body); msg.setAttachments(attachment); service.send(msg); } catch (Exception e) { log.log(Level.SEVERE, "Could not send mail subj:" + subject + " ", e); return false; } return true; } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import javax.xml.bind.JAXBException; import org.springframework.util.StopWatch; import net.leanix.api.BusinessCapabilitiesApi; import net.leanix.api.BusinessObjectsApi; import net.leanix.api.ConsumersApi; import net.leanix.api.IfacesApi; import net.leanix.api.ProcessesApi; import net.leanix.api.ProjectsApi; import net.leanix.api.ProvidersApi; import net.leanix.api.ResourcesApi; import net.leanix.api.ServicesApi; import net.leanix.api.common.ApiClient; import net.leanix.api.models.BusinessCapability; import net.leanix.api.models.BusinessObject; import net.leanix.api.models.Consumer; import net.leanix.api.models.FactSheetHasIfaceProvider; import net.leanix.api.models.Iface; import net.leanix.api.models.IfaceHasBusinessObject; import net.leanix.api.models.Process; import net.leanix.api.models.Project; import net.leanix.api.models.Provider; import net.leanix.api.models.Resource; import net.leanix.api.models.Service; import net.leanix.api.models.ServiceHasBusinessCapability; import net.leanix.api.models.ServiceHasConsumer; import net.leanix.api.models.ServiceHasProcess; import net.leanix.api.models.ServiceHasProject; import net.leanix.api.models.ServiceHasResource; import net.leanix.benchmark.ApiClientFactory; import net.leanix.benchmark.ConfigurationProvider; import net.leanix.benchmark.Helper; import net.leanix.benchmark.performance.ReportBuilder; import net.leanix.benchmark.performance.TestSuite; /** * Creates a list of services (SERVICE_COUNT) with a list of linked resources (RESOURCE_PER_SERVICE_COUNT) * * @author andre */ public class BenchmarkC extends BaseBenchmarkTests { int numServices = ConfigurationProvider.getServicesCount(); int numResourcesPerService = ConfigurationProvider.getNumResourcesPerService(); final StopWatch stopWatch; public static void main(String[] args) throws Exception { BenchmarkC instance = new BenchmarkC(); instance.run(instance.stopWatch); } public BenchmarkC() { super(); stopWatch = new StopWatch( String.format("%s creates %s services withc %s resources/service", getClass().getSimpleName(), numServices, numResourcesPerService)); } @Override public void runBenchmarkOnWorkspace(StopWatch stopWatch) throws JAXBException { try { ApiClient apiClient = ApiClientFactory.getApiClient(wsName); apiClient.addDefaultHeader("X-Api-Update-Relations", "true"); // allow asynchronous job run apiClient.addDefaultHeader("X-Api-Synchronous", "false"); ServicesApi servicesApi = new ServicesApi(apiClient); ResourcesApi resourcesApi = new ResourcesApi(apiClient); ConsumersApi consumersApi = new ConsumersApi(apiClient); BusinessCapabilitiesApi businessCapabilitiesApi = new BusinessCapabilitiesApi(apiClient); ProcessesApi processApi = new ProcessesApi(apiClient); ProjectsApi projectApi = new ProjectsApi(apiClient); BusinessObjectsApi businessObjectApi = new BusinessObjectsApi(apiClient); IfacesApi ifacesApi = new IfacesApi(apiClient); // Add consumers (User Group) Helper h = new Helper(configurationProvider.getRandomSeed()); List<Consumer> consumers = new ArrayList<>(); stopWatch.start("adding Consumers " + Helper.getProperty("consumers.count", "10")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("consumers.count", "10")); i++) { Consumer c = new Consumer(); c.setName(h.getUniqueString()); c.setDescription(h.getUniqueText(10)); c = consumersApi.createConsumer(c); System.out.println(String.format("Create USER GROUP %d, name = %s, id = %s", i, c.getName(), c.getID())); consumers.add(c); } stopWatch.stop(); // Add provider List<Provider> providers = new ArrayList<>(); stopWatch.start("adding Provider " + Helper.getProperty("provider.count", "8")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("provider.count", "8")); i++) { Provider model = new Provider(); model.setName("Provider " + h.getUniqueString()); // model.setDescription(h.getUniqueText(40)); model = new ProvidersApi(apiClient).createProvider(model); System.out.println(String.format("Create PROVIDER %d, name = %s, id = %s", i, model.getName(), model.getID())); providers.add(model); } stopWatch.stop(); // Add business capability List<BusinessCapability> bcs = new ArrayList<>(); stopWatch.start("adding BusinessCapabilities " + Helper.getProperty("businessCapabilities.count", "8")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("businessCapabilities.count", "8")); i++) { BusinessCapability bc = new BusinessCapability(); bc.setName(h.getUniqueString()); bc.setDescription(h.getUniqueText(10)); bc = businessCapabilitiesApi.createBusinessCapability(bc); System.out.println(String.format("Create BUS. CAPABILITY %d, name = %s, id = %s", i, bc.getName(), bc.getID())); bcs.add(bc); } stopWatch.stop(); // Add Processes List<Process> processes = new ArrayList<>(); stopWatch.start("adding Processes " + Helper.getProperty("processes.count", "8")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("processes.count", "8")); i++) { Process process = new Process(); process.setName(h.getUniqueString()); process.setDescription(h.getUniqueText(10)); process = processApi.createProcess(process); System.out.println(String.format("Create PROCESS %d, name = %s, id = %s", i, process.getName(), process.getID())); processes.add(process); } stopWatch.stop(); // Add Projects List<Project> projects = new ArrayList<>(); stopWatch.start("adding Projects " + Helper.getProperty("projects.count", "8")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("projects.count", "8")); i++) { Project project = new Project(); project.setName(h.getUniqueString()); project.setDescription(h.getUniqueText(10)); project = projectApi.createProject(project); System.out.println(String.format("Create PROJECT %d, name = %s, id = %s", i, project.getName(), project.getID())); projects.add(project); } stopWatch.stop(); // Add Business Objects (Data Objects) List<BusinessObject> businessObjects = new ArrayList<>(); stopWatch.start("adding Data Objects " + Helper.getProperty("businessobjects.count", "6")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("businessobjects.count", "6")); i++) { BusinessObject businessObject = new BusinessObject(); businessObject.setName("Data Object " + h.getUniqueString()); businessObject.setDescription(h.getUniqueText(40)); businessObject = businessObjectApi.createBusinessObject(businessObject); System.out.println(String.format("Create DATA OBJECT %d, name = %s, id = %s", i, businessObject.getName(), businessObject.getID())); businessObjects.add(businessObject); } stopWatch.stop(); // Add Interfaces assigned with business objects List<Iface> interfaces = new ArrayList<>(); stopWatch.start("adding Interfaces " + Helper.getProperty("iface.count", "8")); for (int i = 0; i < Integer.parseInt(Helper.getProperty("iface.count", "8")); i++) { Iface iface = new Iface(); iface.setName("IFace " + h.getUniqueString()); iface.setDescription(h.getUniqueText(40)); IfaceHasBusinessObject ifaceHasBusinessObject = new IfaceHasBusinessObject(); ifaceHasBusinessObject.setBusinessObjectID( businessObjects.get(ThreadLocalRandom.current().nextInt(0, businessObjects.size() - 1)).getID()); iface.setIfaceHasBusinessObjects(Arrays.asList(ifaceHasBusinessObject)); iface.setInterfaceDirectionID("1"); iface = ifacesApi.createIface(iface); System.out.println(String.format("Create INTERFACE %d, name = %s, id = %s", i, iface.getName(), iface.getID())); interfaces.add(iface); } stopWatch.stop(); // Create services for (int i = 0; i < numServices; i++) { stopWatch.start("Service " + i); Service s = new Service(); s.setName(h.getUniqueString()); s.setDescription(h.getUniqueText(10)); s.setFactSheetHasLifecycles(h.getRandomLifecycle("2010-01-10", "2020-01-01")); if (consumers.size() > 0) { Consumer cur = consumers.get(ThreadLocalRandom.current().nextInt(0, consumers.size() - 1)); ServiceHasConsumer shc = new ServiceHasConsumer(); shc.setUsageTypeID("1"); shc.setConsumerID(cur.getID()); List<ServiceHasConsumer> shcList = new ArrayList<>(); shcList.add(shc); s.setServiceHasConsumers(shcList); } if (bcs.size() > 0) { BusinessCapability cur = bcs.get(ThreadLocalRandom.current().nextInt(0, bcs.size() - 1)); ServiceHasBusinessCapability shb = new ServiceHasBusinessCapability(); shb.setSupportTypeID("1"); shb.setBusinessCapabilityID(cur.getID()); List<ServiceHasBusinessCapability> shbList = new ArrayList<>(); shbList.add(shb); s.setServiceHasBusinessCapabilities(shbList); } if (processes.size() > 0) { Process process = processes.get(ThreadLocalRandom.current().nextInt(0, processes.size() - 1)); ServiceHasProcess shp = new ServiceHasProcess(); shp.setProcessID(process.getID()); s.setServiceHasProcesses(Arrays.asList(shp)); } if (projects.size() > 0) { Project project = projects.get(ThreadLocalRandom.current().nextInt(0, projects.size() - 1)); ServiceHasProject shp = new ServiceHasProject(); shp.setProjectID(project.getID()); s.setServiceHasProjects(Arrays.asList(shp)); } if (interfaces.size() > 0) { Iface iface = interfaces.get(ThreadLocalRandom.current().nextInt(0, interfaces.size() - 1)); FactSheetHasIfaceProvider factSheetHasIfaceProvider = new FactSheetHasIfaceProvider(); factSheetHasIfaceProvider.setIfaceID(iface.getID()); s.setFactSheetHasIfaceProviders(Arrays.asList(factSheetHasIfaceProvider)); } s = servicesApi.createService(s); System.out.println("Create SERVICE " + i + ", name = " + s.getName() + ", id = " + s.getID()); // Create resources (IT Components) for (int x = 0; x < numResourcesPerService; x++) { Resource r = new Resource(); r.setName(h.getUniqueString()); r.setDescription(h.getUniqueText(10)); r.setFactSheetHasLifecycles(h.getRandomLifecycle("2012-01-10", "2020-01-01")); ServiceHasResource shr = new ServiceHasResource(); shr.setServiceID(s.getID()); shr.setComment("Created by SDK"); List<ServiceHasResource> shrList = new ArrayList<>(); shrList.add(shr); r.setServiceHasResources(shrList); r = resourcesApi.createResource(r); System.out.println("Create RESOURCE " + i + ", name = " + r.getName() + ", id = " + r.getID()); } stopWatch.stop(); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ReportBuilder reportBuilder = new ReportBuilder().forTestClass(getClass()); TestSuite testSuite = reportBuilder.addErrorTestResult("runBenchmarkOnWorkspace", 0, ex).build(); writeBenchmarkJUnitResultFile(getClass(), testSuite); return; } // do some output to stdout System.out.println(stopWatch.prettyPrint()); double totalTimeSeconds = stopWatch.getTotalTimeSeconds(); System.out.println(String.format("Complete Time of Run (+WS Setup) : %.2f s (%d:%02d)", totalTimeSeconds, (int) totalTimeSeconds / 60, (int) totalTimeSeconds % 60)); double timeTestCase = getSumOfLastTasksInSeconds(stopWatch, stopWatch.getTaskCount() - 1); System.out.println(String.format("Complete Job processing time : %.2f s (%d:%02d)", timeTestCase, (int) timeTestCase / 60, (int) timeTestCase % 60)); System.out.println(String.format("Average Time of test for / %d FS : %.3f s", numServices, timeTestCase / numServices)); // write junit result file used in jenkin's performance plugin // TestSuite testSuite = createTestSuiteObjectBasedOnTaskInfo(getClass(), // getLastTasks(stopWatch, stopWatch.getTaskCount() - 1)); ReportBuilder reportBuilder = new ReportBuilder().forTestClass(getClass()); TestSuite testSuite = reportBuilder .addSuccessfulTestResult(String.format("Average time for %d FS", numServices), timeTestCase / numServices) .build(); writeBenchmarkJUnitResultFile(getClass(), testSuite); } }
package com.lyft.scoop; import android.os.Parcelable; import android.util.SparseArray; import android.view.View; public class Screen { public static final String SERVICE_NAME = "screen"; private transient SparseArray<Parcelable> viewState; public Screen() { viewState = new SparseArray<Parcelable>(); } public void saveViewState(View view) { SparseArray<Parcelable> viewState = new SparseArray<Parcelable>(); view.saveHierarchyState(viewState); this.viewState = viewState; } public void restoreViewState(View view) { view.restoreHierarchyState(viewState); } public Class<? extends ViewController> getController() { Controller controller = getClass().getAnnotation(Controller.class); if (controller != null) { return controller.value(); } return null; } public Integer getLayout() { Layout layout = getClass().getAnnotation(Layout.class); if (layout != null) { return layout.value(); } return null; } public static <T extends Screen> T fromScoop(Scoop scoop) { if (scoop == null) { return null; } return scoop.findService("screen"); } public static <T extends Screen> T fromView(View view) { return Screen.fromScoop(Scoop.fromView(view)); } public static <T extends Screen> T fromController(ViewController controller) { return Screen.fromScoop(controller.getScoop()); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Screen)) { return false; } Screen screen = (Screen) o; return equals(screen.getClass(), getClass()); } public boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } }
package com.Ceridian.tests; import com.Ceridian.Pages.BookAHoliday; import com.Ceridian.Pages.HomePage; import com.Ceridian.Pages.Navigation; import com.Ceridian.com.ExcelUtils; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.core.ui.tests.BaseTest; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class HB01 extends BaseTest { @Test(description = "Submit Holiday booking") @Parameters({"browser"}) public void CD01() { HomePage homePage = new HomePage(); ExcelUtils excelUtils = new ExcelUtils(); String[] excelArray = excelUtils.readLoginInformation(); homePage // .logIn("fulladmin", "Brexit?1$") .openPage(excelArray[2]) .logIn(excelArray[0], excelArray[1]); Navigation navigation = PageFactory.newInstance(Navigation.class); navigation. clickHolidayLink(); BookAHoliday bookAHoliday = PageFactory.newInstance(BookAHoliday.class); bookAHoliday .completeHolidayFormAndSubmit("12/05/2016", "15/05/2016"); } @Test(dependsOnMethods = "CD01", alwaysRun = true, description = "Accept Holiday Booking") public void CD02() { HomePage homePage = new HomePage(); ExcelUtils excelUtils = new ExcelUtils(); String[] excelArray = excelUtils.readLoginInformation(); homePage .openPage(excelArray[2]) .logIn(excelArray[0], excelArray[1]) .clickMessages() .acceptFirstRequest(); } }
package com.example; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedCondition; public class Actionwords { WebDriver driver=null; public Actionwords() { System.setProperty("D:\\geckodriver-v0.11.1-win64\\geckodriver.exe"); driver = new FirefoxDriver(); } public void iOpenP1(String p1) { driver.get(p1); } public void iSearchForP1(String p1) { WebElement element = driver.findElement(By.name("q")); element.clear(); element.sendKeys(p1); element.submit(); } public void aLinkToP1IsShownInTheResults(String p1) { final String matcher = p1; (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.findElements(By.linkText(matcher)).size() != 0; } }); } }
package com.fishercoder; import com.fishercoder.solutions._30; import com.fishercoder.solutions._735; import java.util.Arrays; import java.util.List; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class _30Test { private static _30.Solution1 solution1; private static String[] words; private static List<Integer> expected; @BeforeClass public static void setup() { solution1 = new _30.Solution1(); } @Test @Ignore //TODO: needs to fix the solution public void test1() { words = new String[] {"foo", "bar"}; expected = Arrays.asList(0, 9); assertEquals(expected, solution1.findSubstring("barfoothefoobarman", words)); } }
package slogo_front; /** * currently includes methods to move turtle * to be added: * - canvas implementation (paint methods) * - turtle image updates * @author emresonmez * */ public class Display { private int xOrigin; private int yOrigin; private int xBoundHigh; private int xBoundLow; private int yBoundHigh; private int yBoundLow; /** * basic constructor * @param xCenter * @param yCenter * @param xHigh * @param xLow * @param yHigh * @param yLow */ public Display(int xCenter, int yCenter, int xHigh, int xLow, int yHigh, int yLow){ xOrigin = xCenter; yOrigin = yCenter; xBoundHigh = xHigh; xBoundLow = xLow; yBoundHigh = yHigh; yBoundLow = yLow; } /* * methods for turtle movement * input: turtle, parameters */ public void moveForward(Turtle t, int pixels, boolean leaveTrail){ moveStraight(t,pixels,leaveTrail,true); } public void moveBackward(Turtle t, int pixels, boolean leaveTrail){ moveStraight(t,pixels,leaveTrail,false); } /** * given turtle and distance, moves turtle accordingly * @param t * @param pixels * @param leaveTrail */ private void moveStraight(Turtle t,int pixels,boolean leaveTrail, boolean forward){ boolean atTop = false; boolean atBottom = false; boolean atLeft = false; boolean atRight = false; int curX = t.getXloc(); int curY = t.getYloc(); double heading = t.getHeading(); double xDistance = getXDistance(heading,pixels); double yDistance = getYDistance(heading,pixels); double xTemp = curX; double yTemp = curY; if(forward){ xTemp += xDistance; yTemp += yDistance; }else{ xTemp -= xDistance; yTemp -= yDistance; } int finalX; int finalY; // check if line hits edge in x direction if(checkEdgeHorizontal(xTemp)){ finalX = (int) xTemp; }else{ if(xTemp > xBoundHigh){ atRight = true; finalX = xBoundHigh; xDistance = xDistance - xBoundHigh; }else{ atLeft = true; finalX = xBoundLow; xDistance = xDistance - xBoundLow; } } // check if line hits edge in y direction if(checkEdgeVertical(yTemp)){ // y loc is in bounds finalY = (int) yTemp; }else{ if(yTemp > yBoundHigh){ atTop = true; finalY = yBoundHigh; yDistance = yDistance - yBoundHigh; }else{ atBottom = true; finalY = yBoundLow; yDistance = yDistance - yBoundLow; } } // update turtle location properties t.setXLoc(finalX); t.setYLoc(finalY); // paint line (first line if hits edge) if(leaveTrail){ paintLine(curX, curY, finalX, finalY); } // set new locations if at edge if(atRight){ t.setXLoc(xBoundLow); }else if(atLeft){ t.setXLoc(xBoundHigh); } if(atTop){ t.setYLoc(yBoundLow); }else if(atBottom){ t.setYLoc(yBoundHigh); } // if turtle is at edge, continue moving turtle if(atRight|atLeft|atTop|atBottom){ int newDistance = (int) Math.sqrt(xDistance*xDistance + // update distance yDistance*yDistance); moveStraight(t,newDistance,leaveTrail,forward); // call recursively on remaining distance } } private boolean checkEdgeHorizontal(double x){ return ((x <= xBoundHigh) && (x >= xBoundLow)); } private boolean checkEdgeVertical(double y){ return ((y <= yBoundHigh) && (y >= yBoundLow)); } /* * painting methods */ /** * draws line on canvas from point A to point B (points guaranteed to be in bounds) * @param x1 * @param x2 * @param y1 * @param y2 */ private void paintLine(int x1, int x2, int y1, int y2){ // TODO implement this } /* * helper methods for geometry */ private double getDistance(int x1,int y1, int x2, int y2){ int xDiff = x2-x1; int yDiff = y2-y1; return Math.sqrt(xDiff*xDiff + yDiff*yDiff); } private double getXDistance(double heading, int pixels){ double headingInRadians = degreesToRadians(heading); return pixels*Math.cos(headingInRadians); } private double getYDistance(double heading, int pixels){ double headingInRadians = degreesToRadians(heading); return pixels*Math.sin(headingInRadians); } private double degreesToRadians (double degrees){ return Math.toRadians(degrees); } }
package guitests; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.address.model.TaskManager; import seedu.address.model.task.Task; import seedu.address.model.util.SampleDataUtil; import seedu.address.testutil.TestUtil; public class SampleDataTest extends TaskManagerGuiTest { @Override protected TaskManager getInitialData() { // return null to force test app to load data from file only return null; } @Override protected String getDataFileLocation() { // return a non-existent file location to force test app to load sample data return TestUtil.getFilePathInSandboxFolder("SomeFileThatDoesNotExist1234567890.xml"); } @Test public void addressBook_dataFileDoesNotExist_loadSampleData() throws Exception { Task[] expectedList = SampleDataUtil.getSampleTasks(); assertTrue(taskListPanel.isListMatching(expectedList)); } }
package engine.element; import java.util.ArrayList; import java.util.List; import java.util.Map; import annotations.parameter; import engine.Endable; import engine.Reflectable; import engine.UpdateAndReturnable; import engine.factories.GameElementFactory; /** * Contains all information about a single level within a game. Has methods for checking win/loss * conditions, updating the scene, and moving between rounds and waves. The level also contains a * pointer to another level which will be called if the win conditions are met - if the loss * conditions are met, a generic "Game Over" is loaded before the same level is reloaded. * * @author Bojia Chen * @author Qian Wang */ public class Level implements UpdateAndReturnable, Endable, Reflectable, Comparable<Level> { private static final String PARAMETER_ROUND = "Round"; @parameter(settable = true, playerDisplay = true, defaultValue = "20") private Integer myLives; @parameter(settable = true, playerDisplay = true, defaultValue = "null") private List<String> myRounds; @parameter(settable = true, playerDisplay = true, defaultValue = "null") private List<String> myConditions; /** * Identifies the level number. Used to determine order. */ @parameter(settable = true, playerDisplay = true, defaultValue = "0") private Integer myNumber; private int myActiveRoundIndex = 0; private Round myActiveRound; private GameElementFactory myGameElementFactory; // TODO: Win/Lose Conditions public Level () { } public void addInstanceVariables (Map<String, Object> parameters) { myLives = (Integer) parameters.get("myLives"); myRounds = (List<String>) parameters.get("myRounds"); myConditions = (List<String>) parameters.get("myConditions"); myNumber = (Integer) parameters.get("myNumber"); } public void setGameElementFactory (GameElementFactory factory) { myGameElementFactory = factory; } /** * Method called by Player when ready to start next Round * * @return True if able to start next round */ public boolean startNextRound () { if (myActiveRound.hasEnded()) { myActiveRoundIndex++; } if (hasEnded()) { return false; } else { setActiveRound(); return true; } } private void setActiveRound () { String roundGUID = myRounds.get(myActiveRoundIndex); myActiveRound = (Round) myGameElementFactory.getGameElement(PARAMETER_ROUND, roundGUID); } @Override public boolean hasEnded () { return myActiveRoundIndex == myRounds.size(); } @Override public Map<Object, List<String>> update (int counter) { if (myActiveRound == null) { return null; } return myActiveRound.update(counter); } @Override public int compareTo (Level other) { int thisLevel = this.myNumber; int otherLevel = other.myNumber; return thisLevel - otherLevel; } }
package org.scijava.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map.Entry; /** * A helper class to help with optimizing the performance of a list of * operations. * <p> * For example, when trying to figure out which * {@link org.scijava.service.Service} would be the best candidate to speed up * {@link org.scijava.Context} initialization, this helper comes in real handy: * it accumulates a list of operations with their duration and prints out a * sorted list when asked to. * </p> * <p> * Use this class as following: * </p> * <code> * private static Timing timing = new Timing();<br /> * ...<br /> * private void oneOperation() {<br /> * &nbsp;final long t1 = System.nanoTime();<br /> * &nbsp;...<br /> * &nbsp;timing.add(System.nanoTime() - t1, "Operation #1");<br /> * }<br /> * ...<br /> * private void atEnd() {<br /> * &nbsp;...<br /> * &nbsp;timing.report("Operations");<br /> * } * </code> * * @author Johannes Schindelin */ public class Timing { private long total = 0, start = System.nanoTime(), tick = start; private List<Entry<Long, String>> list = new ArrayList<Entry<Long, String>>(); public void reset() { tick = System.nanoTime(); } public void addTiming(final Object message) { addTiming(System.nanoTime() - tick, message == null ? getCaller() : message); tick = System.nanoTime(); } public void addTiming(final long duration, final Object message) { final long now = System.nanoTime(); total += duration; list.add(new Entry<Long, String>() { @Override public Long getKey() { return Long.valueOf(duration); } @Override public String getValue() { return message.toString() + ": " + ((now - start - duration) / 1e6) + " - " + ((now - start) / 1e6); } @Override public String setValue(String value) { throw new UnsupportedOperationException(); } }); } public void report(final String description) { System.err.println(description == null ? getCaller() : description); Collections.sort(list, new Comparator<Entry<Long, String>>() { @Override public int compare(Entry<Long, String> o1, Entry<Long, String> o2) { return Double.compare(o1.getKey(), o2.getKey()); } }); for (final Entry<?,?> e: list) { System.err.printf("% 5.3f ms %s\n", ((Long)e.getKey()) / 1e6, e.getValue()); } System.err.println("Total time: " + total + " = " + (total / 1e9) + " sec"); } private static String getCaller() { final StackTraceElement[] trace = Thread.currentThread().getStackTrace(); int i = 1; while (i + 1 < trace.length && Timing.class.getName().equals(trace[i].getClassName())) { i++; } return i >= trace.length ? "?" : trace[i].getClassName() + "." + trace[i].getMethodName() + "(" + trace[i].getFileName() + ":" + trace[i].getLineNumber() + ")"; } }
package picocli; import org.junit.Test; import picocli.CommandLine.Help.ColorScheme; import static org.junit.Assert.*; public class ColorSchemeTest { @Test public void testEquals() { ColorScheme defaultScheme = CommandLine.Help.defaultColorScheme(CommandLine.Help.Ansi.AUTO); ColorScheme expect = new ColorScheme.Builder() .commands(CommandLine.Help.Ansi.Style.bold) .options(CommandLine.Help.Ansi.Style.fg_yellow) .parameters(CommandLine.Help.Ansi.Style.fg_yellow) .optionParams(CommandLine.Help.Ansi.Style.italic).build(); assertEquals(expect, defaultScheme); } @Test public void testEqualsOther() { ColorScheme defaultScheme = CommandLine.Help.defaultColorScheme(CommandLine.Help.Ansi.AUTO); assertNotEquals("blah", defaultScheme); } @Test public void testHashCode() { ColorScheme defaultScheme = CommandLine.Help.defaultColorScheme(CommandLine.Help.Ansi.AUTO); ColorScheme expect = new ColorScheme.Builder() .commands(CommandLine.Help.Ansi.Style.bold) .options(CommandLine.Help.Ansi.Style.fg_yellow) .parameters(CommandLine.Help.Ansi.Style.fg_yellow) .optionParams(CommandLine.Help.Ansi.Style.italic).build(); assertEquals(expect.hashCode(), defaultScheme.hashCode()); } @Test public void testToString() { ColorScheme defaultScheme = CommandLine.Help.defaultColorScheme(CommandLine.Help.Ansi.AUTO); assertEquals("ColorScheme[ansi=AUTO, commands=[bold], optionStyles=[fg_yellow], parameterStyles=[fg_yellow], optionParamStyles=[italic]]", defaultScheme.toString()); } }
package som.compiler; import static som.compiler.Symbol.And; import static som.compiler.Symbol.At; import static som.compiler.Symbol.BeginComment; import static som.compiler.Symbol.Colon; import static som.compiler.Symbol.Comma; import static som.compiler.Symbol.Div; import static som.compiler.Symbol.EndBlock; import static som.compiler.Symbol.EndComment; import static som.compiler.Symbol.EndTerm; import static som.compiler.Symbol.Equal; import static som.compiler.Symbol.EventualSend; import static som.compiler.Symbol.Exit; import static som.compiler.Symbol.Identifier; import static som.compiler.Symbol.Keyword; import static som.compiler.Symbol.KeywordSequence; import static som.compiler.Symbol.LCurly; import static som.compiler.Symbol.Less; import static som.compiler.Symbol.Minus; import static som.compiler.Symbol.MixinOperator; import static som.compiler.Symbol.Mod; import static som.compiler.Symbol.More; import static som.compiler.Symbol.NONE; import static som.compiler.Symbol.NewBlock; import static som.compiler.Symbol.NewTerm; import static som.compiler.Symbol.Not; import static som.compiler.Symbol.Numeral; import static som.compiler.Symbol.OperatorSequence; import static som.compiler.Symbol.Or; import static som.compiler.Symbol.Per; import static som.compiler.Symbol.Period; import static som.compiler.Symbol.Plus; import static som.compiler.Symbol.Pound; import static som.compiler.Symbol.RCurly; import static som.compiler.Symbol.STString; import static som.compiler.Symbol.SlotMutableAssign; import static som.compiler.Symbol.Star; import static som.interpreter.SNodeFactory.createImplicitReceiverSend; import static som.interpreter.SNodeFactory.createMessageSend; import static som.interpreter.SNodeFactory.createSequence; import static som.vm.Symbols.symbolFor; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; import som.compiler.Lexer.Peek; import som.compiler.MethodBuilder.MethodDefinitionError; import som.compiler.MixinBuilder.MixinDefinitionError; import som.compiler.Variable.Argument; import som.compiler.Variable.Local; import som.interpreter.SomLanguage; import som.interpreter.nodes.ExpressionNode; import som.interpreter.nodes.MessageSendNode; import som.interpreter.nodes.MessageSendNode.AbstractUninitializedMessageSendNode; import som.interpreter.nodes.literals.ArrayLiteralNode; import som.interpreter.nodes.literals.BigIntegerLiteralNode; import som.interpreter.nodes.literals.BlockNode; import som.interpreter.nodes.literals.BlockNode.BlockNodeWithContext; import som.interpreter.nodes.literals.BooleanLiteralNode.FalseLiteralNode; import som.interpreter.nodes.literals.BooleanLiteralNode.TrueLiteralNode; import som.interpreter.nodes.literals.DoubleLiteralNode; import som.interpreter.nodes.literals.IntegerLiteralNode; import som.interpreter.nodes.literals.LiteralNode; import som.interpreter.nodes.literals.NilLiteralNode; import som.interpreter.nodes.literals.StringLiteralNode; import som.interpreter.nodes.literals.SymbolLiteralNode; import som.interpreter.nodes.specialized.BooleanInlinedLiteralNode.AndInlinedLiteralNode; import som.interpreter.nodes.specialized.BooleanInlinedLiteralNode.OrInlinedLiteralNode; import som.interpreter.nodes.specialized.IfInlinedLiteralNode; import som.interpreter.nodes.specialized.IfTrueIfFalseInlinedLiteralsNode; import som.interpreter.nodes.specialized.IntDownToDoInlinedLiteralsNodeGen; import som.interpreter.nodes.specialized.IntTimesRepeatLiteralNodeGen; import som.interpreter.nodes.specialized.IntToDoInlinedLiteralsNodeGen; import som.interpreter.nodes.specialized.whileloops.WhileInlinedLiteralsNode; import som.vm.Symbols; import som.vm.VmSettings; import som.vmobjects.SInvokable; import som.vmobjects.SSymbol; import tools.SourceCoordinate; import tools.debugger.Tags; import tools.debugger.Tags.ArgumentTag; import tools.debugger.Tags.CommentTag; import tools.debugger.Tags.DelimiterClosingTag; import tools.debugger.Tags.DelimiterOpeningTag; import tools.debugger.Tags.IdentifierTag; import tools.debugger.Tags.KeywordTag; import tools.debugger.Tags.LiteralTag; import tools.debugger.Tags.LocalVariableTag; import tools.debugger.Tags.StatementSeparatorTag; import tools.language.StructuralProbe; public class Parser { private final Lexer lexer; private final Source source; private final SomLanguage language; private Symbol sym; private String text; private Symbol nextSym; private String nextText; private SourceSection lastMethodsSourceSection; private final Set<SourceSection> syntaxAnnotations; private final StructuralProbe structuralProbe; private static final Symbol[] singleOpSyms = new Symbol[] {Not, And, Or, Star, Div, Mod, Plus, Equal, More, Less, Comma, At, Per, NONE}; private static final Symbol[] binaryOpSyms = new Symbol[] {Or, Comma, Minus, Equal, Not, And, Or, Star, Div, Mod, Plus, Equal, More, Less, Comma, At, Per, NONE}; private static final Symbol[] keywordSelectorSyms = new Symbol[] {Keyword, KeywordSequence}; private static final Symbol[] literalSyms = new Symbol[] {Pound, STString, Numeral}; private static boolean arrayContains(final Symbol[] arr, final Symbol sym) { for (Symbol s : arr) { if (s == sym) { return true; } } return false; } @Override public String toString() { return "Parser(" + source.getName() + ", " + this.getCoordinate().toString() + ")"; } public static class ParseError extends ProgramDefinitionError { private static final long serialVersionUID = 425390202979033628L; private final SourceCoordinate sourceCoordinate; private final String text; private final String rawBuffer; private final String fileName; private final Symbol expected; private final Symbol found; ParseError(final String message, final Symbol expected, final Parser parser) { super(message); if (parser.lexer == null) { this.sourceCoordinate = new SourceCoordinate(0, 0, 0, 0); this.rawBuffer = ""; } else { this.sourceCoordinate = parser.getCoordinate(); this.rawBuffer = new String(parser.lexer.getCurrentLine()); } this.text = parser.text; this.fileName = parser.source.getName(); this.expected = expected; this.found = parser.sym; } protected String expectedSymbolAsString() { return expected.toString(); } public SourceCoordinate getSourceCoordinate() { return sourceCoordinate; } @Override public String getMessage() { String msg = super.getMessage(); String foundStr; if (Parser.printableSymbol(found)) { foundStr = found + " (" + text + ")"; } else { foundStr = found.toString(); } String expectedStr = expectedSymbolAsString(); msg = msg.replace("%(expected)s", expectedStr); msg = msg.replace("%(found)s", foundStr); return msg; } @Override public String toString() { String msg = "%(file)s:%(line)d:%(column)d: error: " + super.getMessage(); String foundStr; if (Parser.printableSymbol(found)) { foundStr = found + " (" + text + ")"; } else { foundStr = found.toString(); } msg += ": " + rawBuffer; String expectedStr = expectedSymbolAsString(); msg = msg.replace("%(file)s", fileName); msg = msg.replace("%(line)d", java.lang.Integer.toString(sourceCoordinate.startLine)); msg = msg.replace("%(column)d", java.lang.Integer.toString(sourceCoordinate.startColumn)); msg = msg.replace("%(expected)s", expectedStr); msg = msg.replace("%(found)s", foundStr); return msg; } } public static class ParseErrorWithSymbols extends ParseError { private static final long serialVersionUID = 561313162441723955L; private final Symbol[] expectedSymbols; ParseErrorWithSymbols(final String message, final Symbol[] expected, final Parser parser) { super(message, null, parser); this.expectedSymbols = expected; } @Override protected String expectedSymbolAsString() { StringBuilder sb = new StringBuilder(); String deliminator = ""; for (Symbol s : expectedSymbols) { sb.append(deliminator); sb.append(s); deliminator = ", "; } return sb.toString(); } } public Parser(final String content, final long fileSize, final Source source, final StructuralProbe structuralProbe, final SomLanguage language) throws ParseError { this.source = source; this.language = language; sym = NONE; nextSym = NONE; if (fileSize == 0) { throw new ParseError("Provided file is empty.", NONE, this); } lexer = new Lexer(content); getSymbolFromLexer(); this.syntaxAnnotations = new HashSet<>(); this.structuralProbe = structuralProbe; } Set<SourceSection> getSyntaxAnnotations() { return syntaxAnnotations; } public SourceCoordinate getCoordinate() { return lexer.getStartCoordinate(); } public MixinBuilder moduleDeclaration() throws ProgramDefinitionError { comments(); return classDeclaration(null, AccessModifier.PUBLIC); } protected String className() throws ParseError { String mixinName = text; expect(Identifier, IdentifierTag.class); return mixinName; } private MixinBuilder classDeclaration(final MixinBuilder outerBuilder, final AccessModifier accessModifier) throws ProgramDefinitionError { expectIdentifier("class", "Found unexpected token %(found)s. " + "Tried parsing a class declaration and expected 'class' instead.", KeywordTag.class); SourceCoordinate coord = getCoordinate(); String mixinName = className(); SourceSection nameSS = getSource(coord); MixinBuilder mxnBuilder = new MixinBuilder(outerBuilder, accessModifier, symbolFor(mixinName), nameSS, structuralProbe, language); MethodBuilder primaryFactory = mxnBuilder.getPrimaryFactoryMethodBuilder(); coord = getCoordinate(); // Newspeak-spec: this is not strictly sufficient for Newspeak // it could also parse a binary selector here, I think // but, doesn't seem so useful, so, let's keep it simple if (sym == Identifier || sym == Keyword) { messagePattern(primaryFactory); } else { // in the standard case, the primary factory method is #new primaryFactory.addArgument("self", getEmptySource()); primaryFactory.setSignature(Symbols.NEW); } mxnBuilder.setupInitializerBasedOnPrimaryFactory(getSource(coord)); expect(Equal, "Unexpected symbol %(found)s." + " Tried to parse the class declaration of " + mixinName + " and expect '=' before the (optional) inheritance declaration.", KeywordTag.class); inheritanceListAndOrBody(mxnBuilder); return mxnBuilder; } private void inheritanceListAndOrBody(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { if (sym == NewTerm) { defaultSuperclassAndBody(mxnBuilder); } else { explicitInheritanceListAndOrBody(mxnBuilder); } } private void defaultSuperclassAndBody(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { SourceSection source = getEmptySource(); MethodBuilder def = mxnBuilder.getClassInstantiationMethodBuilder(); ExpressionNode selfRead = def.getSelfRead(source); ExpressionNode superClass = createMessageSend(Symbols.OBJECT, new ExpressionNode[] {selfRead}, false, source, null, language); mxnBuilder.setSuperClassResolution(superClass); mxnBuilder.setSuperclassFactorySend( mxnBuilder.createStandardSuperFactorySend(source), true); classBody(mxnBuilder); } private void explicitInheritanceListAndOrBody(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { SourceCoordinate superAndMixinCoord = getCoordinate(); inheritanceClause(mxnBuilder); final boolean hasMixins = sym == MixinOperator; int i = 0; while (sym == MixinOperator) { i++; mixinApplication(mxnBuilder, i); } if (hasMixins) { mxnBuilder.setMixinResolverSource(getSource(superAndMixinCoord)); SourceCoordinate initCoord = getCoordinate(); if (accept(Period, StatementSeparatorTag.class)) { // TODO: what else do we need to do here? mxnBuilder.setInitializerSource(getSource(initCoord)); mxnBuilder.finalizeInitializer(); return; } } classBody(mxnBuilder); } private void mixinApplication(final MixinBuilder mxnBuilder, final int mixinId) throws ProgramDefinitionError { expect(MixinOperator, KeywordTag.class); SourceCoordinate coord = getCoordinate(); ExpressionNode mixinResolution = inheritancePrefixAndSuperclass(mxnBuilder); mxnBuilder.addMixinResolver(mixinResolution); AbstractUninitializedMessageSendNode mixinFactorySend; SSymbol uniqueInitName; if (sym != NewTerm && sym != MixinOperator && sym != Period) { mixinFactorySend = (AbstractUninitializedMessageSendNode) messages( mxnBuilder.getInitializerMethodBuilder(), mxnBuilder.getInitializerMethodBuilder().getSelfRead(getSource(coord))); uniqueInitName = MixinBuilder.getInitializerName( mixinFactorySend.getSelector(), mixinId); mixinFactorySend = (AbstractUninitializedMessageSendNode) MessageSendNode.adaptSymbol( uniqueInitName, mixinFactorySend, language.getVM()); } else { uniqueInitName = MixinBuilder.getInitializerName(Symbols.NEW, mixinId); mixinFactorySend = (AbstractUninitializedMessageSendNode) createMessageSend(uniqueInitName, new ExpressionNode[] {mxnBuilder.getInitializerMethodBuilder().getSelfRead(getSource(coord))}, false, getSource(coord), null, language); } mxnBuilder.addMixinFactorySend(mixinFactorySend); } private void inheritanceClause(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { ExpressionNode superClassResolution = inheritancePrefixAndSuperclass(mxnBuilder); mxnBuilder.setSuperClassResolution(superClassResolution); if (sym != NewTerm && sym != MixinOperator) { // This factory method on the super class is actually called as // initializer of the super class after object creation. // The Newspeak spec isn't entirely straight forward on that, but it says // that it is a runtime error if it is not the primary factory method. // Which for me implies that this one is special. And indeed, it is // used to create the proper initialize method, on which we rely here. ExpressionNode superFactorySend = messages( mxnBuilder.getInitializerMethodBuilder(), mxnBuilder.getInitializerMethodBuilder().getSuperReadNode(getEmptySource())); SSymbol initializerName = MixinBuilder.getInitializerName( ((AbstractUninitializedMessageSendNode) superFactorySend).getSelector()); // TODO: the false we pass here, should that be conditional on the superFactorSend being a #new send? mxnBuilder.setSuperclassFactorySend( MessageSendNode.adaptSymbol( initializerName, (AbstractUninitializedMessageSendNode) superFactorySend, language.getVM()), false); } else { mxnBuilder.setSuperclassFactorySend( mxnBuilder.createStandardSuperFactorySend( getEmptySource()), true); } } private ExpressionNode inheritancePrefixAndSuperclass( final MixinBuilder mxnBuilder) throws ParseError, MixinDefinitionError { MethodBuilder meth = mxnBuilder.getClassInstantiationMethodBuilder(); SourceCoordinate coord = getCoordinate(); if (acceptIdentifier("outer", KeywordTag.class)) { String outer = identifier(); ExpressionNode self = meth.getOuterRead(outer, getSource(coord)); if (sym == Identifier) { return unaryMessage(self, false, null); } else { return self; } } ExpressionNode self; if (acceptIdentifier("super", KeywordTag.class)) { self = meth.getSuperReadNode(getSource(coord)); } else if (acceptIdentifier("self", KeywordTag.class)) { self = meth.getSelfRead(getSource(coord)); } else { return meth.getImplicitReceiverSend(unarySelector(), getSource(coord)); } return unaryMessage(self, false, null); } private void classBody(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { classHeader(mxnBuilder); sideDeclaration(mxnBuilder); if (sym == Colon) { classSideDecl(mxnBuilder); } } private void classSideDecl(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { mxnBuilder.switchToClassSide(); expect(Colon, KeywordTag.class); expect(NewTerm, null); while (sym != EndTerm) { comments(); methodDeclaration(mxnBuilder); comments(); } expect(EndTerm, null); } private void classHeader(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { expect(NewTerm, null); classComment(mxnBuilder); SourceCoordinate coord = getCoordinate(); if (sym == Or) { slotDeclarations(mxnBuilder); } comments(); if (sym != EndTerm) { initExprs(mxnBuilder); } mxnBuilder.setInitializerSource(getSource(coord)); expect(EndTerm, null); mxnBuilder.finalizeInitializer(); } private void classComment(final MixinBuilder mxnBuilder) throws ParseError { mxnBuilder.setComment(comments()); } private String comments() throws ParseError { String comment = ""; while (sym == BeginComment) { if (comment.length() > 0) { comment += "\n"; } comment += comment(); } return comment; } private String comment() throws ParseError { SourceCoordinate coord = getCoordinate(); expect(BeginComment, null); String comment = ""; while (sym != EndComment) { comment += lexer.getCommentPart(); getSymbolFromLexer(); if (sym == BeginComment) { comment += "(*" + comments() + "*)"; } if (sym == NONE) { throw new ParseError("Comment seems not to be closed", EndComment, this); } } expect(EndComment, null); language.getVM().reportSyntaxElement(CommentTag.class, getSource(coord)); return comment; } private void slotDeclarations(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { // Newspeak-speak: we do not support simSlotDecls, i.e., // simultaneous slots clauses (spec 6.3.2) expect(Or, DelimiterOpeningTag.class); while (sym != Or) { slotDefinition(mxnBuilder); } comments(); expect(Or, DelimiterClosingTag.class); } private void slotDefinition(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { comments(); if (sym == Or) { return; } SourceCoordinate coord = getCoordinate(); AccessModifier acccessModifier = accessModifier(); String slotName = slotDecl(); boolean immutable; ExpressionNode init; if (accept(Equal, KeywordTag.class)) { immutable = true; init = expression(mxnBuilder.getInitializerMethodBuilder()); expect(Period, StatementSeparatorTag.class); } else if (accept(SlotMutableAssign, KeywordTag.class)) { immutable = false; init = expression(mxnBuilder.getInitializerMethodBuilder()); expect(Period, StatementSeparatorTag.class); } else { immutable = false; init = null; } mxnBuilder.addSlot(symbolFor(slotName), acccessModifier, immutable, init, getSource(coord)); } private AccessModifier accessModifier() { if (sym == Identifier) { if (acceptIdentifier("private", KeywordTag.class)) { return AccessModifier.PRIVATE; } if (acceptIdentifier("protected", KeywordTag.class)) { return AccessModifier.PROTECTED; } if (acceptIdentifier("public", KeywordTag.class)) { return AccessModifier.PUBLIC; } } return AccessModifier.PROTECTED; } private String slotDecl() throws ParseError { return identifier(); } private void initExprs(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { MethodBuilder initializer = mxnBuilder.getInitializerMethodBuilder(); mxnBuilder.addInitializerExpression(expression(initializer)); while (accept(Period, StatementSeparatorTag.class)) { if (sym != EndTerm) { mxnBuilder.addInitializerExpression(expression(initializer)); } } } private void sideDeclaration(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { expect(NewTerm, DelimiterOpeningTag.class); comments(); while (canAcceptIdentifierWithOptionalEarlierIdentifier( new String[]{"private", "protected", "public"}, "class")) { nestedClassDeclaration(mxnBuilder); comments(); } while (sym != EndTerm) { comments(); methodDeclaration(mxnBuilder); comments(); } expect(EndTerm, DelimiterClosingTag.class); } private void nestedClassDeclaration(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); AccessModifier accessModifier = accessModifier(); MixinBuilder nestedCls = classDeclaration(mxnBuilder, accessModifier); mxnBuilder.addNestedMixin(nestedCls.assemble(getSource(coord))); } private boolean symIn(final Symbol[] ss) { return arrayContains(ss, sym); } private boolean canAcceptIdentifierWithOptionalEarlierIdentifier( final String[] earlierIdentifier, final String identifier) { if (sym != Identifier) { return false; } if (identifier.equals(text)) { return true; } boolean oneMatches = false; for (String s : earlierIdentifier) { if (s.equals(text)) { oneMatches = true; break; } } if (!oneMatches) { return false; } peekForNextSymbolFromLexer(); return nextSym == Identifier && identifier.equals(nextText); } private boolean acceptIdentifier(final String identifier, final Class<? extends Tags> tag) { if (sym == Identifier && identifier.equals(text)) { accept(Identifier, tag); return true; } return false; } private boolean accept(final Symbol s, final Class<? extends Tags> tag) { if (sym == s) { SourceCoordinate coord = tag == null ? null : getCoordinate(); getSymbolFromLexer(); if (tag != null) { language.getVM().reportSyntaxElement(tag, getSource(coord)); } return true; } return false; } private boolean acceptOneOf(final Symbol[] ss, final Class<? extends Tags> tag) { if (symIn(ss)) { SourceCoordinate coord = tag == null ? null : getCoordinate(); getSymbolFromLexer(); if (tag != null) { language.getVM().reportSyntaxElement(tag, getSource(coord)); } return true; } return false; } private void expectIdentifier(final String identifier, final String msg, final Class<? extends Tags> tag) throws ParseError { if (acceptIdentifier(identifier, tag)) { return; } throw new ParseError(msg, Identifier, this); } private void expectIdentifier(final String identifier, final Class<? extends Tags> tag) throws ParseError { expectIdentifier(identifier, "Unexpected token. Expected '" + identifier + "', but found %(found)s", tag); } private void expect(final Symbol s, final String msg, final Class<? extends Tags> tag) throws ParseError { if (accept(s, tag)) { return; } throw new ParseError(msg, s, this); } private void expect(final Symbol s, final Class<? extends Tags> tag) throws ParseError { expect(s, "Unexpected symbol. Expected %(expected)s, but found %(found)s", tag); } private boolean expectOneOf(final Symbol[] ss, final Class<? extends Tags> tag) throws ParseError { if (acceptOneOf(ss, tag)) { return true; } throw new ParseErrorWithSymbols("Unexpected symbol. Expected one of " + "%(expected)s, but found %(found)s", ss, this); } SourceSection getEmptySource() { SourceCoordinate coord = getCoordinate(); return source.createSection(coord.charIndex, 0); } public SourceSection getSource(final SourceCoordinate coord) { assert lexer.getNumberOfCharactersRead() - coord.charIndex >= 0; SourceSection ss = source.createSection(coord.charIndex, Math.max(lexer.getNumberOfNonWhiteCharsRead() - coord.charIndex, 0)); return ss; } private void methodDeclaration(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); AccessModifier accessModifier = accessModifier(); MethodBuilder builder = new MethodBuilder( mxnBuilder, mxnBuilder.getScopeForCurrentParserPosition()); messagePattern(builder); expect(Equal, "Unexpected symbol %(found)s. Tried to parse method declaration and expect '=' between message pattern, and method body.", KeywordTag.class); ExpressionNode body = methodBlock(builder); builder.finalizeMethodScope(); SInvokable meth = builder.assemble(body, accessModifier, getSource(coord)); if (structuralProbe != null) { structuralProbe.recordNewMethod(meth); } mxnBuilder.addMethod(meth); } private void messagePattern(final MethodBuilder builder) throws ParseError { builder.addArgument("self", getEmptySource()); switch (sym) { case Identifier: unaryPattern(builder); break; case Keyword: keywordPattern(builder); break; default: binaryPattern(builder); break; } } protected void unaryPattern(final MethodBuilder builder) throws ParseError { SourceCoordinate coord = getCoordinate(); builder.setSignature(unarySelector()); builder.addMethodDefinitionSource(getSource(coord)); } protected void binaryPattern(final MethodBuilder builder) throws ParseError { SourceCoordinate coord = getCoordinate(); builder.setSignature(binarySelector()); builder.addMethodDefinitionSource(getSource(coord)); coord = getCoordinate(); builder.addArgument(argument(), getSource(coord)); } protected void keywordPattern(final MethodBuilder builder) throws ParseError { StringBuilder kw = new StringBuilder(); do { SourceCoordinate coord = getCoordinate(); kw.append(keyword()); builder.addMethodDefinitionSource(getSource(coord)); coord = getCoordinate(); builder.addArgument(argument(), getSource(coord)); } while (sym == Keyword); builder.setSignature(symbolFor(kw.toString())); } private ExpressionNode methodBlock(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); expect(NewTerm, DelimiterOpeningTag.class); ExpressionNode methodBody = blockContents(builder); expect(EndTerm, DelimiterClosingTag.class); lastMethodsSourceSection = getSource(coord); return methodBody; } protected SSymbol unarySelector() throws ParseError { return symbolFor(identifier()); } protected SSymbol binarySelector() throws ParseError { String s = text; // Checkstyle: stop if (accept(Or, null)) { } else if (accept(Comma, null)) { } else if (accept(Minus, null)) { } else if (accept(Equal, null)) { } else if (acceptOneOf(singleOpSyms, null)) { } else if (accept(OperatorSequence, null)) { } else { throw new ParseError("Unexpected symbol. Expected binary operator, " + "but found %(found)s", Symbol.NONE, this); } // Checkstyle: resume return symbolFor(s); } private String identifier() throws ParseError { String s = text; expect(Identifier, null); return s; } protected String keyword() throws ParseError { String s = text; expect(Keyword, null); return s; } protected String setterKeyword() throws ParseError { String s = text; expect(Symbol.SetterKeyword, null); return s; } private String argument() throws ParseError { SourceCoordinate coord = getCoordinate(); String id = identifier(); language.getVM().reportSyntaxElement(ArgumentTag.class, getSource(coord)); return id; } private ExpressionNode blockContents(final MethodBuilder builder) throws ProgramDefinitionError { comments(); if (accept(Or, DelimiterOpeningTag.class)) { locals(builder); expect(Or, DelimiterClosingTag.class); } builder.setVarsOnMethodScope(); return blockBody(builder); } private void locals(final MethodBuilder builder) throws ParseError, MethodDefinitionError { while (sym == Identifier) { SourceCoordinate coord = getCoordinate(); String id = identifier(); SourceSection source = getSource(coord); builder.addLocal(id, source); language.getVM().reportSyntaxElement(LocalVariableTag.class, source); } } private ExpressionNode blockBody(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); List<ExpressionNode> expressions = new ArrayList<ExpressionNode>(); boolean sawPeriod = true; while (true) { comments(); if (accept(Exit, KeywordTag.class)) { if (!sawPeriod) { expect(Period, null); } expressions.add(result(builder)); return createSequence(expressions, getSource(coord)); } else if (sym == EndBlock) { return createSequence(expressions, getSource(coord)); } else if (sym == EndTerm) { // the end of the method has been found (EndTerm) - make it implicitly // return "self" ExpressionNode self = builder.getSelfRead(getEmptySource()); expressions.add(self); return createSequence(expressions, getSource(coord)); } if (!sawPeriod) { expect(Period, null); } expressions.add(expression(builder)); sawPeriod = accept(Period, StatementSeparatorTag.class); } } private ExpressionNode result(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); ExpressionNode exp = expression(builder); accept(Period, StatementSeparatorTag.class); if (builder.isBlockMethod()) { return builder.getNonLocalReturn(exp, getSource(coord)); } else { return exp; } } private ExpressionNode expression(final MethodBuilder builder) throws ProgramDefinitionError { comments(); peekForNextSymbolFromLexer(); if (sym == Symbol.SetterKeyword) { return setterSends(builder); } else { return evaluation(builder); } } protected ExpressionNode setterSends(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); if (sym != Symbol.SetterKeyword) { throw new ParseError("Expected setter send, but found instead a %(found)s", Symbol.SetterKeyword, this); } SSymbol setter = symbolFor(setterKeyword()); peekForNextSymbolFromLexer(); ExpressionNode value; if (sym == Symbol.SetterKeyword) { value = setterSends(builder); } else { value = evaluation(builder); } return builder.getSetterSend(setter, value, getSource(coord)); } private ExpressionNode evaluation(final MethodBuilder builder) throws ProgramDefinitionError { ExpressionNode exp; if (sym == Keyword) { exp = keywordMessage(builder, builder.getSelfRead(getEmptySource()), false, false, null); } else { exp = primary(builder); } if (symIsMessageSend()) { exp = messages(builder, exp); } return exp; } private boolean symIsMessageSend() { return sym == Identifier || sym == Keyword || sym == OperatorSequence || symIn(binaryOpSyms) || sym == EventualSend; } private ExpressionNode primary(final MethodBuilder builder) throws ProgramDefinitionError { switch (sym) { case Identifier: { SourceCoordinate coord = getCoordinate(); // Parse true, false, and nil as keyword-like constructs // (cf. Newspeak spec on reserved words) if (acceptIdentifier("true", LiteralTag.class)) { return new TrueLiteralNode(getSource(coord)); } if (acceptIdentifier("false", LiteralTag.class)) { return new FalseLiteralNode(getSource(coord)); } if (acceptIdentifier("nil", LiteralTag.class)) { return new NilLiteralNode(getSource(coord)); } if ("outer".equals(text)) { return outerSend(builder); } SSymbol selector = unarySelector(); return builder.getImplicitReceiverSend(selector, getSource(coord)); } case NewTerm: { return nestedTerm(builder); } case NewBlock: { MethodBuilder bgenc = new MethodBuilder(builder); ExpressionNode blockBody = nestedBlock(bgenc); bgenc.finalizeMethodScope(); SInvokable blockMethod = bgenc.assemble(blockBody, AccessModifier.BLOCK_METHOD, lastMethodsSourceSection); builder.addEmbeddedBlockMethod(blockMethod); if (bgenc.requiresContext() || VmSettings.TRUFFLE_DEBUGGER_ENABLED) { return new BlockNodeWithContext(blockMethod, lastMethodsSourceSection); } else { return new BlockNode(blockMethod, lastMethodsSourceSection); } } case LCurly: { return literalArray(builder); } default: { if (symIn(literalSyms)) { return literal(); } } } throw new ParseError("Unexpected symbol. Tried to parse a primary " + "expression but found %(found)s", sym, this); } private ExpressionNode outerSend(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); expectIdentifier("outer", KeywordTag.class); String outer = identifier(); ExpressionNode operand = builder.getOuterRead(outer, getSource(coord)); operand = binaryConsecutiveMessages(builder, operand, false, null); return operand; } protected ExpressionNode binaryConsecutiveMessages( final MethodBuilder builder, ExpressionNode operand, boolean eventualSend, SourceSection sendOp) throws ProgramDefinitionError { while (sym == OperatorSequence || symIn(binaryOpSyms)) { operand = binaryMessage(builder, operand, eventualSend, sendOp); SourceCoordinate coord = getCoordinate(); eventualSend = accept(EventualSend, KeywordTag.class); if (eventualSend) { sendOp = getSource(coord); } } return operand; } private ExpressionNode messages(final MethodBuilder builder, final ExpressionNode receiver) throws ProgramDefinitionError { ExpressionNode msg = receiver; SourceCoordinate coord = getCoordinate(); boolean eventualSend = accept(EventualSend, KeywordTag.class); SourceSection sendOp = null; if (eventualSend) { sendOp = getSource(coord); } while (sym == Identifier) { msg = unaryMessage(msg, eventualSend, sendOp); eventualSend = accept(EventualSend, KeywordTag.class); if (eventualSend) { sendOp = getSource(coord); } } if (sym == OperatorSequence || symIn(binaryOpSyms)) { msg = binaryConsecutiveMessages(builder, msg, eventualSend, sendOp); eventualSend = accept(EventualSend, KeywordTag.class); if (eventualSend) { sendOp = getSource(coord); } } if (sym == Keyword) { msg = keywordMessage(builder, msg, true, eventualSend, sendOp); } return msg; } protected ExpressionNode unaryMessage(final ExpressionNode receiver, final boolean eventualSend, final SourceSection sendOperator) throws ParseError { SourceCoordinate coord = getCoordinate(); SSymbol selector = unarySelector(); return createMessageSend(selector, new ExpressionNode[] {receiver}, eventualSend, getSource(coord), sendOperator, language); } private ExpressionNode tryInliningBinaryMessage(final MethodBuilder builder, final ExpressionNode receiver, final SourceCoordinate coord, final SSymbol msg, final ExpressionNode operand) { List<ExpressionNode> arguments = new ArrayList<ExpressionNode>(); arguments.add(receiver); arguments.add(operand); SourceSection source = getSource(coord); ExpressionNode node = inlineControlStructureIfPossible(builder, arguments, msg.getString(), msg.getNumberOfSignatureArguments(), source); return node; } protected ExpressionNode binaryMessage(final MethodBuilder builder, final ExpressionNode receiver, final boolean eventualSend, final SourceSection sendOperator) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); SSymbol msg = binarySelector(); ExpressionNode operand = binaryOperand(builder); if (!eventualSend) { ExpressionNode node = tryInliningBinaryMessage(builder, receiver, coord, msg, operand); if (node != null) { return node; } } return createMessageSend(msg, new ExpressionNode[] {receiver, operand}, eventualSend, getSource(coord), sendOperator, language); } private ExpressionNode binaryOperand(final MethodBuilder builder) throws ProgramDefinitionError { ExpressionNode operand = primary(builder); // a binary operand can receive unaryMessages // Example: 2 * 3 asString // is evaluated as 2 * (3 asString) SourceCoordinate coord = getCoordinate(); boolean evenutalSend = accept(EventualSend, KeywordTag.class); while (sym == Identifier) { SourceSection sendOp = null; if (evenutalSend) { sendOp = getSource(coord); } operand = unaryMessage(operand, evenutalSend, sendOp); evenutalSend = accept(EventualSend, KeywordTag.class); } assert !evenutalSend : "eventualSend should not be true, because that means we steal it from the next operation (think here shouldn't be one, but still...)"; return operand; } // TODO: if the eventual send is not consumed by an expression (assignment, etc) // we don't need to create a promise protected ExpressionNode keywordMessage(final MethodBuilder builder, final ExpressionNode receiver, final boolean explicitRcvr, final boolean eventualSend, final SourceSection sendOperator) throws ProgramDefinitionError { assert !(!explicitRcvr && eventualSend); SourceCoordinate coord = getCoordinate(); List<ExpressionNode> arguments = new ArrayList<ExpressionNode>(); StringBuilder kw = new StringBuilder(); arguments.add(receiver); do { kw.append(keyword()); arguments.add(formula(builder)); } while (sym == Keyword); String msgStr = kw.toString(); SSymbol msg = symbolFor(msgStr); if (!eventualSend) { ExpressionNode node = inlineControlStructureIfPossible(builder, arguments, msgStr, msg.getNumberOfSignatureArguments(), getSource(coord)); if (node != null) { return node; } } SourceSection source = getSource(coord); ExpressionNode[] args = arguments.toArray(new ExpressionNode[0]); if (explicitRcvr) { return createMessageSend( msg, args, eventualSend, source, sendOperator, language); } else { assert !eventualSend; return createImplicitReceiverSend(msg, args, builder.getCurrentMethodScope(), builder.getEnclosingMixinBuilder().getMixinId(), source, language.getVM()); } } protected ExpressionNode inlineControlStructureIfPossible( final MethodBuilder builder, final List<ExpressionNode> arguments, final String msgStr, final int numberOfArguments, final SourceSection source) { if (numberOfArguments == 2) { if (arguments.get(1) instanceof LiteralNode) { if ("ifTrue:".equals(msgStr)) { ExpressionNode condition = arguments.get(0); condition.markAsControlFlowCondition(); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); return new IfInlinedLiteralNode(condition, true, inlinedBody, arguments.get(1), source); } else if ("ifFalse:".equals(msgStr)) { ExpressionNode condition = arguments.get(0); condition.markAsControlFlowCondition(); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); return new IfInlinedLiteralNode(condition, false, inlinedBody, arguments.get(1), source); } else if ("whileTrue:".equals(msgStr)) { ExpressionNode inlinedCondition = ((LiteralNode) arguments.get(0)).inline(builder); inlinedCondition.markAsControlFlowCondition(); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); inlinedBody.markAsLoopBody(); return new WhileInlinedLiteralsNode(inlinedCondition, inlinedBody, true, arguments.get(0), arguments.get(1), source); } else if ("whileFalse:".equals(msgStr)) { ExpressionNode inlinedCondition = ((LiteralNode) arguments.get(0)).inline(builder); inlinedCondition.markAsControlFlowCondition(); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); inlinedBody.markAsLoopBody(); return new WhileInlinedLiteralsNode(inlinedCondition, inlinedBody, false, arguments.get(0), arguments.get(1), source); } else if ("or:".equals(msgStr) || "||".equals(msgStr)) { ExpressionNode inlinedArg = ((LiteralNode) arguments.get(1)).inline(builder); return new OrInlinedLiteralNode(arguments.get(0), inlinedArg, arguments.get(1), source); } else if ("and:".equals(msgStr) || "&&".equals(msgStr)) { ExpressionNode inlinedArg = ((LiteralNode) arguments.get(1)).inline(builder); return new AndInlinedLiteralNode(arguments.get(0), inlinedArg, arguments.get(1), source); } else if (!VmSettings.DYNAMIC_METRICS && "timesRepeat:".equals(msgStr)) { ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); inlinedBody.markAsLoopBody(); return IntTimesRepeatLiteralNodeGen.create(inlinedBody, arguments.get(1), source, arguments.get(0)); } } } else if (numberOfArguments == 3) { if ("ifTrue:ifFalse:".equals(msgStr) && arguments.get(1) instanceof LiteralNode && arguments.get(2) instanceof LiteralNode) { LiteralNode blockOrVal = (LiteralNode) arguments.get(2); ExpressionNode condition = arguments.get(0); condition.markAsControlFlowCondition(); ExpressionNode inlinedTrueNode = ((LiteralNode) arguments.get(1)).inline(builder); ExpressionNode inlinedFalseNode = blockOrVal.inline(builder); return new IfTrueIfFalseInlinedLiteralsNode(condition, inlinedTrueNode, inlinedFalseNode, arguments.get(1), arguments.get(2), source); } else if (!VmSettings.DYNAMIC_METRICS && "to:do:".equals(msgStr) && arguments.get(2) instanceof LiteralNode) { LiteralNode blockOrVal = (LiteralNode) arguments.get(2); try { ExpressionNode inlinedBody = blockOrVal.inline(builder); inlinedBody.markAsLoopBody(); Local loopIdx = getLoopIdx(builder, blockOrVal, source); return IntToDoInlinedLiteralsNodeGen.create(inlinedBody, loopIdx, arguments.get(2), source, arguments.get(0), arguments.get(1)); } catch (MethodDefinitionError e) { throw new RuntimeException(e); } } else if (!VmSettings.DYNAMIC_METRICS && "downTo:do:".equals(msgStr) && arguments.get(2) instanceof LiteralNode) { LiteralNode blockOrVal = (LiteralNode) arguments.get(2); try { ExpressionNode inlinedBody = blockOrVal.inline(builder); inlinedBody.markAsLoopBody(); Local loopIdx = getLoopIdx(builder, blockOrVal, source); return IntDownToDoInlinedLiteralsNodeGen.create(inlinedBody, loopIdx, arguments.get(2), source, arguments.get(0), arguments.get(1)); } catch (MethodDefinitionError e) { throw new RuntimeException(e); } } } return null; } private Local getLoopIdx(final MethodBuilder builder, final LiteralNode blockOrVal, final SourceSection source) throws MethodDefinitionError { Local loopIdx; if (blockOrVal instanceof BlockNode) { Argument[] args = ((BlockNode) blockOrVal).getArguments(); assert args.length == 2; loopIdx = builder.getLocal(args[1].getQualifiedName()); } else { // if it is a literal, we still need a memory location for counting, so, // add a synthetic local loopIdx = builder.addLocalAndUpdateScope( "!i" + SourceCoordinate.getLocationQualifier(source), source); } return loopIdx; } private ExpressionNode formula(final MethodBuilder builder) throws ProgramDefinitionError { ExpressionNode operand = binaryOperand(builder); SourceCoordinate coord = getCoordinate(); boolean evenutalSend = accept(EventualSend, KeywordTag.class); SourceSection sendOp = null; if (evenutalSend) { sendOp = getSource(coord); } operand = binaryConsecutiveMessages(builder, operand, evenutalSend, sendOp); return operand; } private ExpressionNode nestedTerm(final MethodBuilder builder) throws ProgramDefinitionError { expect(NewTerm, DelimiterOpeningTag.class); ExpressionNode exp = expression(builder); expect(EndTerm, DelimiterClosingTag.class); return exp; } private LiteralNode literal() throws ParseError { switch (sym) { case Pound: return literalSymbol(); case STString: return literalString(); default: return literalNumber(); } } private LiteralNode literalNumber() throws ParseError { SourceCoordinate coord = getCoordinate(); NumeralParser parser = lexer.getNumeralParser(); expect(Numeral, null); SourceSection source = getSource(coord); if (parser.isInteger()) { return literalInteger(parser, source); } else { return literalDouble(parser, source); } } private LiteralNode literalInteger(final NumeralParser parser, final SourceSection source) throws ParseError { try { Number n = parser.getInteger(); if (n instanceof Long) { return new IntegerLiteralNode((Long) n, source); } else { return new BigIntegerLiteralNode((BigInteger) n, source); } } catch (NumberFormatException e) { throw new ParseError("Could not parse integer. Expected a number but " + "got '" + text + "'", NONE, this); } } private LiteralNode literalDouble(final NumeralParser parser, final SourceSection source) throws ParseError { try { return new DoubleLiteralNode(parser.getDouble(), source); } catch (NumberFormatException e) { throw new ParseError("Could not parse double. Expected a number but " + "got '" + text + "'", NONE, this); } } private LiteralNode literalSymbol() throws ParseError { SourceCoordinate coord = getCoordinate(); SSymbol symb; expect(Pound, null); if (sym == STString) { String s = string(); symb = symbolFor(s); } else { symb = selector(); } return new SymbolLiteralNode(symb, getSource(coord)); } private LiteralNode literalString() throws ParseError { SourceCoordinate coord = getCoordinate(); String s = string(); return new StringLiteralNode(s, getSource(coord)); } private LiteralNode literalArray(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); List<ExpressionNode> expressions = new ArrayList<ExpressionNode>(); expect(LCurly, DelimiterOpeningTag.class); boolean needsSeparator = false; while (true) { comments(); if (sym == RCurly) { expect(RCurly, DelimiterClosingTag.class); return ArrayLiteralNode.create(expressions.toArray(new ExpressionNode[0]), getSource(coord)); } if (needsSeparator) { expect(Period, "Could not parse statement. Expected a '.' but got '" + text + "'", StatementSeparatorTag.class); } expressions.add(expression(builder)); needsSeparator = !accept(Period, StatementSeparatorTag.class); } } private SSymbol selector() throws ParseError { if (sym == OperatorSequence || symIn(singleOpSyms)) { return binarySelector(); } else if (sym == Keyword || sym == KeywordSequence) { return keywordSelector(); } else { return unarySelector(); } } private SSymbol keywordSelector() throws ParseError { String s = text; expectOneOf(keywordSelectorSyms, null); SSymbol symb = symbolFor(s); return symb; } private String string() throws ParseError { String s = text; expect(STString, null); return s; } private String stripColons(final String str) { return str.replace(":", ""); } private ExpressionNode nestedBlock(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); expect(NewBlock, DelimiterOpeningTag.class); builder.addArgument("$blockSelf", getEmptySource()); if (sym == Colon) { blockPattern(builder); } String outerMethodName = stripColons(builder.getOuterBuilder(). getSignature().getString()); // generate Block signature String blockSig = "λ" + outerMethodName + "@" + coord.startLine + "@" + coord.startColumn; int argSize = builder.getNumberOfArguments(); for (int i = 1; i < argSize; i++) { blockSig += ":"; } builder.setSignature(symbolFor(blockSig)); ExpressionNode expressions = blockContents(builder); expect(EndBlock, DelimiterClosingTag.class); lastMethodsSourceSection = getSource(coord); return expressions; } private void blockPattern(final MethodBuilder builder) throws ParseError { blockArguments(builder); expect(Or, KeywordTag.class); } private void blockArguments(final MethodBuilder builder) throws ParseError { do { expect(Colon, KeywordTag.class); SourceCoordinate coord = getCoordinate(); builder.addArgument(argument(), getSource(coord)); } while (sym == Colon); } private void getSymbolFromLexer() { sym = lexer.getSym(); text = lexer.getText(); } private void peekForNextSymbolFromLexer() { Peek peek = lexer.peek(); nextSym = peek.nextSym; nextText = peek.nextText; } private static boolean printableSymbol(final Symbol sym) { return sym == Numeral || sym.compareTo(STString) >= 0; } }
package org.jfree.chart.axis; import java.awt.BasicStroke; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.ValueAxisPlot; import org.jfree.chart.util.ParamChecks; import org.jfree.data.Range; import org.jfree.data.time.Day; import org.jfree.data.time.Month; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.Year; import org.jfree.io.SerialUtilities; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleEdge; import org.jfree.ui.TextAnchor; import org.jfree.util.PublicCloneable; /** * An axis that displays a date scale based on a * {@link org.jfree.data.time.RegularTimePeriod}. This axis works when * displayed across the bottom or top of a plot, but is broken for display at * the left or right of charts. */ public class PeriodAxis extends ValueAxis implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 8353295532075872069L; /** The first time period in the overall range. */ private RegularTimePeriod first; /** The last time period in the overall range. */ private RegularTimePeriod last; /** * The time zone used to convert 'first' and 'last' to absolute * milliseconds. */ private TimeZone timeZone; /** * The locale (never <code>null</code>). * * @since 1.0.13 */ private Locale locale; /** * A calendar used for date manipulations in the current time zone and * locale. */ private Calendar calendar; /** * The {@link RegularTimePeriod} subclass used to automatically determine * the axis range. */ private Class autoRangeTimePeriodClass; /** * Indicates the {@link RegularTimePeriod} subclass that is used to * determine the spacing of the major tick marks. */ private Class majorTickTimePeriodClass; /** * A flag that indicates whether or not tick marks are visible for the * axis. */ private boolean minorTickMarksVisible; /** * Indicates the {@link RegularTimePeriod} subclass that is used to * determine the spacing of the minor tick marks. */ private Class minorTickTimePeriodClass; /** The length of the tick mark inside the data area (zero permitted). */ private float minorTickMarkInsideLength = 0.0f; /** The length of the tick mark outside the data area (zero permitted). */ private float minorTickMarkOutsideLength = 2.0f; /** The stroke used to draw tick marks. */ private transient Stroke minorTickMarkStroke = new BasicStroke(0.5f); /** The paint used to draw tick marks. */ private transient Paint minorTickMarkPaint = Color.black; /** Info for each labeling band. */ private PeriodAxisLabelInfo[] labelInfo; /** * Creates a new axis. * * @param label the axis label. */ public PeriodAxis(String label) { this(label, new Day(), new Day()); } /** * Creates a new axis. * * @param label the axis label (<code>null</code> permitted). * @param first the first time period in the axis range * (<code>null</code> not permitted). * @param last the last time period in the axis range * (<code>null</code> not permitted). */ public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last) { this(label, first, last, TimeZone.getDefault(), Locale.getDefault()); } /** * Creates a new axis. * * @param label the axis label (<code>null</code> permitted). * @param first the first time period in the axis range * (<code>null</code> not permitted). * @param last the last time period in the axis range * (<code>null</code> not permitted). * @param timeZone the time zone (<code>null</code> not permitted). * * @deprecated As of version 1.0.13, you should use the constructor that * specifies a Locale also. */ public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last, TimeZone timeZone) { this(label, first, last, timeZone, Locale.getDefault()); } /** * Creates a new axis. * * @param label the axis label (<code>null</code> permitted). * @param first the first time period in the axis range * (<code>null</code> not permitted). * @param last the last time period in the axis range * (<code>null</code> not permitted). * @param timeZone the time zone (<code>null</code> not permitted). * @param locale the locale (<code>null</code> not permitted). * * @since 1.0.13 */ public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last, TimeZone timeZone, Locale locale) { super(label, null); ParamChecks.nullNotPermitted(timeZone, "timeZone"); ParamChecks.nullNotPermitted(locale, "locale"); this.first = first; this.last = last; this.timeZone = timeZone; this.locale = locale; this.calendar = Calendar.getInstance(timeZone, locale); this.first.peg(this.calendar); this.last.peg(this.calendar); this.autoRangeTimePeriodClass = first.getClass(); this.majorTickTimePeriodClass = first.getClass(); this.minorTickMarksVisible = false; this.minorTickTimePeriodClass = RegularTimePeriod.downsize( this.majorTickTimePeriodClass); setAutoRange(true); this.labelInfo = new PeriodAxisLabelInfo[2]; SimpleDateFormat df0 = new SimpleDateFormat("MMM", locale); df0.setTimeZone(timeZone); this.labelInfo[0] = new PeriodAxisLabelInfo(Month.class, df0); SimpleDateFormat df1 = new SimpleDateFormat("yyyy", locale); df1.setTimeZone(timeZone); this.labelInfo[1] = new PeriodAxisLabelInfo(Year.class, df1); } /** * Returns the first time period in the axis range. * * @return The first time period (never <code>null</code>). */ public RegularTimePeriod getFirst() { return this.first; } /** * Sets the first time period in the axis range and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param first the time period (<code>null</code> not permitted). */ public void setFirst(RegularTimePeriod first) { ParamChecks.nullNotPermitted(first, "first"); this.first = first; this.first.peg(this.calendar); fireChangeEvent(); } /** * Returns the last time period in the axis range. * * @return The last time period (never <code>null</code>). */ public RegularTimePeriod getLast() { return this.last; } /** * Sets the last time period in the axis range and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param last the time period (<code>null</code> not permitted). */ public void setLast(RegularTimePeriod last) { ParamChecks.nullNotPermitted(last, "last"); this.last = last; this.last.peg(this.calendar); fireChangeEvent(); } /** * Returns the time zone used to convert the periods defining the axis * range into absolute milliseconds. * * @return The time zone (never <code>null</code>). */ public TimeZone getTimeZone() { return this.timeZone; } /** * Sets the time zone that is used to convert the time periods into * absolute milliseconds. * * @param zone the time zone (<code>null</code> not permitted). */ public void setTimeZone(TimeZone zone) { ParamChecks.nullNotPermitted(zone, "zone"); this.timeZone = zone; this.calendar = Calendar.getInstance(zone, this.locale); this.first.peg(this.calendar); this.last.peg(this.calendar); fireChangeEvent(); } /** * Returns the locale for this axis. * * @return The locale (never (<code>null</code>). * * @since 1.0.13 */ public Locale getLocale() { return this.locale; } /** * Returns the class used to create the first and last time periods for * the axis range when the auto-range flag is set to <code>true</code>. * * @return The class (never <code>null</code>). */ public Class getAutoRangeTimePeriodClass() { return this.autoRangeTimePeriodClass; } /** * Sets the class used to create the first and last time periods for the * axis range when the auto-range flag is set to <code>true</code> and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param c the class (<code>null</code> not permitted). */ public void setAutoRangeTimePeriodClass(Class c) { ParamChecks.nullNotPermitted(c, "c"); this.autoRangeTimePeriodClass = c; fireChangeEvent(); } /** * Returns the class that controls the spacing of the major tick marks. * * @return The class (never <code>null</code>). */ public Class getMajorTickTimePeriodClass() { return this.majorTickTimePeriodClass; } /** * Sets the class that controls the spacing of the major tick marks, and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param c the class (a subclass of {@link RegularTimePeriod} is * expected). */ public void setMajorTickTimePeriodClass(Class c) { ParamChecks.nullNotPermitted(c, "c"); this.majorTickTimePeriodClass = c; fireChangeEvent(); } /** * Returns the flag that controls whether or not minor tick marks * are displayed for the axis. * * @return A boolean. */ public boolean isMinorTickMarksVisible() { return this.minorTickMarksVisible; } /** * Sets the flag that controls whether or not minor tick marks * are displayed for the axis, and sends a {@link AxisChangeEvent} * to all registered listeners. * * @param visible the flag. */ public void setMinorTickMarksVisible(boolean visible) { this.minorTickMarksVisible = visible; fireChangeEvent(); } /** * Returns the class that controls the spacing of the minor tick marks. * * @return The class (never <code>null</code>). */ public Class getMinorTickTimePeriodClass() { return this.minorTickTimePeriodClass; } /** * Sets the class that controls the spacing of the minor tick marks, and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param c the class (a subclass of {@link RegularTimePeriod} is * expected). */ public void setMinorTickTimePeriodClass(Class c) { ParamChecks.nullNotPermitted(c, "c"); this.minorTickTimePeriodClass = c; fireChangeEvent(); } /** * Returns the stroke used to display minor tick marks, if they are * visible. * * @return A stroke (never <code>null</code>). */ public Stroke getMinorTickMarkStroke() { return this.minorTickMarkStroke; } /** * Sets the stroke used to display minor tick marks, if they are * visible, and sends a {@link AxisChangeEvent} to all registered * listeners. * * @param stroke the stroke (<code>null</code> not permitted). */ public void setMinorTickMarkStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.minorTickMarkStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to display minor tick marks, if they are * visible. * * @return A paint (never <code>null</code>). */ public Paint getMinorTickMarkPaint() { return this.minorTickMarkPaint; } /** * Sets the paint used to display minor tick marks, if they are * visible, and sends a {@link AxisChangeEvent} to all registered * listeners. * * @param paint the paint (<code>null</code> not permitted). */ public void setMinorTickMarkPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.minorTickMarkPaint = paint; fireChangeEvent(); } /** * Returns the inside length for the minor tick marks. * * @return The length. */ public float getMinorTickMarkInsideLength() { return this.minorTickMarkInsideLength; } /** * Sets the inside length of the minor tick marks and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param length the length. */ public void setMinorTickMarkInsideLength(float length) { this.minorTickMarkInsideLength = length; fireChangeEvent(); } /** * Returns the outside length for the minor tick marks. * * @return The length. */ public float getMinorTickMarkOutsideLength() { return this.minorTickMarkOutsideLength; } /** * Sets the outside length of the minor tick marks and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param length the length. */ public void setMinorTickMarkOutsideLength(float length) { this.minorTickMarkOutsideLength = length; fireChangeEvent(); } /** * Returns an array of label info records. * * @return An array. */ public PeriodAxisLabelInfo[] getLabelInfo() { return this.labelInfo; } /** * Sets the array of label info records and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param info the info. */ public void setLabelInfo(PeriodAxisLabelInfo[] info) { this.labelInfo = info; fireChangeEvent(); } /** * Sets the range for the axis, if requested, sends an * {@link AxisChangeEvent} to all registered listeners. As a side-effect, * the auto-range flag is set to <code>false</code> (optional). * * @param range the range (<code>null</code> not permitted). * @param turnOffAutoRange a flag that controls whether or not the auto * range is turned off. * @param notify a flag that controls whether or not listeners are * notified. */ public void setRange(Range range, boolean turnOffAutoRange, boolean notify) { long upper = Math.round(range.getUpperBound()); long lower = Math.round(range.getLowerBound()); this.first = createInstance(this.autoRangeTimePeriodClass, new Date(lower), this.timeZone, this.locale); this.last = createInstance(this.autoRangeTimePeriodClass, new Date(upper), this.timeZone, this.locale); super.setRange(new Range(this.first.getFirstMillisecond(), this.last.getLastMillisecond() + 1.0), turnOffAutoRange, notify); } /** * Configures the axis to work with the current plot. Override this method * to perform any special processing (such as auto-rescaling). */ public void configure() { if (this.isAutoRange()) { autoAdjustRange(); } } /** * Estimates the space (height or width) required to draw the axis. * * @param g2 the graphics device. * @param plot the plot that the axis belongs to. * @param plotArea the area within which the plot (including axes) should * be drawn. * @param edge the axis location. * @param space space already reserved. * * @return The space required to draw the axis (including pre-reserved * space). */ public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) { // create a new space object if one wasn't supplied... if (space == null) { space = new AxisSpace(); } // if the axis is not visible, no additional space is required... if (!isVisible()) { return space; } // if the axis has a fixed dimension, return it... double dimension = getFixedDimension(); if (dimension > 0.0) { space.ensureAtLeast(dimension, edge); } // get the axis label size and update the space object... Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge); double labelHeight, labelWidth; double tickLabelBandsDimension = 0.0; for (int i = 0; i < this.labelInfo.length; i++) { PeriodAxisLabelInfo info = this.labelInfo[i]; FontMetrics fm = g2.getFontMetrics(info.getLabelFont()); tickLabelBandsDimension += info.getPadding().extendHeight(fm.getHeight()); } if (RectangleEdge.isTopOrBottom(edge)) { labelHeight = labelEnclosure.getHeight(); space.add(labelHeight + tickLabelBandsDimension, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { labelWidth = labelEnclosure.getWidth(); space.add(labelWidth + tickLabelBandsDimension, edge); } // add space for the outer tick labels, if any... double tickMarkSpace = 0.0; if (isTickMarksVisible()) { tickMarkSpace = getTickMarkOutsideLength(); } if (this.minorTickMarksVisible) { tickMarkSpace = Math.max(tickMarkSpace, this.minorTickMarkOutsideLength); } space.add(tickMarkSpace, edge); return space; } /** * Draws the axis on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device (<code>null</code> not permitted). * @param cursor the cursor location (determines where to draw the axis). * @param plotArea the area within which the axes and plot should be drawn. * @param dataArea the area within which the data should be drawn. * @param edge the axis location (<code>null</code> not permitted). * @param plotState collects information about the plot * (<code>null</code> permitted). * * @return The axis state (never <code>null</code>). */ public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState) { AxisState axisState = new AxisState(cursor); if (isAxisLineVisible()) { drawAxisLine(g2, cursor, dataArea, edge); } if (isTickMarksVisible()) { drawTickMarks(g2, axisState, dataArea, edge); } if (isTickLabelsVisible()) { for (int band = 0; band < this.labelInfo.length; band++) { axisState = drawTickLabels(band, g2, axisState, dataArea, edge); } } // draw the axis label (note that 'state' is passed in *and* // returned)... axisState = drawLabel(getLabel(), g2, plotArea, dataArea, edge, axisState); return axisState; } /** * Draws the tick marks for the axis. * * @param g2 the graphics device. * @param state the axis state. * @param dataArea the data area. * @param edge the edge. */ protected void drawTickMarks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { if (RectangleEdge.isTopOrBottom(edge)) { drawTickMarksHorizontal(g2, state, dataArea, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { drawTickMarksVertical(g2, state, dataArea, edge); } } /** * Draws the major and minor tick marks for an axis that lies at the top or * bottom of the plot. * * @param g2 the graphics device. * @param state the axis state. * @param dataArea the data area. * @param edge the edge. */ protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { List ticks = new ArrayList(); double x0; double y0 = state.getCursor(); double insideLength = getTickMarkInsideLength(); double outsideLength = getTickMarkOutsideLength(); RegularTimePeriod t = createInstance(this.majorTickTimePeriodClass, this.first.getStart(), getTimeZone(), this.locale); long t0 = t.getFirstMillisecond(); Line2D inside = null; Line2D outside = null; long firstOnAxis = getFirst().getFirstMillisecond(); long lastOnAxis = getLast().getLastMillisecond() + 1; while (t0 <= lastOnAxis) { ticks.add(new NumberTick(Double.valueOf(t0), "", TextAnchor.CENTER, TextAnchor.CENTER, 0.0)); x0 = valueToJava2D(t0, dataArea, edge); if (edge == RectangleEdge.TOP) { inside = new Line2D.Double(x0, y0, x0, y0 + insideLength); outside = new Line2D.Double(x0, y0, x0, y0 - outsideLength); } else if (edge == RectangleEdge.BOTTOM) { inside = new Line2D.Double(x0, y0, x0, y0 - insideLength); outside = new Line2D.Double(x0, y0, x0, y0 + outsideLength); } if (t0 >= firstOnAxis) { g2.setPaint(getTickMarkPaint()); g2.setStroke(getTickMarkStroke()); g2.draw(inside); g2.draw(outside); } // draw minor tick marks if (this.minorTickMarksVisible) { RegularTimePeriod tminor = createInstance( this.minorTickTimePeriodClass, new Date(t0), getTimeZone(), this.locale); long tt0 = tminor.getFirstMillisecond(); while (tt0 < t.getLastMillisecond() && tt0 < lastOnAxis) { double xx0 = valueToJava2D(tt0, dataArea, edge); if (edge == RectangleEdge.TOP) { inside = new Line2D.Double(xx0, y0, xx0, y0 + this.minorTickMarkInsideLength); outside = new Line2D.Double(xx0, y0, xx0, y0 - this.minorTickMarkOutsideLength); } else if (edge == RectangleEdge.BOTTOM) { inside = new Line2D.Double(xx0, y0, xx0, y0 - this.minorTickMarkInsideLength); outside = new Line2D.Double(xx0, y0, xx0, y0 + this.minorTickMarkOutsideLength); } if (tt0 >= firstOnAxis) { g2.setPaint(this.minorTickMarkPaint); g2.setStroke(this.minorTickMarkStroke); g2.draw(inside); g2.draw(outside); } tminor = tminor.next(); tminor.peg(this.calendar); tt0 = tminor.getFirstMillisecond(); } } t = t.next(); t.peg(this.calendar); t0 = t.getFirstMillisecond(); } if (edge == RectangleEdge.TOP) { state.cursorUp(Math.max(outsideLength, this.minorTickMarkOutsideLength)); } else if (edge == RectangleEdge.BOTTOM) { state.cursorDown(Math.max(outsideLength, this.minorTickMarkOutsideLength)); } state.setTicks(ticks); } /** * Draws the tick marks for a vertical axis. * * @param g2 the graphics device. * @param state the axis state. * @param dataArea the data area. * @param edge the edge. */ protected void drawTickMarksVertical(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { // FIXME: implement this... } /** * Draws the tick labels for one "band" of time periods. * * @param band the band index (zero-based). * @param g2 the graphics device. * @param state the axis state. * @param dataArea the data area. * @param edge the edge where the axis is located. * * @return The updated axis state. */ protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { // work out the initial gap double delta1 = 0.0; FontMetrics fm = g2.getFontMetrics(this.labelInfo[band].getLabelFont()); if (edge == RectangleEdge.BOTTOM) { delta1 = this.labelInfo[band].getPadding().calculateTopOutset( fm.getHeight()); } else if (edge == RectangleEdge.TOP) { delta1 = this.labelInfo[band].getPadding().calculateBottomOutset( fm.getHeight()); } state.moveCursor(delta1, edge); long axisMin = this.first.getFirstMillisecond(); long axisMax = this.last.getLastMillisecond(); g2.setFont(this.labelInfo[band].getLabelFont()); g2.setPaint(this.labelInfo[band].getLabelPaint()); // work out the number of periods to skip for labelling RegularTimePeriod p1 = this.labelInfo[band].createInstance( new Date(axisMin), this.timeZone, this.locale); RegularTimePeriod p2 = this.labelInfo[band].createInstance( new Date(axisMax), this.timeZone, this.locale); DateFormat df = this.labelInfo[band].getDateFormat(); df.setTimeZone(this.timeZone); String label1 = df.format(new Date(p1.getMiddleMillisecond())); String label2 = df.format(new Date(p2.getMiddleMillisecond())); Rectangle2D b1 = TextUtilities.getTextBounds(label1, g2, g2.getFontMetrics()); Rectangle2D b2 = TextUtilities.getTextBounds(label2, g2, g2.getFontMetrics()); double w = Math.max(b1.getWidth(), b2.getWidth()); long ww = Math.round(java2DToValue(dataArea.getX() + w + 5.0, dataArea, edge)); if (isInverted()) { ww = axisMax - ww; } else { ww = ww - axisMin; } long length = p1.getLastMillisecond() - p1.getFirstMillisecond(); int periods = (int) (ww / length) + 1; RegularTimePeriod p = this.labelInfo[band].createInstance( new Date(axisMin), this.timeZone, this.locale); Rectangle2D b = null; long lastXX = 0L; float y = (float) (state.getCursor()); TextAnchor anchor = TextAnchor.TOP_CENTER; float yDelta = (float) b1.getHeight(); if (edge == RectangleEdge.TOP) { anchor = TextAnchor.BOTTOM_CENTER; yDelta = -yDelta; } while (p.getFirstMillisecond() <= axisMax) { float x = (float) valueToJava2D(p.getMiddleMillisecond(), dataArea, edge); String label = df.format(new Date(p.getMiddleMillisecond())); long first = p.getFirstMillisecond(); long last = p.getLastMillisecond(); if (last > axisMax) { // this is the last period, but it is only partially visible // so check that the label will fit before displaying it... Rectangle2D bb = TextUtilities.getTextBounds(label, g2, g2.getFontMetrics()); if ((x + bb.getWidth() / 2) > dataArea.getMaxX()) { float xstart = (float) valueToJava2D(Math.max(first, axisMin), dataArea, edge); if (bb.getWidth() < (dataArea.getMaxX() - xstart)) { x = ((float) dataArea.getMaxX() + xstart) / 2.0f; } else { label = null; } } } if (first < axisMin) { // this is the first period, but it is only partially visible // so check that the label will fit before displaying it... Rectangle2D bb = TextUtilities.getTextBounds(label, g2, g2.getFontMetrics()); if ((x - bb.getWidth() / 2) < dataArea.getX()) { float xlast = (float) valueToJava2D(Math.min(last, axisMax), dataArea, edge); if (bb.getWidth() < (xlast - dataArea.getX())) { x = (xlast + (float) dataArea.getX()) / 2.0f; } else { label = null; } } } if (label != null) { g2.setPaint(this.labelInfo[band].getLabelPaint()); b = TextUtilities.drawAlignedString(label, g2, x, y, anchor); } if (lastXX > 0L) { if (this.labelInfo[band].getDrawDividers()) { long nextXX = p.getFirstMillisecond(); long mid = (lastXX + nextXX) / 2; float mid2d = (float) valueToJava2D(mid, dataArea, edge); g2.setStroke(this.labelInfo[band].getDividerStroke()); g2.setPaint(this.labelInfo[band].getDividerPaint()); g2.draw(new Line2D.Float(mid2d, y, mid2d, y + yDelta)); } } lastXX = last; for (int i = 0; i < periods; i++) { p = p.next(); } p.peg(this.calendar); } double used = 0.0; if (b != null) { used = b.getHeight(); // work out the trailing gap if (edge == RectangleEdge.BOTTOM) { used += this.labelInfo[band].getPadding().calculateBottomOutset( fm.getHeight()); } else if (edge == RectangleEdge.TOP) { used += this.labelInfo[band].getPadding().calculateTopOutset( fm.getHeight()); } } state.moveCursor(used, edge); return state; } /** * Calculates the positions of the ticks for the axis, storing the results * in the tick list (ready for drawing). * * @param g2 the graphics device. * @param state the axis state. * @param dataArea the area inside the axes. * @param edge the edge on which the axis is located. * * @return The list of ticks. */ public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { return Collections.EMPTY_LIST; } /** * Converts a data value to a coordinate in Java2D space, assuming that the * axis runs along one edge of the specified dataArea. * <p> * Note that it is possible for the coordinate to fall outside the area. * * @param value the data value. * @param area the area for plotting the data. * @param edge the edge along which the axis lies. * * @return The Java2D coordinate. */ public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge) { double result = Double.NaN; double axisMin = this.first.getFirstMillisecond(); double axisMax = this.last.getLastMillisecond(); if (RectangleEdge.isTopOrBottom(edge)) { double minX = area.getX(); double maxX = area.getMaxX(); if (isInverted()) { result = maxX + ((value - axisMin) / (axisMax - axisMin)) * (minX - maxX); } else { result = minX + ((value - axisMin) / (axisMax - axisMin)) * (maxX - minX); } } else if (RectangleEdge.isLeftOrRight(edge)) { double minY = area.getMinY(); double maxY = area.getMaxY(); if (isInverted()) { result = minY + (((value - axisMin) / (axisMax - axisMin)) * (maxY - minY)); } else { result = maxY - (((value - axisMin) / (axisMax - axisMin)) * (maxY - minY)); } } return result; } /** * Converts a coordinate in Java2D space to the corresponding data value, * assuming that the axis runs along one edge of the specified dataArea. * * @param java2DValue the coordinate in Java2D space. * @param area the area in which the data is plotted. * @param edge the edge along which the axis lies. * * @return The data value. */ public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge) { double result; double min = 0.0; double max = 0.0; double axisMin = this.first.getFirstMillisecond(); double axisMax = this.last.getLastMillisecond(); if (RectangleEdge.isTopOrBottom(edge)) { min = area.getX(); max = area.getMaxX(); } else if (RectangleEdge.isLeftOrRight(edge)) { min = area.getMaxY(); max = area.getY(); } if (isInverted()) { result = axisMax - ((java2DValue - min) / (max - min) * (axisMax - axisMin)); } else { result = axisMin + ((java2DValue - min) / (max - min) * (axisMax - axisMin)); } return result; } /** * Rescales the axis to ensure that all data is visible. */ protected void autoAdjustRange() { Plot plot = getPlot(); if (plot == null) { return; // no plot, no data } if (plot instanceof ValueAxisPlot) { ValueAxisPlot vap = (ValueAxisPlot) plot; Range r = vap.getDataRange(this); if (r == null) { r = getDefaultAutoRange(); } long upper = Math.round(r.getUpperBound()); long lower = Math.round(r.getLowerBound()); this.first = createInstance(this.autoRangeTimePeriodClass, new Date(lower), this.timeZone, this.locale); this.last = createInstance(this.autoRangeTimePeriodClass, new Date(upper), this.timeZone, this.locale); setRange(r, false, false); } } /** * Tests the axis for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof PeriodAxis)) { return false; } PeriodAxis that = (PeriodAxis) obj; if (!this.first.equals(that.first)) { return false; } if (!this.last.equals(that.last)) { return false; } if (!this.timeZone.equals(that.timeZone)) { return false; } if (!this.locale.equals(that.locale)) { return false; } if (!this.autoRangeTimePeriodClass.equals( that.autoRangeTimePeriodClass)) { return false; } if (!(isMinorTickMarksVisible() == that.isMinorTickMarksVisible())) { return false; } if (!this.majorTickTimePeriodClass.equals( that.majorTickTimePeriodClass)) { return false; } if (!this.minorTickTimePeriodClass.equals( that.minorTickTimePeriodClass)) { return false; } if (!this.minorTickMarkPaint.equals(that.minorTickMarkPaint)) { return false; } if (!this.minorTickMarkStroke.equals(that.minorTickMarkStroke)) { return false; } if (!Arrays.equals(this.labelInfo, that.labelInfo)) { return false; } return super.equals(obj); } /** * Returns a hash code for this object. * * @return A hash code. */ public int hashCode() { if (getLabel() != null) { return getLabel().hashCode(); } else { return 0; } } /** * Returns a clone of the axis. * * @return A clone. * * @throws CloneNotSupportedException this class is cloneable, but * subclasses may not be. */ public Object clone() throws CloneNotSupportedException { PeriodAxis clone = (PeriodAxis) super.clone(); clone.timeZone = (TimeZone) this.timeZone.clone(); clone.labelInfo = (PeriodAxisLabelInfo[]) this.labelInfo.clone(); return clone; } /** * A utility method used to create a particular subclass of the * {@link RegularTimePeriod} class that includes the specified millisecond, * assuming the specified time zone. * * @param periodClass the class. * @param millisecond the time. * @param zone the time zone. * @param locale the locale. * * @return The time period. */ private RegularTimePeriod createInstance(Class periodClass, Date millisecond, TimeZone zone, Locale locale) { RegularTimePeriod result = null; try { Constructor c = periodClass.getDeclaredConstructor(new Class[] { Date.class, TimeZone.class, Locale.class}); result = (RegularTimePeriod) c.newInstance(new Object[] { millisecond, zone, locale}); } catch (Exception e) { try { Constructor c = periodClass.getDeclaredConstructor(new Class[] { Date.class}); result = (RegularTimePeriod) c.newInstance(new Object[] { millisecond}); } catch (Exception e2) { // do nothing } } return result; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.minorTickMarkStroke, stream); SerialUtilities.writePaint(this.minorTickMarkPaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.minorTickMarkStroke = SerialUtilities.readStroke(stream); this.minorTickMarkPaint = SerialUtilities.readPaint(stream); } }
package testsuite.manager; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.WriterAppender; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; import testsuite.bean.Beanable; import testsuite.group.Group; import testsuite.result.ResultsCollections; import testsuite.result.ResultsExporter; import testsuite.test.AbstractTest; import testsuite.xml.ManagerDescriptorHandler; import testsuite.xslt.TransformerXSLT; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Calendar; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; /** * @author Alexandre di Costanzo * */ public abstract class AbstractManager implements ResultsExporter, Beanable, AbstractManagerConstants { private String name = "AbstractManager with no name"; private String description = "AbstractManager with no description."; private ArrayList groups = new ArrayList(); protected static Logger logger = Logger.getLogger(AbstractManager.class); private int nbRuns = 1; private ResultsCollections results = new ResultsCollections(); private Properties properties = null; protected ArrayList interLinkedGroups = null; private int resultType = 0; private String outputPath = null; public AbstractManager() { // logger = Logger.getLogger(getClass().getName()); testAppender(); } public AbstractManager(String name, String description) { this.name = name; this.description = description; logger = Logger.getLogger(getClass().getName()); testAppender(); } public AbstractManager(File xmlDescriptor) throws IOException, SAXException { // logger = Logger.getLogger(getClass().getName()); testAppender(); ManagerDescriptorHandler.createManagerDescriptor(xmlDescriptor.getPath(), this); } private void testAppender() { int nbAppenders = 0; Enumeration enum = Logger.getRootLogger().getAllAppenders(); while (enum.hasMoreElements()) { nbAppenders++; enum.nextElement(); } if (nbAppenders == 0) { File log = new File(System.getProperty("user.home") + File.separatorChar + "tests.log"); FileOutputStream out = null; try { out = new FileOutputStream(log); } catch (FileNotFoundException e) { System.out.println("XXXXXXXXXXXXXXXXXXXXX"); logger.warn("Log file not found", e); } Logger.getRootLogger().addAppender(new WriterAppender( new PatternLayout("%d [%t] %-5p %c %x - %m%n"), out)); Logger.getRootLogger().setLevel((Level) Level.INFO); } } public abstract void initManager() throws Exception; public void execute() { this.execute(false); } public abstract void execute(boolean useAttributesFile); public abstract void endManager() throws Exception; /** * @return */ public String getDescription() { return description; } /** * @return */ public String getName() { return name; } /** * @param string */ public void setDescription(String string) { description = string; } /** * @param string */ public void setName(String string) { name = string; } /** * @see java.util.Collection#add(java.lang.Object) */ public boolean add(Group o) { return groups.add(o); } /** * @see java.util.Collection#clear() */ public void clear() { groups.clear(); } /** * @see java.util.Collection#contains(java.lang.Object) */ public boolean contains(Group o) { return groups.contains(o); } /** * @see java.util.Collection#isEmpty() */ public boolean isEmpty() { return groups.isEmpty(); } /** * @see java.util.Collection#iterator() */ public Iterator iterator() { return groups.iterator(); } /** * @see java.util.Collection#remove(java.lang.Object) */ public boolean remove(Group o) { return groups.remove(o); } /** * @see java.util.Collection#size() */ public int size() { return groups.size(); } /** * @see java.util.Collection#toArray() */ public Group[] toArray() { return (Group[]) groups.toArray(new Group[groups.size()]); } /** * @return */ public Logger getLogger() { return logger; } /** * @return */ public int getNbRuns() { return nbRuns; } /** * @param i */ public void setNbRuns(int i) { nbRuns = i; if (logger.isDebugEnabled()) { logger.debug("Nb runs change in " + nbRuns); } } public void setNbRuns(String i) { this.nbRuns = Integer.parseInt(i); if (logger.isDebugEnabled()) { logger.debug("Nb runs change in " + this.nbRuns); } } /** * @return */ public ArrayList getGroups() { return groups; } /** * @param groups */ public void setGroups(ArrayList groups) { this.groups = groups; } /** * @return */ public ResultsCollections getResults() { return results; } /** * @see testsuite.result.ResultsExporter#toHTML(java.io.File) */ public void toHTML(File location) throws ParserConfigurationException, TransformerException, IOException { if (logger.isInfoEnabled()) { logger.info("Create HMTL file ..."); } String xslPath = "/" + AbstractManager.class.getName().replace('.', '/').replaceAll("manager.*", "/xslt/manager.xsl"); TransformerXSLT.transformerTo(toXML(), location, xslPath); // copy css String cssPath = "/" + AbstractManager.class.getName().replace('.', '/').replaceAll("manager.*", "/css/stylesheet.css"); InputStream css = getClass().getResourceAsStream(cssPath); File copy = new File(location.getParent() + File.separator + "stylesheet.css"); FileOutputStream out = new FileOutputStream(copy); byte[] buffer = new byte[1024]; int nbBytes = 0; while (nbBytes != -1) { nbBytes = css.read(buffer); if (nbBytes > 0) { out.write(buffer, 0, nbBytes); } } css.close(); out.close(); if (logger.isInfoEnabled()) { logger.info("... Finish creating HTML file"); } } /** * @see testsuite.result.ResultsExporter#toOutPutStream(java.io.OutputStream) */ public void toOutPutStream(OutputStream out) throws IOException { out.write(toString().getBytes()); } /** * @see testsuite.result.ResultsExporter#toPrintWriter(java.io.PrintWriter) */ public void toPrintWriter(PrintWriter out) { out.println(toString()); } /** * @see testsuite.result.ResultsExporter#toXML() */ public Document toXML() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Node root = document.createElement("Manager"); Node nameNode = document.createElement("Name"); Node nameNodeText = document.createTextNode(this.name); nameNode.appendChild(nameNodeText); root.appendChild(nameNode); Node descriptionNode = document.createElement("Description"); Node descriptionNodeText = document.createTextNode(this.description); descriptionNode.appendChild(descriptionNodeText); root.appendChild(descriptionNode); Node date = time(document); root.appendChild(date); Node runs = document.createElement("NbRuns"); Node runsText = document.createTextNode(nbRuns + ""); runs.appendChild(runsText); root.appendChild(runs); Node groups = document.createElement("Groups"); Iterator itGroup = iterator(); while (itGroup.hasNext()) { Group group = (Group) itGroup.next(); Node groupNode = document.createElement("Group"); Node groupName = document.createElement("Name"); Node groupNameText = document.createTextNode(group.getName()); groupName.appendChild(groupNameText); groupNode.appendChild(groupName); Node groupDescription = document.createElement("Description"); Node groupDescriptionText = document.createTextNode(group.getDescription()); groupDescription.appendChild(groupDescriptionText); groupNode.appendChild(groupDescription); Node groupResults = document.importNode(group.getResults().toXML() .getFirstChild(), true); groupNode.appendChild(groupResults); groups.appendChild(groupNode); } root.appendChild(groups); Node allMessages = document.createElement("AllMessages"); Node resultsNode = document.importNode(results.toXML().getFirstChild(), true); allMessages.appendChild(resultsNode); root.appendChild(allMessages); document.appendChild(root); return document; } private Node time(Document document) { Calendar date = Calendar.getInstance(); Element root = document.createElement("Date"); root.setAttribute("day", date.get(Calendar.DATE) + ""); root.setAttribute("month", date.get(Calendar.MONTH) + ""); root.setAttribute("year", date.get(Calendar.YEAR) + ""); Element time = document.createElement("Time"); time.setAttribute("hour", date.get(Calendar.HOUR_OF_DAY) + ""); time.setAttribute("minute", date.get(Calendar.MINUTE) + ""); time.setAttribute("second", date.get(Calendar.SECOND) + ""); time.setAttribute("millisecond", date.get(Calendar.MILLISECOND) + ""); root.appendChild(time); return root; } /** * @see testsuite.result.ResultsExporter#toString() */ public String toString() { return results.toString(); } public void setVerbatim(boolean verbatim) { results.setVerbatim(verbatim); } public boolean isVerbatim() { return results.isVerbatim(); } /** * @see testsuite.bean.Beanable#loadAttributes() */ public void loadAttributes() throws IOException { String filename = getClass() .getResource("/" + getClass().getName().replace('.', '/') + ".class").getPath(); filename = filename.replaceAll("\\.class", ".prop"); loadAttributes(new File(filename.replaceAll("%20", " "))); } /** * @see testsuite.bean.Beanable#loadAttributes(java.io.File) */ public void loadAttributes(File propsFile) throws IOException { Properties props = new Properties(); FileInputStream in = new FileInputStream(propsFile); props.load(in); in.close(); loadAttributes(props); } /** * @see testsuite.bean.Beanable#loadAttributes(java.util.Properties) */ public void loadAttributes(Properties properties) { if (properties != null) { this.properties = properties; Class[] parameterTypes = { String.class }; Enumeration enum = properties.propertyNames(); Method setter = null; while (enum.hasMoreElements()) { String name = (String) enum.nextElement(); String value = properties.getProperty(name); try { setter = getClass().getMethod("set" + name, parameterTypes); Object[] args = { value }; try { setter.invoke(this, args); if (logger.isDebugEnabled()) { logger.debug("set " + name + " with " + value); } } catch (IllegalArgumentException e1) { if (logger.isDebugEnabled()) { logger.debug(e1); } } catch (IllegalAccessException e1) { if (logger.isDebugEnabled()) { logger.debug(e1); } } catch (InvocationTargetException e1) { if (logger.isDebugEnabled()) { logger.debug(e1); } } } catch (SecurityException e) { // do nothing } catch (NoSuchMethodException e) { // do nothing } } for (int i = 0; i < groups.size(); i++) { Group group = (Group) groups.get(0); Iterator it = group.iterator(); while (it.hasNext()) { AbstractTest test = (AbstractTest) it.next(); test.loadAttributes(properties); } } if (logger.isInfoEnabled()) { logger.info("Test Suite's attributes readed"); } } } protected void showResult() { if (this.getResultType() != 0) { switch (this.getResultType()) { case AbstractManager.HTML: try { this.toHTML(new File(this.getOutputPath())); } catch (ParserConfigurationException e) { logger.warn("Parser Configuration error", e); } catch (TransformerException e) { logger.warn("Transformer error", e); } catch (IOException e) { logger.warn("IO error", e); } break; case AbstractManager.TEXT: try { this.toOutPutStream(new FileOutputStream( this.getOutputPath())); } catch (FileNotFoundException e) { logger.warn("File " + this.getOutputPath() + " not found", e); } catch (IOException e) { logger.warn("IO error", e); } break; case AbstractManager.CONSOLE: try { this.toOutPutStream(System.out); } catch (IOException e) { logger.warn("Can't write results in the console", e); } break; case AbstractManager.XML: try { Document document = this.toXML(); String xslPath = "/" + AbstractManager.class.getName().replace('.', '/') .replaceAll("manager.*", "/xslt/xmlExport.xsl"); TransformerXSLT.transformerTo(document, new File(this.getOutputPath()), xslPath); } catch (ParserConfigurationException e) { logger.warn("Parser Configuration error", e); } catch (TransformerException e) { logger.warn("Transformer error", e); } catch (IOException e) { logger.warn("IO error", e); } break; } } } /** * @return */ public Properties getProperties() { return properties; } /** * @param properties */ public void setProperties(Properties properties) { this.properties = properties; } public void loggerConfigure(String path) { PropertyConfigurator.configure(path); } /** * @return */ public int getResultType() { return resultType; } /** * @param i */ public void setResultType(int i) { resultType = i; } /** * @return */ public String getOutputPath() { return outputPath; } /** * @param string */ public void setOutputPath(String string) { outputPath = string; } }
package som.compiler; import static som.compiler.Symbol.And; import static som.compiler.Symbol.Assign; import static som.compiler.Symbol.At; import static som.compiler.Symbol.BeginComment; import static som.compiler.Symbol.Colon; import static som.compiler.Symbol.Comma; import static som.compiler.Symbol.Div; import static som.compiler.Symbol.Double; import static som.compiler.Symbol.EndBlock; import static som.compiler.Symbol.EndComment; import static som.compiler.Symbol.EndTerm; import static som.compiler.Symbol.Equal; import static som.compiler.Symbol.Exit; import static som.compiler.Symbol.Identifier; import static som.compiler.Symbol.Integer; import static som.compiler.Symbol.Keyword; import static som.compiler.Symbol.KeywordSequence; import static som.compiler.Symbol.Less; import static som.compiler.Symbol.Minus; import static som.compiler.Symbol.Mod; import static som.compiler.Symbol.More; import static som.compiler.Symbol.NONE; import static som.compiler.Symbol.NewBlock; import static som.compiler.Symbol.NewTerm; import static som.compiler.Symbol.Not; import static som.compiler.Symbol.OperatorSequence; import static som.compiler.Symbol.Or; import static som.compiler.Symbol.Per; import static som.compiler.Symbol.Period; import static som.compiler.Symbol.Plus; import static som.compiler.Symbol.Pound; import static som.compiler.Symbol.STString; import static som.compiler.Symbol.Star; import static som.interpreter.SNodeFactory.createGlobalRead; import static som.interpreter.SNodeFactory.createMessageSend; import static som.interpreter.SNodeFactory.createSequence; import static som.vm.Symbols.symbolFor; import java.io.Reader; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import som.compiler.Lexer.Peek; import som.compiler.Lexer.SourceCoordinate; import som.compiler.Variable.Local; import som.interpreter.SNodeFactory; import som.interpreter.nodes.ExpressionNode; import som.interpreter.nodes.MessageSendNode.AbstractMessageSendNode; import som.interpreter.nodes.literals.BigIntegerLiteralNode; import som.interpreter.nodes.literals.BlockNode; import som.interpreter.nodes.literals.BlockNode.BlockNodeWithContext; import som.interpreter.nodes.literals.DoubleLiteralNode; import som.interpreter.nodes.literals.IntegerLiteralNode; import som.interpreter.nodes.literals.LiteralNode; import som.interpreter.nodes.literals.StringLiteralNode; import som.interpreter.nodes.literals.SymbolLiteralNode; import som.interpreter.nodes.specialized.BooleanInlinedLiteralNode.AndInlinedLiteralNode; import som.interpreter.nodes.specialized.BooleanInlinedLiteralNode.OrInlinedLiteralNode; import som.interpreter.nodes.specialized.IfInlinedLiteralNode; import som.interpreter.nodes.specialized.IfTrueIfFalseInlinedLiteralsNode; import som.interpreter.nodes.specialized.IntToDoInlinedLiteralsNodeGen; import som.interpreter.nodes.specialized.whileloops.WhileInlinedLiteralsNode; import som.vm.NotYetImplementedException; import som.vm.Universe; import som.vmobjects.SInvokable.SMethod; import som.vmobjects.SSymbol; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; public final class Parser { private final Universe universe; private final Lexer lexer; private final Source source; private Symbol sym; private String text; private Symbol nextSym; private String nextText; private SourceSection lastMethodsSourceSection; private static final List<Symbol> singleOpSyms = new ArrayList<Symbol>(); private static final List<Symbol> binaryOpSyms = new ArrayList<Symbol>(); private static final List<Symbol> keywordSelectorSyms = new ArrayList<Symbol>(); static { for (Symbol s : new Symbol[] {Not, And, Or, Star, Div, Mod, Plus, Equal, More, Less, Comma, At, Per, NONE}) { singleOpSyms.add(s); } for (Symbol s : new Symbol[] {Or, Comma, Minus, Equal, Not, And, Or, Star, Div, Mod, Plus, Equal, More, Less, Comma, At, Per, NONE}) { binaryOpSyms.add(s); } for (Symbol s : new Symbol[] {Keyword, KeywordSequence}) { keywordSelectorSyms.add(s); } } @Override public String toString() { return "Parser(" + source.getName() + ", " + this.getCoordinate().toString() + ")"; } public static class ParseError extends Exception { private static final long serialVersionUID = 425390202979033628L; private final String message; private final SourceCoordinate sourceCoordinate; private final String text; private final String rawBuffer; private final String fileName; private final Symbol expected; private final Symbol found; ParseError(final String message, final Symbol expected, final Parser parser) { this.message = message; this.sourceCoordinate = parser.getCoordinate(); this.text = parser.text; this.rawBuffer = parser.lexer.getRawBuffer(); this.fileName = parser.source.getName(); this.expected = expected; this.found = parser.sym; } protected String expectedSymbolAsString() { return expected.toString(); } @Override public String toString() { String msg = "%(file)s:%(line)d:%(column)d: error: " + message; String foundStr; if (Parser.printableSymbol(found)) { foundStr = found + " (" + text + ")"; } else { foundStr = found.toString(); } msg += ": " + rawBuffer; String expectedStr = expectedSymbolAsString(); msg = msg.replace("%(file)s", fileName); msg = msg.replace("%(line)d", java.lang.Integer.toString(sourceCoordinate.startLine)); msg = msg.replace("%(column)d", java.lang.Integer.toString(sourceCoordinate.startColumn)); msg = msg.replace("%(expected)s", expectedStr); msg = msg.replace("%(found)s", foundStr); return msg; } } public static class ParseErrorWithSymbolList extends ParseError { private static final long serialVersionUID = 561313162441723955L; private final List<Symbol> expectedSymbols; ParseErrorWithSymbolList(final String message, final List<Symbol> expected, final Parser parser) { super(message, null, parser); this.expectedSymbols = expected; } @Override protected String expectedSymbolAsString() { StringBuilder sb = new StringBuilder(); String deliminator = ""; for (Symbol s : expectedSymbols) { sb.append(deliminator); sb.append(s); deliminator = ", "; } return sb.toString(); } } public Parser(final Reader reader, final long fileSize, final Source source, final Universe universe) { this.universe = universe; this.source = source; sym = NONE; lexer = new Lexer(reader, fileSize); nextSym = NONE; getSymbolFromLexer(); } private SourceCoordinate getCoordinate() { return lexer.getStartCoordinate(); } public void moduleDeclaration(final ClassBuilder clsBuilder) throws ParseError { comment(); classDeclaration(AccessModifier.PUBLIC, clsBuilder); } private void classDeclaration(final AccessModifier accessModifier, final ClassBuilder clsBuilder) throws ParseError { expectIdentifier("class"); String className = text; expect(Identifier); clsBuilder.setName(symbolFor(className)); MethodBuilder primaryFactory = clsBuilder.getInitializerMethodBuilder(); // Newspeak-spec: this is not strictly sufficient for Newspeak // it could also parse a binary selector here, I think // but, doesn't seem so useful, so, let's keep it simple if (isIdentifier(sym) || sym == Keyword) { messagePattern(primaryFactory); } expect(Equal); inheritanceListAndOrBody(clsBuilder); } private void inheritanceListAndOrBody(final ClassBuilder clsBuilder) throws ParseError { if (sym == NewTerm) { defaultSuperclassAndBody(clsBuilder); } else { explicitInheritanceListAndOrBody(clsBuilder); } } private void defaultSuperclassAndBody(final ClassBuilder clsBuilder) throws ParseError { MethodBuilder def = clsBuilder.getInstantiationMethodBuilder(); ExpressionNode selfRead = def.getReadNode("self", null); AbstractMessageSendNode superClass = SNodeFactory.createMessageSend( symbolFor("Object"), new ExpressionNode[] {selfRead}, null); clsBuilder.setSuperClassResolution(superClass); classBody(clsBuilder); } private void explicitInheritanceListAndOrBody(final ClassBuilder clsBuilder) { throw new NotYetImplementedException(); } private void classBody(final ClassBuilder clsBuilder) throws ParseError { classHeader(clsBuilder); sideDeclaration(clsBuilder); if (sym == Colon) { classSideDecl(clsBuilder); } } private void classSideDecl(final ClassBuilder clsBuilder) throws ParseError { clsBuilder.switchToClassSide(); expect(Colon); expect(NewTerm); category(clsBuilder); expect(EndTerm); } private void classHeader(final ClassBuilder clsBuilder) throws ParseError { expect(NewTerm); classComment(clsBuilder); if (sym == Or) { slotDeclarations(clsBuilder); } if (sym != EndTerm) { initExprs(clsBuilder); } expect(EndTerm); } private void classComment(final ClassBuilder clsBuilder) throws ParseError { // TODO: capture comment and add it to class comment(); } private void comment() throws ParseError { if (sym != BeginComment) { return; } expect(BeginComment); while (sym != EndComment) { if (sym == BeginComment) { comment(); } else { getSymbolFromLexer(); } } expect(EndComment); } private void slotDeclarations(final ClassBuilder clsBuilder) throws ParseError { // Newspeak-speak: we do not support simSlotDecls, i.e., // simultaneous slots clauses (spec 6.3.2) expect(Or); while (sym != Or) { slotDefinition(clsBuilder); } expect(Or); } private void slotDefinition(final ClassBuilder clsBuilder) throws ParseError { AccessModifier acccessModifier = accessModifier(); String slotName = slotDecl(); boolean immutable; if (accept(Equal)) { immutable = true; } else { immutable = false; // TODO: need to parse tokenFromSymbol: throw new NotYetImplementedException(); } ExpressionNode init = expression(clsBuilder.getInitializerMethodBuilder()); clsBuilder.addSlot(symbolFor(slotName), acccessModifier, immutable, init); expect(Period); } private AccessModifier accessModifier() { if (sym == Identifier) { if (acceptIdentifier("private")) { return AccessModifier.PRIVATE; } if (acceptIdentifier("protected")) { return AccessModifier.PROTECTED; } if (acceptIdentifier("public")) { return AccessModifier.PUBLIC; } } return AccessModifier.PROTECTED; } private String slotDecl() throws ParseError { return identifier(); } private void initExprs(final ClassBuilder clsBuilder) throws ParseError { MethodBuilder initializer = clsBuilder.getInitializerMethodBuilder(); clsBuilder.addInitializerExpression(expression(initializer)); while (accept(Period)) { if (sym != EndTerm) { clsBuilder.addInitializerExpression(expression(initializer)); } } } private void sideDeclaration(final ClassBuilder clsBuilder) throws ParseError { expect(NewTerm); while (canAcceptThisOrNextIdentifier("class")) { nestedClassDeclaration(clsBuilder); } while (sym != EndTerm) { category(clsBuilder); } expect(EndTerm); } private void nestedClassDeclaration(final ClassBuilder clsBuilder) throws ParseError { AccessModifier accessModifier = accessModifier(); ClassBuilder nestedCls = new ClassBuilder(); classDeclaration(accessModifier, nestedCls); } private void category(final ClassBuilder clsBuilder) throws ParseError { String categoryName; // Newspeak-spec: this is not conform with Newspeak, // as the category is normally not optional if (sym == STString) { categoryName = string(); } else { categoryName = ""; } while (sym != EndTerm && sym != STString) { comment(); methodDeclaration(clsBuilder, symbolFor(categoryName)); comment(); } } // expect(NewTerm); // while (isIdentifier(sym) || sym == Keyword || sym == OperatorSequence // || symIn(binaryOpSyms)) { // MethodGenerationContext builder = new MethodGenerationContext(clsBuilder); // ExpressionNode methodBody = method(builder); // clsBuilder.addInstanceMethod(builder.assemble(methodBody, lastMethodsSourceSection)); // //TODO: cleanup // //if (accept(Separator)) { // clsBuilder.setClassSide(true); // classFields(clsBuilder); // while (isIdentifier(sym) || sym == Keyword || sym == OperatorSequence // || symIn(binaryOpSyms)) { // MethodGenerationContext builder = new MethodGenerationContext(clsBuilder); // ExpressionNode methodBody = method(builder); // clsBuilder.addClassMethod(builder.assemble(methodBody, lastMethodsSourceSection)); // expect(EndTerm); private boolean symIn(final List<Symbol> ss) { return ss.contains(sym); } private boolean canAcceptThisOrNextIdentifier(final String identifier) { if (sym == Identifier && identifier.equals(text)) { return true; } peekForNextSymbolFromLexer(); return nextSym == Identifier && identifier.equals(nextText); } private boolean acceptIdentifier(final String identifier) { if (sym == Identifier && identifier.equals(text)) { accept(Identifier); return true; } return false; } private boolean accept(final Symbol s) { if (sym == s) { getSymbolFromLexer(); return true; } return false; } private boolean acceptOneOf(final List<Symbol> ss) { if (symIn(ss)) { getSymbolFromLexer(); return true; } return false; } private boolean expectIdentifier(final String identifier) throws ParseError { if (acceptIdentifier(identifier)) { return true; } throw new ParseError("Unexpected token. Expected '" + identifier + "', but found %(found)s", Identifier, this); } private void expect(final Symbol s) throws ParseError { if (accept(s)) { return; } throw new ParseError("Unexpected symbol. Expected %(expected)s, but found " + "%(found)s", s, this); } private boolean expectOneOf(final List<Symbol> ss) throws ParseError { if (acceptOneOf(ss)) { return true; } throw new ParseErrorWithSymbolList("Unexpected symbol. Expected one of " + "%(expected)s, but found %(found)s", ss, this); } private SourceSection getSource(final SourceCoordinate coord) { assert lexer.getNumberOfCharactersRead() - coord.charIndex >= 0; return source.createSection("method", coord.startLine, coord.startColumn, coord.charIndex, lexer.getNumberOfCharactersRead() - coord.charIndex); } private void methodDeclaration(final ClassBuilder clsBuilder, final SSymbol category) throws ParseError { SourceCoordinate coord = getCoordinate(); AccessModifier accessModifier = accessModifier(); MethodBuilder builder = new MethodBuilder(clsBuilder); messagePattern(builder); expect(Equal); ExpressionNode body = methodBlock(builder); SMethod meth = builder.assemble(body, accessModifier, category, getSource(coord)); clsBuilder.addMethod(meth); } private void messagePattern(final MethodBuilder builder) throws ParseError { builder.addArgumentIfAbsent("self"); switch (sym) { case Identifier: unaryPattern(builder); break; case Keyword: keywordPattern(builder); break; default: binaryPattern(builder); break; } } private void unaryPattern(final MethodBuilder builder) throws ParseError { builder.setSignature(unarySelector()); } private void binaryPattern(final MethodBuilder builder) throws ParseError { builder.setSignature(binarySelector()); builder.addArgumentIfAbsent(argument()); } private void keywordPattern(final MethodBuilder builder) throws ParseError { StringBuffer kw = new StringBuffer(); do { kw.append(keyword()); builder.addArgumentIfAbsent(argument()); } while (sym == Keyword); builder.setSignature(symbolFor(kw.toString())); } private ExpressionNode methodBlock(final MethodBuilder builder) throws ParseError { expect(NewTerm); SourceCoordinate coord = getCoordinate(); ExpressionNode methodBody = blockContents(builder); lastMethodsSourceSection = getSource(coord); expect(EndTerm); return methodBody; } private SSymbol unarySelector() throws ParseError { return symbolFor(identifier()); } private SSymbol binarySelector() throws ParseError { String s = new String(text); // Checkstyle: stop if (accept(Or)) { } else if (accept(Comma)) { } else if (accept(Minus)) { } else if (accept(Equal)) { } else if (acceptOneOf(singleOpSyms)) { } else if (accept(OperatorSequence)) { } else { throw new ParseError("Unexpected symbol. Expected binary operator, " + "but found %(found)s", Symbol.NONE, this); } // Checkstyle: resume return symbolFor(s); } private String identifier() throws ParseError { String s = new String(text); expect(Identifier); return s; } private String keyword() throws ParseError { String s = new String(text); expect(Keyword); return s; } private String argument() throws ParseError { return identifier(); } private ExpressionNode blockContents(final MethodBuilder builder) throws ParseError { if (accept(Or)) { locals(builder); expect(Or); } return blockBody(builder); } private void locals(final MethodBuilder builder) throws ParseError { while (isIdentifier(sym)) { builder.addLocalIfAbsent(identifier()); } } private ExpressionNode blockBody(final MethodBuilder builder) throws ParseError { SourceCoordinate coord = getCoordinate(); List<ExpressionNode> expressions = new ArrayList<ExpressionNode>(); while (true) { if (accept(Exit)) { expressions.add(result(builder)); return createSequenceNode(coord, expressions); } else if (sym == EndBlock) { return createSequenceNode(coord, expressions); } else if (sym == EndTerm) { // the end of the method has been found (EndTerm) - make it implicitly // return "self" // TODO: we might need something else to access self ExpressionNode self = implicitReceiverSend(builder, symbolFor("self"), getSource(getCoordinate())); expressions.add(self); return createSequenceNode(coord, expressions); } expressions.add(expression(builder)); accept(Period); } } private ExpressionNode createSequenceNode(final SourceCoordinate coord, final List<ExpressionNode> expressions) { if (expressions.size() == 0) { return createGlobalRead("nil", universe, getSource(coord)); } else if (expressions.size() == 1) { return expressions.get(0); } return createSequence(expressions, getSource(coord)); } private ExpressionNode result(final MethodBuilder builder) throws ParseError { SourceCoordinate coord = getCoordinate(); ExpressionNode exp = expression(builder); accept(Period); if (builder.isBlockMethod()) { return builder.getNonLocalReturn(exp, getSource(coord)); } else { return exp; } } private ExpressionNode expression(final MethodBuilder builder) throws ParseError { peekForNextSymbolFromLexer(); if (nextSym == Assign) { return assignation(builder); } else { return evaluation(builder); } } private ExpressionNode assignation(final MethodBuilder builder) throws ParseError { return assignments(builder); } private ExpressionNode assignments(final MethodBuilder builder) throws ParseError { SourceCoordinate coord = getCoordinate(); if (!isIdentifier(sym)) { throw new ParseError("Assignments should always target variables or" + " fields, but found instead a %(found)s", Symbol.Identifier, this); } SSymbol identifier = assignment(); peekForNextSymbolFromLexer(); ExpressionNode value; if (nextSym == Assign) { value = assignments(builder); } else { value = evaluation(builder); } return setterSend(builder, identifier, value, getSource(coord)); } private SSymbol assignment() throws ParseError { SSymbol id = symbolFor(identifier()); expect(Assign); return id; } private ExpressionNode evaluation(final MethodBuilder builder) throws ParseError { ExpressionNode exp = primary(builder); if (isIdentifier(sym) || sym == Keyword || sym == OperatorSequence || symIn(binaryOpSyms)) { exp = messages(builder, exp); } return exp; } private ExpressionNode primary(final MethodBuilder builder) throws ParseError { switch (sym) { case Identifier: { SourceCoordinate coord = getCoordinate(); SSymbol selector = unarySelector(); return implicitReceiverSend(builder, selector, getSource(coord)); } case NewTerm: { return nestedTerm(builder); } case NewBlock: { SourceCoordinate coord = getCoordinate(); MethodBuilder bgenc = new MethodBuilder(builder.getHolder(), builder); ExpressionNode blockBody = nestedBlock(bgenc); SMethod blockMethod = bgenc.assemble(blockBody, AccessModifier.NOT_APPLICABLE, null, lastMethodsSourceSection); builder.addEmbeddedBlockMethod(blockMethod); if (bgenc.requiresContext()) { return new BlockNodeWithContext(blockMethod, getSource(coord)); } else { return new BlockNode(blockMethod, getSource(coord)); } } default: { return literal(); } } } private ExpressionNode messages(final MethodBuilder builder, final ExpressionNode receiver) throws ParseError { ExpressionNode msg; if (isIdentifier(sym)) { msg = unaryMessage(receiver); while (isIdentifier(sym)) { msg = unaryMessage(msg); } while (sym == OperatorSequence || symIn(binaryOpSyms)) { msg = binaryMessage(builder, msg); } if (sym == Keyword) { msg = keywordMessage(builder, msg); } } else if (sym == OperatorSequence || symIn(binaryOpSyms)) { msg = binaryMessage(builder, receiver); while (sym == OperatorSequence || symIn(binaryOpSyms)) { msg = binaryMessage(builder, msg); } if (sym == Keyword) { msg = keywordMessage(builder, msg); } } else { msg = keywordMessage(builder, receiver); } return msg; } private AbstractMessageSendNode unaryMessage(final ExpressionNode receiver) throws ParseError { SourceCoordinate coord = getCoordinate(); SSymbol selector = unarySelector(); return createMessageSend(selector, new ExpressionNode[] {receiver}, getSource(coord)); } private AbstractMessageSendNode binaryMessage(final MethodBuilder builder, final ExpressionNode receiver) throws ParseError { SourceCoordinate coord = getCoordinate(); SSymbol msg = binarySelector(); ExpressionNode operand = binaryOperand(builder); return createMessageSend(msg, new ExpressionNode[] {receiver, operand}, getSource(coord)); } private ExpressionNode binaryOperand(final MethodBuilder builder) throws ParseError { ExpressionNode operand = primary(builder); // a binary operand can receive unaryMessages // Example: 2 * 3 asString // is evaluated as 2 * (3 asString) while (isIdentifier(sym)) { operand = unaryMessage(operand); } return operand; } private ExpressionNode keywordMessage(final MethodBuilder builder, final ExpressionNode receiver) throws ParseError { SourceCoordinate coord = getCoordinate(); List<ExpressionNode> arguments = new ArrayList<ExpressionNode>(); StringBuffer kw = new StringBuffer(); arguments.add(receiver); do { kw.append(keyword()); arguments.add(formula(builder)); } while (sym == Keyword); String msgStr = kw.toString(); SSymbol msg = symbolFor(msgStr); SourceSection source = getSource(coord); if (msg.getNumberOfSignatureArguments() == 2) { if (arguments.get(1) instanceof LiteralNode) { if ("ifTrue:".equals(msgStr)) { ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); return new IfInlinedLiteralNode(arguments.get(0), true, inlinedBody, arguments.get(1), source); } else if ("ifFalse:".equals(msgStr)) { ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); return new IfInlinedLiteralNode(arguments.get(0), false, inlinedBody, arguments.get(1), source); } else if ("whileTrue:".equals(msgStr)) { ExpressionNode inlinedCondition = ((LiteralNode) arguments.get(0)).inline(builder); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); return new WhileInlinedLiteralsNode(inlinedCondition, inlinedBody, true, arguments.get(0), arguments.get(1), source); } else if ("whileFalse:".equals(msgStr)) { ExpressionNode inlinedCondition = ((LiteralNode) arguments.get(0)).inline(builder); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(1)).inline(builder); return new WhileInlinedLiteralsNode(inlinedCondition, inlinedBody, false, arguments.get(0), arguments.get(1), source); } else if ("or:".equals(msgStr) || "||".equals(msgStr)) { ExpressionNode inlinedArg = ((LiteralNode) arguments.get(1)).inline(builder); return new OrInlinedLiteralNode(arguments.get(0), inlinedArg, arguments.get(1), source); } else if ("and:".equals(msgStr) || "&&".equals(msgStr)) { ExpressionNode inlinedArg = ((LiteralNode) arguments.get(1)).inline(builder); return new AndInlinedLiteralNode(arguments.get(0), inlinedArg, arguments.get(1), source); } } } else if (msg.getNumberOfSignatureArguments() == 3) { if ("ifTrue:ifFalse:".equals(msgStr) && arguments.get(1) instanceof LiteralNode && arguments.get(2) instanceof LiteralNode) { ExpressionNode inlinedTrueNode = ((LiteralNode) arguments.get(1)).inline(builder); ExpressionNode inlinedFalseNode = ((LiteralNode) arguments.get(2)).inline(builder); return new IfTrueIfFalseInlinedLiteralsNode(arguments.get(0), inlinedTrueNode, inlinedFalseNode, arguments.get(1), arguments.get(2), source); } else if ("to:do:".equals(msgStr) && arguments.get(2) instanceof LiteralNode) { Local loopIdx = builder.addLocal("i:" + source.getCharIndex()); ExpressionNode inlinedBody = ((LiteralNode) arguments.get(2)).inline(builder, loopIdx); return IntToDoInlinedLiteralsNodeGen.create(inlinedBody, loopIdx.getSlot(), arguments.get(2), source, arguments.get(0), arguments.get(1)); } } return createMessageSend(msg, arguments.toArray(new ExpressionNode[0]), source); } private ExpressionNode formula(final MethodBuilder builder) throws ParseError { ExpressionNode operand = binaryOperand(builder); while (sym == OperatorSequence || symIn(binaryOpSyms)) { operand = binaryMessage(builder, operand); } return operand; } private ExpressionNode nestedTerm(final MethodBuilder builder) throws ParseError { expect(NewTerm); ExpressionNode exp = expression(builder); expect(EndTerm); return exp; } private LiteralNode literal() throws ParseError { switch (sym) { case Pound: return literalSymbol(); case STString: return literalString(); default: return literalNumber(); } } private LiteralNode literalNumber() throws ParseError { SourceCoordinate coord = getCoordinate(); if (sym == Minus) { return negativeDecimal(coord); } else { return literalDecimal(false, coord); } } private LiteralNode literalDecimal(final boolean isNegative, final SourceCoordinate coord) throws ParseError { if (sym == Integer) { return literalInteger(isNegative, coord); } else { assert sym == Double; return literalDouble(isNegative, coord); } } private LiteralNode negativeDecimal(final SourceCoordinate coord) throws ParseError { expect(Minus); return literalDecimal(true, coord); } private LiteralNode literalInteger(final boolean isNegative, final SourceCoordinate coord) throws ParseError { try { long i = Long.parseLong(text); if (isNegative) { i = 0 - i; } expect(Integer); SourceSection source = getSource(coord); if (i < Long.MIN_VALUE || i > Long.MAX_VALUE) { return new BigIntegerLiteralNode(BigInteger.valueOf(i), source); } else { return new IntegerLiteralNode(i, source); } } catch (NumberFormatException e) { throw new ParseError("Could not parse integer. Expected a number but " + "got '" + text + "'", NONE, this); } } private LiteralNode literalDouble(final boolean isNegative, final SourceCoordinate coord) throws ParseError { try { double d = java.lang.Double.parseDouble(text); if (isNegative) { d = 0.0 - d; } expect(Double); SourceSection source = getSource(coord); return new DoubleLiteralNode(d, source); } catch (NumberFormatException e) { throw new ParseError("Could not parse double. Expected a number but " + "got '" + text + "'", NONE, this); } } private LiteralNode literalSymbol() throws ParseError { SourceCoordinate coord = getCoordinate(); SSymbol symb; expect(Pound); if (sym == STString) { String s = string(); symb = symbolFor(s); } else { symb = selector(); } return new SymbolLiteralNode(symb, getSource(coord)); } private LiteralNode literalString() throws ParseError { SourceCoordinate coord = getCoordinate(); String s = string(); return new StringLiteralNode(s, getSource(coord)); } private SSymbol selector() throws ParseError { if (sym == OperatorSequence || symIn(singleOpSyms)) { return binarySelector(); } else if (sym == Keyword || sym == KeywordSequence) { return keywordSelector(); } else { return unarySelector(); } } private SSymbol keywordSelector() throws ParseError { String s = new String(text); expectOneOf(keywordSelectorSyms); SSymbol symb = symbolFor(s); return symb; } private String string() throws ParseError { String s = new String(text); expect(STString); return s; } private ExpressionNode nestedBlock(final MethodBuilder builder) throws ParseError { expect(NewBlock); SourceCoordinate coord = getCoordinate(); builder.addArgumentIfAbsent("$blockSelf"); if (sym == Colon) { blockPattern(builder); } // generate Block signature String blockSig = "$blockMethod@" + lexer.getCurrentLineNumber() + "@" + lexer.getCurrentColumn(); int argSize = builder.getNumberOfArguments(); for (int i = 1; i < argSize; i++) { blockSig += ":"; } builder.setSignature(symbolFor(blockSig)); ExpressionNode expressions = blockContents(builder); lastMethodsSourceSection = getSource(coord); expect(EndBlock); return expressions; } private void blockPattern(final MethodBuilder builder) throws ParseError { blockArguments(builder); expect(Or); } private void blockArguments(final MethodBuilder builder) throws ParseError { do { expect(Colon); builder.addArgumentIfAbsent(argument()); } while (sym == Colon); } private ExpressionNode implicitReceiverSend(final MethodBuilder builder, final SSymbol selector, final SourceSection source) { // we need to handle super special here if ("super".equals(selector.getString())) { return builder.getSuperReadNode(source); } // first look up local or argument variables Variable variable = builder.getVariable(selector.getString()); if (variable != null) { return builder.getReadNode(selector.getString(), source); } // otherwise, it is an implicit receiver send return SNodeFactory.createImplicitReceiverSend(selector, source); } private ExpressionNode setterSend(final MethodBuilder builder, final SSymbol identifier, final ExpressionNode exp, final SourceSection source) { // write directly to local variables (excluding arguments) Local variable = builder.getLocal(identifier.getString()); if (variable != null) { return builder.getWriteNode(identifier.getString(), exp, source); } // otherwise, it is a setter send. return SNodeFactory.createImplicitReceiverSetterSend(identifier, exp, source); } private void getSymbolFromLexer() { sym = lexer.getSym(); text = lexer.getText(); } private void peekForNextSymbolFromLexer() { Peek peek = lexer.peek(); nextSym = peek.nextSym; nextText = peek.nextText; } private static boolean isIdentifier(final Symbol sym) { return sym == Identifier; } private static boolean printableSymbol(final Symbol sym) { return sym == Integer || sym == Double || sym.compareTo(STString) >= 0; } }
package thesbros.bukkit.CFBanner; //Imports import java.io.IOException; import java.util.logging.Logger; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; //End imports //Start class public class CFBanner extends JavaPlugin implements Listener { //Start setting variables Logger log = Logger.getLogger("Minecraft"); //End setting variables //Start enable code public void onEnable() { if(this.getConfig().getBoolean("enabled") == true) { this.getConfig().options().copyDefaults(true); if(this.getConfig().getBoolean("autoUpdate") == true) { Updater updater = new Updater(this, this.getName().toLowerCase(), this.getFile(), Updater.UpdateType.DEFAULT, true); } this.saveConfig(); //Register the Listener getServer().getPluginManager().registerEvents(this, this); try { Metrics metrics = new Metrics(this); metrics.start(); } catch (IOException e) { log.severe("CFBanner: Could not load Metrics!"); } //TODO: On enable } else { //PluginManager PluginManager pluginManager = Bukkit.getServer().getPluginManager(); //Oh no! log.info("CFBanner: Plugin not enabled! Check config.yml to enable!"); //Disable me pluginManager.disablePlugin(this); } } //End enable code //Start disable code public void onDisable() { //TODO: On disable } //End disable code //Listener code String ZOMBE_FLY_CODE = "f f 1 0 2 4 3 9 2 0 0 1"; String ZOMBE_CHEAT_CODE = "f f 2 0 4 8 3 9 2 0 0 2"; String CJB_CODE = "3 9 2 0 0 0"; String REI_CODE = "001234567ef"; @EventHandler(priority=EventPriority.HIGH) public void onPlayerJoin(final PlayerJoinEvent event) { Player thePlayer = event.getPlayer(); if (!thePlayer.hasPermission("cfbanner.fly")) { thePlayer.sendMessage(this.ZOMBE_FLY_CODE);; } if (!thePlayer.hasPermission("cfbanner.xray")) { thePlayer.sendMessage(this.ZOMBE_CHEAT_CODE); } if (!thePlayer.hasPermission("cfbanner.cjb")) { thePlayer.sendMessage(this.CJB_CODE); } if (thePlayer.hasPermission("cfbanner.minimap")) { thePlayer.sendMessage(this.REI_CODE); } if(getConfig().getBoolean("enabled") == true && getConfig().getBoolean("showRunningCFBanner") == true) { thePlayer.sendMessage(getConfig().getString("runningCFBannerMessage")); } } //End listener code } //End class
package springies; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import org.w3c.dom.Node; import jgame.JGColor; import jgame.platform.JGEngine; import Connectors.Spring; import Forces.CenterOfMass; import Forces.Gravity; import Forces.Viscosity; import Forces.WallRepulsion; import Forces.WorldManager; import Masses.PhysicalObjectMass; import PhysicalObjects.Assembly; import Walls.Wall; import Walls.WalledArea; import parserutil.EnvironmentParser; import parserutil.ObjectsParser; @SuppressWarnings("serial") public class Springies extends JGEngine { private PhysicalObjectMass m1; private PhysicalObjectMass m2; private PhysicalObjectMass m3; public Spring temp; public Spring temp2; public Spring temp3; private WalledArea walls; private ArrayList<Assembly> assemblies; static final double WALL_MARGIN = 10; static final double WALL_THICKNESS = 10; private Gravity g; private Viscosity v; private CenterOfMass com; private WallRepulsion wr; private PhysicalObjectMass mouseMass; public Springies () { int height = 480; double aspect = 16.0 / 9.0; initEngineComponent((int) (height * aspect), height); } @Override public void initCanvas (){ setCanvasSettings(1, 1, displayWidth(), displayHeight(), null, null, null); } @Override public void initGame (){ setFrameRate(60, 2); getEnvironment("assets/environment.xml"); WorldManager.initWorld(this); assemblies = new ArrayList<Assembly>(); // addBall(); addWalls(); // createPhysicalElements("assets/ball.xml"); mouseMass = new PhysicalObjectMass("mass", -2, JGColor.white, 10, 5, 0, 0, 0, 0); } public void addBall (){ m1 = new PhysicalObjectMass("ball", 1, JGColor.red, 10, 5, displayWidth()/2, displayHeight()/2,0,0); m2 = new PhysicalObjectMass("ball2", 1, JGColor.yellow, 10, 5, displayWidth()/2-100, displayHeight()/2-100, 0,0); m3 = new PhysicalObjectMass("ball3", 1, JGColor.blue, 10, 5, displayWidth()/2-200, displayHeight()/2, 0, 0); temp = new Spring("spring", 0, JGColor.pink); temp2 = new Spring("spring", 0, JGColor.magenta); temp3 = new Spring("spring", 0, JGColor.orange); temp.connect(m1, m2, 4, 20); temp2.connect(m1, m3, 4, 20); temp3.connect(m2, m3, 4, 20); } private void addWalls (){ final double WALL_WIDTH = displayWidth() - WALL_MARGIN * 2 + WALL_THICKNESS; final double WALL_HEIGHT = displayHeight() - WALL_MARGIN * 2 + WALL_THICKNESS; walls = new WalledArea("walled area", 10, JGColor.yellow); Wall topwall = new Wall("wall", 2, JGColor.green, WALL_WIDTH, WALL_THICKNESS, "top"); topwall.setPos(displayWidth() / 2, WALL_MARGIN); Wall bottomwall = new Wall("wall", 2, JGColor.green, WALL_WIDTH, WALL_THICKNESS, "bottom"); bottomwall.setPos(displayWidth() / 2, displayHeight() - WALL_MARGIN); Wall leftwall = new Wall("wall", 2, JGColor.green, WALL_THICKNESS, WALL_HEIGHT, "left"); leftwall.setPos(WALL_MARGIN, displayHeight() / 2); Wall rightwall = new Wall("wall", 2, JGColor.green, WALL_THICKNESS, WALL_HEIGHT, "right"); rightwall.setPos(displayWidth() - WALL_MARGIN, displayHeight() / 2); walls.setWalls(topwall, leftwall, rightwall, bottomwall); } private HashMap<String, PhysicalObjectMass> implementMasses(String[][] masses) { HashMap<String, PhysicalObjectMass> allmasses = new HashMap<String, PhysicalObjectMass>(); for (int springIdx = 0; springIdx< masses.length; springIdx++) { String[] currmass = masses[springIdx]; String id = currmass[0]; int collisionId = 1; JGColor color = JGColor.green; double radius = 5; double x = Double.parseDouble(currmass[1]); double y = Double.parseDouble(currmass[2]); double mass = Double.parseDouble(currmass[3]); double vx = Double.parseDouble(currmass[4]); double vy = Double.parseDouble(currmass[5]); PhysicalObjectMass newmass = new PhysicalObjectMass(id, collisionId, color, radius, mass, x, y, vx, vy); allmasses.put(id, newmass); } return allmasses; } private ArrayList<Spring> implementSprings(String[][] springs, HashMap<String, PhysicalObjectMass> allmasses) { ArrayList<Spring> allSprings = new ArrayList<Spring>(); for (int springIdx = 0; springIdx< springs.length; springIdx++) { String[] currspring = springs[springIdx]; Spring spring = new Spring("spring", 1, JGColor.yellow); PhysicalObjectMass mass1 = allmasses.get(currspring[0]); PhysicalObjectMass mass2 = allmasses.get(currspring[1]); double k = Double.parseDouble(currspring[3]); double restLength = Double.parseDouble(currspring[2]); spring.connect(mass1, mass2, k, restLength); spring.applyForce(); allSprings.add(spring); } return allSprings; } public void createPhysicalElements(String filename) { ObjectsParser elements = new ObjectsParser(); Node doc = elements.parse(filename); String[][] masses = elements.createMasses(doc); HashMap<String, PhysicalObjectMass> allmasses = this.implementMasses(masses); //String [][] fmasses = elements.createFixedMasses(doc); //createFMasses(fmasses); String [][]springs = elements.createSprings(doc); ArrayList<Spring> springList = this.implementSprings(springs, allmasses); ArrayList<PhysicalObjectMass> massList = new ArrayList<PhysicalObjectMass>(allmasses.values()); Assembly assembly= new Assembly(massList, springList); assemblies.add(assembly); //String [][] muscles = elements.createMuscles(doc); //createMuscles(muscles); } private void getEnvironment(String filename) { EnvironmentParser environment = new EnvironmentParser(); Node environ = environment.parse(filename); double [] gravityvals = environment.getGravity(environ); double viscositymagnitude = environment.getViscosity(environ); double [] centermass = environment.getCenterMass(environ); double[][] wallvals = environment.getWalls(environ); g = new Gravity(gravityvals[0], gravityvals[1]); g.setAssembliesList(assemblies); v = new Viscosity(viscositymagnitude); v.setAssembliesList(assemblies); com = new CenterOfMass(centermass[0], centermass[1]); com.setAssembliesList(assemblies); } public String userSelects() { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "XML Files", "xml"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(getParent()); if(returnVal == JFileChooser.APPROVE_OPTION) { File chosenFile = chooser.getSelectedFile(); String pathofFile = chosenFile.getAbsolutePath(); return pathofFile; } return ""; } boolean GRAVITY = false; boolean VISCOSITY = false; boolean CENTER_OF_MASS = false; boolean MOUSE = false; boolean LEFT_WALL = false; boolean TOP_WALL = false; boolean RIGHT_WALL = false; boolean BOTTOM_WALL = false; @Override public void doFrame () { WorldManager.getWorld().step(1f, 1); moveObjects(); checkCollision(2, 1); // temp.applyForce(); // temp2.applyForce(); // temp3.applyForce(); checkToggle(); mouseDragging(mouseMass); } public void mouseDragging(PhysicalObjectMass mouseMass){ if(getMouseButton(1)){ double curMin = Integer.MAX_VALUE; PhysicalObjectMass minMass = null; for(int i = 0; i < assemblies.size(); i++){ ArrayList<PhysicalObjectMass> assemblyMasses = assemblies.get(i).getMasses(); for(int j = 0; j < assemblyMasses.size(); j++){ PhysicalObjectMass curMass = assemblyMasses.get(j); double dist = Math.sqrt(Math.pow(mouseMass.myX - curMass.myX, 2) + Math.pow(mouseMass.myY - curMass.myY, 2)); if(dist < curMin){ curMin = dist; minMass = curMass; } } } mouseMass.setPos(getMouseX(), getMouseY()); Spring TEMPORARY = new Spring("spring", -1, JGColor.red); TEMPORARY.connect(minMass, mouseMass, 1, 20); } } private void checkToggle() { if(getKey('C')) { if (assemblies.size()>0) { for (Assembly assembly: assemblies) { assembly.remove(); } } } if (getKey(KeyUp)) { walls.increaseArea(); } if (getKey(KeyDown)) { walls.reduceArea(); } if (getKey('N')) { String chosenFile= userSelects(); createPhysicalElements(chosenFile); } if(getKey('G')){ GRAVITY = !GRAVITY; clearKey('G'); } if(getKey('V')){ VISCOSITY = !VISCOSITY; clearKey('V'); } if(getKey('M')){ CENTER_OF_MASS = !CENTER_OF_MASS; clearKey('M'); } if(GRAVITY){ g.setAssembliesList(assemblies); g.applyForce(); } if(VISCOSITY) { v.setAssembliesList(assemblies); v.applyForce(); } if(CENTER_OF_MASS){ com.setAssembliesList(assemblies); com.applyForce(); } if(getKey('1')){ LEFT_WALL = !LEFT_WALL; clearKey('1'); } if(getKey('2')){ TOP_WALL = !TOP_WALL; clearKey('2'); } if(getKey('3')){ RIGHT_WALL = !RIGHT_WALL; clearKey('3'); } if(getKey('4')){ BOTTOM_WALL = !BOTTOM_WALL; clearKey('4'); } wr = new WallRepulsion(1, 10000, 1); wr.setAssembliesList(assemblies); if(LEFT_WALL){ wr.leftWallForce(); } if(TOP_WALL){ wr.topWallForce(); } if(RIGHT_WALL){ wr.rightWallForce(); } if(BOTTOM_WALL){ wr.bottomWallForce(); } } @Override public void paintFrame (){ drawString("Gravity ('g'): " + GRAVITY, 100, 20, 0, null, JGColor.white); drawString("Viscosity ('v'): " + VISCOSITY, 110, 40, 0, null, JGColor.white); drawString("Center of Mass ('m'): " + CENTER_OF_MASS, 140, 60, 0, null, JGColor.white); if(getKey(KeyUp)){ drawString("Wall Expanding (up): true", 145, 80, 0, null, JGColor.white); } else{ drawString("Wall Expanding (up): false", 145, 80, 0, null, JGColor.white); } if(getKey(KeyDown)){ drawString("Wall Shrinking (down): true", 150, 100, 0, null, JGColor.white); } else{ drawString("Wall Shrinking (down): false", 150, 100, 0, null, JGColor.white); } drawString("Wall Forces:", pfWidth() - 130, 20, 0, null, JGColor.white); drawString("Left Wall ('1'): " + LEFT_WALL, pfWidth() - 130, 40, 0, null, JGColor.white); drawString("Top Wall ('2'): " + TOP_WALL, pfWidth() - 130, 60, 0, null, JGColor.white); drawString("Right Wall ('3'): " + RIGHT_WALL, pfWidth() - 130, 80, 0, null, JGColor.white); drawString("Bottom Wall ('4'): " + BOTTOM_WALL, pfWidth() - 130, 100, 0, null, JGColor.white); } }
package examples.subdf; import java.io.IOException; import java.io.InterruptedIOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetAddress; import jade.core.*; import jade.core.behaviours.*; import jade.domain.FIPAAgentManagement.*; import jade.domain.FIPAException; import jade.domain.DFServiceCommunicator; import jade.lang.acl.ACLMessage; /** This is an example of an agent that plays the role of a sub-df by automatically registering with a parent DF. Notice that exactly the same might be done by using the GUI of the DF. <p> This SUBDF inherits all the functionalities of the default DF, including its GUI. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class SubDF extends jade.domain.df { public void setup() { // Input df name int len = 0; byte[] buffer = new byte[1024]; try { AID parentName = getDefaultDF(); //Execute the setup of jade.domain.df which includes all the default behaviours of a df //(i.e. register, unregister,modify, and search). super.setup(); //Use this method to modify the current description of this df. setDescriptionOfThisDF(getDescription()); //Show the default Gui of a df. super.showGui(); DFServiceCommunicator.register(this,parentName,getDescription()); addParent(parentName,getDescription()); System.out.println("Agent: " + getName() + " federated with default df."); }catch(FIPAException fe){fe.printStackTrace();} } private DFAgentDescription getDescription() { DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); ServiceDescription sd = new ServiceDescription(); sd.setName(getLocalName() + "-sub-df"); sd.setType("fipa-df"); sd.addProtocols("fipa-request"); sd.addOntologies("fipa-agent-management"); sd.setOwnership("JADE"); dfd.addServices(sd); return dfd; } }
package foam.nanos.boot; import foam.core.*; import foam.dao.AbstractSink; import foam.dao.DAO; import foam.dao.ProxyDAO; import foam.dao.java.JDAO; import foam.nanos.auth.User; import foam.nanos.logger.Logger; import foam.nanos.logger.ProxyLogger; import foam.nanos.logger.StdoutLogger; import foam.nanos.script.Script; import foam.nanos.session.Session; import java.util.List; import static foam.mlang.MLang.EQ; public class Boot { // Context key used to store the top-level root context in the context. public final static String ROOT = "_ROOT_"; protected DAO serviceDAO_; protected X root_ = new ProxyX(); public Boot() { this(""); } public Boot(String datadir) { Logger logger = new ProxyLogger(new StdoutLogger()); root_.put("logger", logger); if ( datadir == null || datadir == "" ) { datadir = System.getProperty("JOURNAL_HOME"); } root_.put(foam.nanos.fs.Storage.class, new foam.nanos.fs.Storage(datadir)); // Used for all the services that will be required when Booting serviceDAO_ = new foam.nanos.auth.PermissionedPropertyDAO(root_, new JDAO(((foam.core.ProxyX) root_).getX(), NSpec.getOwnClassInfo(), "services")); installSystemUser(); serviceDAO_.select(new AbstractSink() { @Override public void put(Object obj, Detachable sub) { NSpec sp = (NSpec) obj; logger.info("Registering:", sp.getName()); root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory((ProxyX) root_, sp))); } }); serviceDAO_.listen(new AbstractSink() { @Override public void put(Object obj, Detachable sub) { NSpec sp = (NSpec) obj; FObject newService = sp.getService(); if ( newService != null ) { logger.info("Updating service configuration: ", sp.getName()); FObject service = (FObject) root_.get(sp.getName()); List<PropertyInfo> props = service.getClassInfo().getAxioms(); for (PropertyInfo prop : props) { prop.set(service, prop.get(newService)); } } } }, null); // Use an XFactory so that the root context can contain itself. root_ = root_.putFactory(ROOT, new XFactory() { public Object create(X x) { return Boot.this.getX(); } }); // Revert root_ to non ProxyX to avoid letting children add new bindings. root_ = ((ProxyX) root_).getX(); // Export the ServiceDAO ((ProxyDAO) root_.get("nSpecDAO")).setDelegate( new foam.dao.PMDAO(root_, new foam.dao.AuthenticatedDAO("service", false, serviceDAO_))); // 'read' authenticated version - for dig and docs ((ProxyDAO) root_.get("AuthenticatedNSpecDAO")).setDelegate( new foam.dao.PMDAO(root_, new foam.dao.AuthenticatedDAO("service", true, (DAO) root_.get("nSpecDAO")))); serviceDAO_.where(EQ(NSpec.LAZY, false)).select(new AbstractSink() { @Override public void put(Object obj, Detachable sub) { NSpec sp = (NSpec) obj; logger.info("Starting:", sp.getName()); root_.get(sp.getName()); } }); String startScript = System.getProperty("foam.main", "main"); if ( startScript != null ) { DAO scriptDAO = (DAO) root_.get("scriptDAO"); Script script = (Script) scriptDAO.find(startScript); if ( script != null ) { script.runScript(root_); } } } protected void installSystemUser() { User user = new User(); user.setId(1); user.setFirstName("system"); user.setGroup("system"); Session session = new Session(); session.setUserId(user.getId()); session.setContext(root_); root_.put("user", user); root_.put(Session.class, session); } public X getX() { return root_; } public static void main (String[] args) throws java.lang.Exception { System.out.println("Starting Nanos Server"); boolean datadirFlag = false; String datadir = ""; for ( int i = 0 ; i < args.length ; i++ ) { String arg = args[i]; if ( datadirFlag ) { datadir = arg; datadirFlag = false; } else if ( arg.equals("--datadir") ) { datadirFlag = true; } else { System.err.println("Unknown argument " + arg); System.exit(1); } } System.out.println("Datadir is " + datadir); new Boot(datadir); } }
package us.kbase.common.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import us.kbase.auth.AuthToken; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.axis.*; import condor.*; import java.net.URL; import java.net.MalformedURLException; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; public class CondorUtils { private static ClassAdStructAttr[] buildJobAd(String owner, String jobFileLocation, int clusterId, int jobId) { String jobOutputFileLocation = jobFileLocation + ".job.out"; String jobLogFileLocation = jobFileLocation + ".job.log"; String stdOutLocation = jobFileLocation + ".stdout"; String stdErrLocation = jobFileLocation + ".stderr"; String dagmanLockFile = jobFileLocation + ".lock"; String workingDirectory = jobFileLocation.substring(0, jobFileLocation.lastIndexOf("/")); ClassAdStructAttr[] jobAd = { createStringAttribute("Owner", owner), // Need to insert kbase username@realm here createStringAttribute("Iwd", workingDirectory), // Awe creates a working directory per job (uuid) we may need to generate one, or use the job id. Not sure if condor will create this directory. If not, we may need to handle working directory creation in the async runner script. createIntAttribute("JobUniverse", 5), // Vanilla Universe createStringAttribute("Cmd", "run_async_srv_method.sh"), createIntAttribute("JobStatus", 1), // Idle createStringAttribute("Env", "_CONDOR_MAX_LOG=0;" + "_CONDOR_LOG=" + jobOutputFileLocation), //leaving in for example setting env var - not needed for kbase createIntAttribute("JobNotification", 0), // Never createStringAttribute("UserLog", jobLogFileLocation), createStringAttribute("RemoveKillSig", "SIGUSR1"), createStringAttribute("Out", stdOutLocation), createStringAttribute("Err", stdErrLocation), createStringAttribute("ShouldTransferFiles", "NO"), // Using shared FS // ERROR schedd log: Job id 62.0 has no Owner attribute. Removing. // TODO: Fix Requirements expression; like: createExpressionAttribute("Requirements", "TARGET.Owner=='root'"), // createExpressionAttribute("Requirements", "TARGET.Owner=='amikaili@???'"), // http://research.cs.wisc.edu/htcondor/manual/v7.6/4_1Condor_s_ClassAd.html#sec:classad-reference // Owner has "Policy" semantics and configuration connotation // Is used to map jobs to machines // Replacing: // createExpressionAttribute("Requirements", "TRUE"), createExpressionAttribute("OnExitRemove", "(ExitSignal =?= 11 || " + " (ExitCode =!= UNDEFINED && " + " ExitCode >=0 && ExitCode <= 2))"), createStringAttribute("Arguments", "-f -l . -Debug 3 "), // also leaving - we can modify for kbase arguments createIntAttribute("ClusterId", clusterId), createIntAttribute("ProcId", jobId) }; return jobAd; } private static ClassAdStructAttr createStringAttribute(String name, String value) { return createAttribute(name, value, ClassAdAttrType.value3); } private static ClassAdStructAttr createIntAttribute(String name, int value) { return createAttribute(name, String.valueOf(value), ClassAdAttrType.value1); } private static ClassAdStructAttr createExpressionAttribute(String name, String value) { return createAttribute(name, value, ClassAdAttrType.value4); } private static ClassAdStructAttr createAttribute(String name, String value, ClassAdAttrType type) { ClassAdStructAttr attribute = new ClassAdStructAttr(); attribute.setName(name); attribute.setValue(value); attribute.setType(type); return attribute; } public static int submitToCondor( String condorUrl, String owner, String jobFileLocation, // String jobName, String args, String scriptName, AuthToken auth, String clientGroups) throws MalformedURLException, RemoteException, ServiceException { URL scheddLocation = new URL( condorUrl ); // Get a handle on a schedd we can make SOAP call on. CondorScheddLocator scheddLocator = new CondorScheddLocator(); CondorScheddPortType schedd = scheddLocator.getcondorSchedd(scheddLocation); // Begin a transaction, allow for 60 seconds between calls TransactionAndStatus transactionAndStatus = schedd.beginTransaction(60); Transaction transaction = transactionAndStatus.getTransaction(); // Get a new cluster for the job. IntAndStatus clusterIdAndStatus = schedd.newCluster(transaction); int clusterId = clusterIdAndStatus.getInteger(); // Get a new Job ID (aka a ProcId) for the Job. IntAndStatus jobIdAndStatus = schedd.newJob(transaction, clusterId); int jobId = jobIdAndStatus.getInteger(); // Build the Job's ClassAd. ClassAdStructAttr[] jobAd = buildJobAd(owner, jobFileLocation, clusterId, jobId); // Submit the Job's ClassAd. schedd.submit(transaction, clusterId, jobId, jobAd); // Commit the transaction. schedd.commitTransaction(transaction); // Ask the Schedd to kick off the Job immediately. schedd.requestReschedule(); return jobId; } public static void main(String[] arguments) throws MalformedURLException, RemoteException, ServiceException { URL scheddLocation = new URL(arguments[0]); String owner = arguments[1]; String jobFileLocation = arguments[2]; // Get a handle on a schedd we can make SOAP call on. CondorScheddLocator scheddLocator = new CondorScheddLocator(); CondorScheddPortType schedd = scheddLocator.getcondorSchedd(scheddLocation); // Begin a transaction, allow for 60 seconds between calls TransactionAndStatus transactionAndStatus = schedd.beginTransaction(60); Transaction transaction = transactionAndStatus.getTransaction(); // Get a new cluster for the job. IntAndStatus clusterIdAndStatus = schedd.newCluster(transaction); int clusterId = clusterIdAndStatus.getInteger(); // Get a new Job ID (aka a ProcId) for the Job. IntAndStatus jobIdAndStatus = schedd.newJob(transaction, clusterId); int jobId = jobIdAndStatus.getInteger(); // Build the Job's ClassAd. ClassAdStructAttr[] jobAd = buildJobAd(owner, jobFileLocation, clusterId, jobId); // Submit the Job's ClassAd. schedd.submit(transaction, clusterId, jobId, jobAd); // Debug: Dump JobAd System.out.println( "CondorUtils::Dump JobAd: " + jobAd.toString() ); for( int i = 0; i < jobAd.length; i++ ) { System.out.println( " JobAd[ " + i + " ] = " + jobAd[ i ] ); } // Commit the transaction. schedd.commitTransaction(transaction); // Ask the Schedd to kick off the Job immediately. schedd.requestReschedule(); } } // class CondorUtils /* public class CondorUtils { @SuppressWarnings("unchecked") public static String submitToCondor(String condorUrl, String jobName, String args, String scriptName, AuthToken auth, String clientGroups) throws JsonGenerationException, JsonMappingException, IOException { */ // TODO: Submit job to Condor /* Map<String, Object> job = new LinkedHashMap<String, Object>(); Map<String, Object> info = new LinkedHashMap<String, Object>(); Map<String, Object> cmd = new LinkedHashMap<String, Object>(); info.put("name", jobName); info.put("project", "SDK"); info.put("user", auth.getUserName()); info.put("clientgroups", clientGroups); job.put("info", info); cmd.put("name", scriptName); Map<String, Object> priv = new LinkedHashMap<String, Object>(); Map<String, Object> env = new LinkedHashMap<String, Object>(); String token = auth.getToken(); priv.put("KB_AUTH_TOKEN", token); env.put("private", priv); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost( condorUrl + "job" ); httpPost.addHeader("Authorization", "OAuth " + token); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(buffer, job); builder.addBinaryBody("upload", buffer.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, "tempjob.json"); httpPost.setEntity(builder.build()); */ // Map<String, Object> respObj = parseAweResponse(httpClient.execute(httpPost)); // Map<String, Object> respData = (Map<String, Object>)respObj.get("data"); // String aweJobId = (String)respData.get("id"); /* return jobName; } } */
// $OldId: Environment.java,v 1.13 2002/10/01 16:14:07 paltherr Exp $ package scalai; import java.util.Map; import java.util.HashMap; import scalac.ast.Tree.ClassDef; import scalac.symtab.Symbol; import scalac.symtab.Type; import scalac.symtab.Scope; import scalac.symtab.Scope.SymbolIterator; import scalac.util.Names; import scalac.util.Debug; public class Environment { // // Private Fields private final Compiler compiler; private final JavaMirror mirror; private final Map/*<Symbol,ClassDef>*/ classdefs; private final Map/*<Symbol,Template>*/ templates; private final Map/*<Symbol,Function>*/ functions; private final Map/*<Symbol,Variable>*/ variables; private final Map/*<Symbol,Override>*/ overrides; // // Public Constructors public Environment(Compiler compiler, JavaMirror mirror) { this.compiler = compiler; this.mirror = mirror; this.classdefs = new HashMap(); this.templates = new HashMap(); this.functions = new HashMap(); this.variables = new HashMap(); this.overrides = new HashMap(); } // // Public Methods - insert public ClassDef insertClassDef(Symbol symbol, ClassDef classdef) { assert symbol.isType() : Debug.show(symbol); assert Debug.log("insert classdef: ", symbol); Object value = classdefs.put(symbol, classdef); assert value == null : Debug.show(symbol) + " -> " + value; assert !templates.containsKey(symbol) : Debug.show(symbol); return classdef; } private Template insertTemplate(Symbol symbol, Template template) { assert symbol.isType() : Debug.show(symbol); assert Debug.log("insert template: ", symbol); Object value = templates.put(symbol, template); assert !classdefs.containsKey(symbol) : Debug.show(symbol); assert value == null : Debug.show(symbol) + " -> " + value; return template; } public Function insertFunction(Symbol symbol, Function function) { assert symbol.isTerm() : Debug.show(symbol); assert Debug.log("insert function: ", symbol); Object value = functions.put(symbol, function); assert value == null : Debug.show(symbol) + " -> " + value; return function; } public Variable insertVariable(Symbol symbol, Variable variable) { assert symbol.isTerm() : Debug.show(symbol); assert Debug.log("insert variable: ", symbol); Object value = variables.put(symbol, variable); assert value == null : Debug.show(symbol) + " -> " + value; return variable; } public Override insertOverride(Symbol symbol, Override override) { assert symbol.isTerm() : Debug.show(symbol); assert Debug.log("insert override: ", symbol); Object value = overrides.put(symbol, override); assert value == null : Debug.show(symbol) + " -> " + value; return override; } // // Public Methods - lookup public Template lookupTemplate(Symbol symbol) { assert symbol.isType() : Debug.show(symbol); Object value = templates.get(symbol); if (value != null) return (Template)value; if (symbol.isExternal()) { Template template = Template.JavaClass(mirror.getClass(symbol)); return insertTemplate(symbol, template); } else { return loadTemplate(symbol); } } public Function lookupFunction(Symbol symbol) { assert symbol.isTerm() : Debug.show(symbol); Object value = functions.get(symbol); if (value != null) return (Function)value; if (symbol.isExternal()) { Function function = (symbol.name == Names.CONSTRUCTOR) ? Function.JavaConstructor(mirror.getConstructor(symbol)) : Function.JavaMethod(mirror.getMethod(symbol)); return insertFunction(symbol, function); } else { return (Function)loadOwnerThenGet("function", symbol, functions); } } public Variable lookupVariable(Symbol symbol) { assert symbol.isTerm() : Debug.show(symbol); Object value = variables.get(symbol); if (value != null) return (Variable)value; if (symbol.isJava() && symbol.isModule()) { // !!! This should never happen. This value will never be used. Class clasz = mirror.getClass(symbol.moduleClass()); Variable variable = Variable.Global(clasz); return insertVariable(symbol, variable); } else if (symbol.isExternal()) { Variable variable = Variable.JavaField(mirror.getField(symbol)); return insertVariable(symbol, variable); } else { return (Variable)loadOwnerThenGet("variable", symbol, variables); } } public Override lookupOverride(Symbol symbol) { assert symbol.isTerm() : Debug.show(symbol); Object value = overrides.get(symbol); if (value != null) return (Override)value; return loadOwnerOverridesThenGet(symbol); } // // Private Methods - template loading private Object loadOwnerThenGet(String what, Symbol symbol, Map table) { loadOwner(what, symbol); Object value = table.get(symbol); assert value != null : Debug.show(symbol) + " -> " + value; return value; } private void loadOwner(String what, Symbol symbol) { assert Debug.log("search ", what, ": ", symbol); assert symbol.owner().isType() : Debug.show(symbol); assert!symbol.owner().isExternal() : Debug.show(symbol); loadTemplate(symbol.owner()); } private Template loadTemplate(Symbol symbol) { Object test1 = classdefs.remove(symbol); if (test1 != null) return loadTemplate(symbol, (ClassDef)test1); loadOwner("template", symbol); Object test2 = classdefs.remove(symbol); if (test2 != null) return loadTemplate(symbol, (ClassDef)test2); Object value = templates.get(symbol); assert value != null : Debug.show(symbol) + " -> " + value; return (Template)value; } private Template loadTemplate(Symbol symbol, ClassDef classdef) { Template template = Template.Global(compiler.load(symbol, classdef)); return insertTemplate(symbol, template); } // // Private Methods - override loading private Override loadOwnerOverridesThenGet(Symbol symbol) { assert Debug.log("search override: ", symbol); assert symbol.owner().isType() : Debug.show(symbol); loadTemplateOverrides(symbol.owner()); Object value = overrides.get(symbol); assert value != null : Debug.show(symbol) + " -> " + value; return (Override)value; } private void loadTemplateOverrides(Symbol symbol) { Type[] bases = symbol.parents(); SymbolIterator i = symbol.members().iterator(true); while (i.hasNext()) loadMethodOverride(bases, i.next()); } private void loadMethodOverride(Type[] bases, Symbol symbol) { if (!symbol.isMethod()) return; Override override = Override.empty().insert(symbol); if (symbol.isExternal()) override.insert(mirror.getMethod(symbol)); for (int i = 0; i < bases.length; i++) { Symbol overridden = symbol.overriddenSymbol(bases[i], true); if (overridden == Symbol.NONE) continue; assert Debug.log("update override: ", symbol, " <- ", overridden); override.insert(lookupOverride(overridden)); } insertOverride(symbol, override); } // }
// $Id: SpeedTest.java,v 1.3 2004/01/01 00:09:02 belaban Exp $ package org.jgroups.tests; import org.jgroups.Channel; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.debug.Debugger; import org.jgroups.log.Trace; import org.jgroups.util.Util; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; /** * Test time taken for multicasting n local messages (messages sent to self). Uses simple MulticastSocket. * Note that packets might get dropped if Util.sleep(1) is commented out (on certain systems this has * to be increased even further). If running with -jg option and Util.sleep() is commented out, there will * probably be packet loss, which will be repaired (by means of retransmission) by JGroups. To see the * retransmit messages, enable tracing (trace=true) in jgroups.properties and add the following lines: * <pre> * trace0=NAKACK.retransmit DEBUG STDOUT * trace1=UNICAST.retransmit DEBUG STDOUT * </pre> * * @author Bela Ban */ public class SpeedTest { static long start, stop; public static void main(String[] args) { MulticastSocket sock=null; Receiver receiver; int num_msgs=1000; byte[] buf; DatagramPacket packet; InetAddress group_addr=null; int[][] matrix; boolean jg=false; // use JGroups channel instead of UDP MulticastSocket JChannel channel=null; String props=null, loopback_props; String group_name="SpeedTest-Group"; Message send_msg; boolean debug=false, cummulative=false; Debugger debugger=null; long sleep_time=1; // sleep in msecs between msg sends boolean busy_sleep=false; boolean yield=false; int num_yields=0; boolean loopback=false; props="UDP(mcast_addr=224.0.0.36;mcast_port=55566;ip_ttl=32;" + "ucast_send_buf_size=32000;ucast_recv_buf_size=64000;" + "mcast_send_buf_size=32000;mcast_recv_buf_size=64000):" + "PING(timeout=2000;num_initial_members=3):" + "MERGE2(min_interval=5000;max_interval=10000):" + "FD_SOCK:" + "VERIFY_SUSPECT(timeout=1500):" + "pbcast.NAKACK(max_xmit_size=8192;gc_lag=50;retransmit_timeout=600,800,1200,2400,4800):" + "UNICAST(timeout=1200):" + "pbcast.STABLE(desired_avg_gossip=10000):" + "FRAG(frag_size=8192;down_thread=false;up_thread=false):" + // "PIGGYBACK(max_size=16000;max_wait_time=500):" + "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" + "shun=false;print_local_addr=true):" + "pbcast.STATE_TRANSFER"; // "PERF(details=true)"; loopback_props="LOOPBACK:" + "PING(timeout=2000;num_initial_members=3):" + "MERGE2(min_interval=5000;max_interval=10000):" + "FD_SOCK:" + "VERIFY_SUSPECT(timeout=1500):" + "pbcast.NAKACK(gc_lag=50;retransmit_timeout=600,800,1200,2400,4800):" + "UNICAST(timeout=5000):" + "pbcast.STABLE(desired_avg_gossip=20000):" + "FRAG(frag_size=16000;down_thread=false;up_thread=false):" + "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" + "shun=false;print_local_addr=true):" + "pbcast.STATE_TRANSFER"; for(int i=0; i < args.length; i++) { if(args[i].equals("-help")) { help(); return; } if(args[i].equals("-jg")) { jg=true; continue; } if(args[i].equals("-loopback")) { loopback=true; props=loopback_props; continue; } if(args[i].equals("-props")) { props=args[++i]; continue; } if(args[i].equals("-debug")) { debug=true; continue; } if(args[i].equals("-cummulative")) { cummulative=true; continue; } if(args[i].equals("-busy_sleep")) { busy_sleep=true; continue; } if(args[i].equals("-yield")) { yield=true; num_yields++; continue; } if(args[i].equals("-sleep")) { sleep_time=new Long(args[++i]).longValue(); continue; } if(args[i].equals("-num_msgs")) { num_msgs=new Integer(args[++i]).intValue(); continue; } help(); return; } System.out.println("jg = " + jg + "\nloopback = " + loopback + "\ndebug = " + debug + "\nsleep = " + sleep_time + "\nbusy_sleep=" + busy_sleep + "\nyield=" + yield + "\nnum_yields=" + num_yields + "\nnum_msgs = " + num_msgs + "\n"); Trace.init(); try { matrix=new int[num_msgs][2]; for(int i=0; i < num_msgs; i++) { for(int j=0; j < matrix[i].length; j++) matrix[i][j]=0; } if(jg) { channel=new JChannel(props); channel.connect(group_name); if(debug) { debugger=new Debugger(channel, cummulative); debugger.start(); } } else { group_addr=InetAddress.getByName("224.0.0.36"); sock=new MulticastSocket(7777); sock.joinGroup(group_addr); } if(debug) { System.out.println("Press key to start"); System.in.read(); } receiver=new Receiver(sock, channel, matrix, jg); receiver.start(); start=System.currentTimeMillis(); send_msg=new Message(); for(int i=0; i < num_msgs; i++) { buf=Util.objectToByteBuffer(new Integer(i)); if(jg) { send_msg=new Message(null, null, buf); channel.send(send_msg); } else { packet=new DatagramPacket(buf, buf.length, group_addr, 7777); sock.send(packet); } if(i % 100 == 0) System.out.println("-- sent " + i); matrix[i][0]=1; if(yield) { for(int k=0; k < num_yields; k++) { Thread.yield(); } } else { if(sleep_time > 0) { sleep(sleep_time, busy_sleep); } } } while(true) { System.in.read(); printMatrix(matrix); } } catch(Exception ex) { System.err.println(ex); } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { Util.sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } static void printMatrix(int[][] m) { int tmp=0; System.out.print("not sent: "); for(int i=0; i < m.length; i++) { if(m[i][0] == 0) { System.out.print(i + " "); tmp++; } } System.out.println("\ntotal not sent: " + tmp); tmp=0; System.out.print("not received: "); for(int i=0; i < m.length; i++) { if(m[i][1] == 0) { System.out.print(i + " "); tmp++; } } System.out.println("\ntotal not received: " + tmp); System.out.println("Press CTRL-C to kill this test"); } static void help() { System.out.println("SpeedTest [-help] [-num_msgs <num>] [-sleep <sleeptime in msecs between messages>] " + "[-busy_sleep] [-yield] [-jg] [-loopback] [-props <channel properties>] [-debug] [-cummulative]"); System.out.println("Options -props -debug and -cummulative are only valid if -jg is used"); } static class Receiver implements Runnable { Thread t=null; byte[] buf=new byte[1024]; MulticastSocket sock; Channel channel; int num_msgs=1000; int[][] matrix=null; boolean jg=false; Receiver(MulticastSocket sock, Channel channel, int[][] matrix, boolean jg) { this.sock=sock; this.channel=channel; this.matrix=matrix; this.jg=jg; num_msgs=matrix.length; } public void start() { if(t == null) { t=new Thread(this, "receiver thread"); t.start(); } } public void run() { int num_received=0; int number; DatagramPacket packet; Object obj; Message msg; byte[] msg_data=null; long total_time; double msgs_per_sec=0; packet=new DatagramPacket(buf, buf.length); while(num_received <= num_msgs) { msg_data=null; try { if(jg) { obj=channel.receive(0); if(obj instanceof Message) { msg=(Message)obj; msg_data=msg.getBuffer(); } else { System.out.println("received non-msg: " + obj.getClass()); continue; } } else { sock.receive(packet); msg_data=packet.getData(); } number=((Integer)Util.objectFromByteBuffer(msg_data)).intValue(); matrix[number][1]=1; num_received++; if(num_received % 100 == 0) System.out.println("received " + num_received + " packets"); if(num_received >= num_msgs) break; } catch(Exception ex) { System.err.println(ex); } } stop=System.currentTimeMillis(); total_time=stop - start; msgs_per_sec=(num_received / (total_time / 1000.0)); System.out.println("\n** Sending and receiving " + num_received + " took " + total_time + " msecs (" + msgs_per_sec + " msgs/sec) **"); } } }