lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
41eb8ef383c1b3b701d258bb7de38bca4b7f69a2
0
31H0B1eV/ChatSecureAndroid,anvayarai/my-ChatSecure,10045125/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,h2ri/ChatSecureAndroid,h2ri/ChatSecureAndroid,n8fr8/AwesomeApp,prembasumatary/ChatSecureAndroid,n8fr8/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,Heart2009/ChatSecureAndroid,guardianproject/ChatSecureAndroid,Heart2009/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,kden/ChatSecureAndroid,anvayarai/my-ChatSecure,maheshwarishivam/ChatSecureAndroid,prive/prive-android,prembasumatary/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,bonashen/ChatSecureAndroid,prive/prive-android,joskarthic/chatsecure,kden/ChatSecureAndroid,joskarthic/chatsecure,n8fr8/ChatSecureAndroid,n8fr8/ChatSecureAndroid,bonashen/ChatSecureAndroid,eighthave/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid,eighthave/ChatSecureAndroid,n8fr8/AwesomeApp,h2ri/ChatSecureAndroid,kden/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,bonashen/ChatSecureAndroid,anvayarai/my-ChatSecure,n8fr8/AwesomeApp,maheshwarishivam/ChatSecureAndroid,prive/prive-android,OnlyInAmerica/ChatSecureAndroid,guardianproject/ChatSecureAndroid,guardianproject/ChatSecureAndroid,eighthave/ChatSecureAndroid,joskarthic/chatsecure,prive/prive-android,10045125/ChatSecureAndroid,10045125/ChatSecureAndroid,Heart2009/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid
package info.guardianproject.otr.app.im.plugin.xmpp; import info.guardianproject.otr.app.im.engine.ChatGroupManager; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.ChatSessionManager; import info.guardianproject.otr.app.im.engine.Contact; import info.guardianproject.otr.app.im.engine.ContactList; import info.guardianproject.otr.app.im.engine.ContactListListener; import info.guardianproject.otr.app.im.engine.ContactListManager; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.ImException; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.Presence; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.util.LogCleaner; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.harmony.javax.security.auth.callback.Callback; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.jivesoftware.smack.JmDNSService; import org.jivesoftware.smack.LLChat; import org.jivesoftware.smack.LLChatListener; import org.jivesoftware.smack.LLMessageListener; import org.jivesoftware.smack.LLPresence; import org.jivesoftware.smack.LLPresence.Mode; import org.jivesoftware.smack.LLPresenceListener; import org.jivesoftware.smack.LLService; import org.jivesoftware.smack.LLServiceStateListener; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.LLServiceDiscoveryManager; import android.content.ContentResolver; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.MulticastLock; import android.net.wifi.WifiManager.WifiLock; import android.util.Log; public class LLXmppConnection extends ImConnection implements CallbackHandler { final static String TAG = "Gibberbot.LLXmppConnection"; private XmppContactListManager mContactListManager; private Contact mUser; private XmppChatSessionManager mSessionManager; private ThreadPoolExecutor mExecutor; private long mAccountId = -1; private long mProviderId = -1; private final static int SOTIMEOUT = 15000; private LLService mService; private MulticastLock mcLock; private WifiLock wifiLock; private InetAddress ipAddress; private String mServiceName; private String mResource; static { LLServiceDiscoveryManager.addServiceListener(); } public LLXmppConnection(Context context) { super(context); SmackConfiguration.setPacketReplyTimeout(SOTIMEOUT); // Create a single threaded executor. This will serialize actions on the // underlying connection. createExecutor(); DeliveryReceipts.addExtensionProviders(); String identityResource = "ChatSecure"; String identityType = "phone"; LLServiceDiscoveryManager.setIdentityName(identityResource); LLServiceDiscoveryManager.setIdentityType(identityType); } private void createExecutor() { mExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } private boolean execute(Runnable runnable) { try { mExecutor.execute(runnable); } catch (RejectedExecutionException ex) { return false; } return true; } // Execute a runnable only if we are idle private boolean executeIfIdle(Runnable runnable) { if (mExecutor.getActiveCount() + mExecutor.getQueue().size() == 0) { return execute(runnable); } return false; } public void join() throws InterruptedException { ExecutorService oldExecutor = mExecutor; createExecutor(); oldExecutor.shutdown(); oldExecutor.awaitTermination(10, TimeUnit.SECONDS); } public void sendPacket(final org.jivesoftware.smack.packet.Message message) { execute(new Runnable() { @Override public void run() { LLChat chat; try { chat = mService.getChat(message.getTo()); chat.sendMessage(message); } catch (XMPPException e) { Log.e(TAG, "Could not send message", e); } } }); } @Override protected void doUpdateUserPresenceAsync(Presence presence) { String statusText = presence.getStatusText(); Mode mode = Mode.avail; if (presence.getStatus() == Presence.AWAY) { mode = Mode.away; } else if (presence.getStatus() == Presence.IDLE) { mode = Mode.away; } else if (presence.getStatus() == Presence.DO_NOT_DISTURB) { mode = Mode.dnd; } else if (presence.getStatus() == Presence.OFFLINE) { statusText = "Offline"; } mService.getLocalPresence().setStatus(mode); mService.getLocalPresence().setMsg(statusText); try { mService.updatePresence(mService.getLocalPresence()); } catch (XMPPException e) { Log.e(TAG, "Could not update presence", e); } mUserPresence = presence; notifyUserPresenceUpdated(); } @Override public int getCapability() { return ImConnection.CAPABILITY_SESSION_REESTABLISHMENT; } @Override public ChatGroupManager getChatGroupManager() { return null; } @Override public synchronized ChatSessionManager getChatSessionManager() { if (mSessionManager == null) mSessionManager = new XmppChatSessionManager(); return mSessionManager; } @Override public synchronized XmppContactListManager getContactListManager() { if (mContactListManager == null) mContactListManager = new XmppContactListManager(); return mContactListManager; } @Override public Contact getLoginUser() { return mUser; } @Override public Map<String, String> getSessionContext() { // Empty state for now (but must have at least one key) return Collections.singletonMap("state", "empty"); } @Override public int[] getSupportedPresenceStatus() { return new int[] { Presence.AVAILABLE, Presence.AWAY, Presence.DO_NOT_DISTURB, }; } @Override public void loginAsync(long accountId, String passwordTemp, long providerId, boolean retry) { mAccountId = accountId; mProviderId = providerId; execute(new Runnable() { @Override public void run() { do_login(); } }); } public void do_login() { ContentResolver contentResolver = mContext.getContentResolver(); Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap( contentResolver, mProviderId, false, null); // providerSettings is closed in initConnection() String userName = Imps.Account.getUserName(contentResolver, mAccountId); String domain = providerSettings.getDomain(); mResource = providerSettings.getXmppResource(); providerSettings.close(); // close this, which was opened in do_login() try { initConnection(userName, domain); } catch (Exception e) { Log.w(TAG, "login failed", e); ImErrorInfo info = new ImErrorInfo(ImErrorInfo.UNKNOWN_ERROR, e.getMessage()); setState(DISCONNECTED, info); mService = null; } } public void setProxy(String type, String host, int port) { // Ignore proxies for mDNS } // Runs in executor thread private void initConnection(String userName, String domain) throws Exception { setState(LOGGING_IN, null); mServiceName = userName + '@' + domain;// + '/' + mResource; ipAddress = getMyAddress(mServiceName, true); if (ipAddress == null) { ImErrorInfo info = new ImErrorInfo(ImErrorInfo.WIFI_NOT_CONNECTED_ERROR, "network connection is required"); setState(DISCONNECTED, info); return; } mUserPresence = new Presence(Presence.AVAILABLE, "", null, null, Presence.CLIENT_TYPE_MOBILE); LLPresence presence = new LLPresence(mServiceName); presence.setNick(userName); presence.setJID(mServiceName); presence.setServiceName(mServiceName); mService = JmDNSService.create(presence, ipAddress); mService.addServiceStateListener(new LLServiceStateListener() { public void serviceNameChanged(String newName, String oldName) { debug(TAG, "Service named changed from " + oldName + " to " + newName + "."); } public void serviceClosed() { debug(TAG, "Service closed"); if (getState() != SUSPENDED) { setState(DISCONNECTED, null); } releaseLocks(); } public void serviceClosedOnError(Exception e) { debug(TAG, "Service closed on error"); ImErrorInfo info = new ImErrorInfo(ImErrorInfo.UNKNOWN_ERROR, e.getMessage()); setState(DISCONNECTED, info); releaseLocks(); } public void unknownOriginMessage(org.jivesoftware.smack.packet.Message m) { debug(TAG, "This message has unknown origin:"); debug(TAG, m.toXML()); } }); // Adding presence listener. mService.addPresenceListener(new LLPresenceListener() { public void presenceRemove(final LLPresence presence) { execute(new Runnable() { public void run() { mContactListManager.handlePresenceChanged(presence, true); } }); } public void presenceNew(final LLPresence presence) { execute(new Runnable() { public void run() { mContactListManager.handlePresenceChanged(presence, false); } }); } }); debug(TAG, "Preparing link-local service discovery"); LLServiceDiscoveryManager disco = LLServiceDiscoveryManager.getInstanceFor(mService); disco.addFeature(DeliveryReceipts.NAMESPACE); // Start listen for Link-local chats mService.addLLChatListener(new LLChatListener() { public void newChat(LLChat chat) { chat.addMessageListener(new LLMessageListener() { public void processMessage(LLChat chat, org.jivesoftware.smack.packet.Message message) { String address = message.getFrom(); ChatSession session = findOrCreateSession(address); DeliveryReceipts.DeliveryReceipt dr = (DeliveryReceipts.DeliveryReceipt) message .getExtension("received", DeliveryReceipts.NAMESPACE); if (dr != null) { debug(TAG, "got delivery receipt for " + dr.getId()); session.onMessageReceipt(dr.getId()); } if (message.getBody() == null) return; Message rec = new Message(message.getBody()); rec.setTo(mUser.getAddress()); rec.setFrom(session.getParticipant().getAddress()); rec.setDateTime(new Date()); rec.setType(Imps.MessageType.INCOMING); session.onReceiveMessage(rec); if (message.getExtension("request", DeliveryReceipts.NAMESPACE) != null) { debug(TAG, "got delivery receipt request"); // got XEP-0184 request, send receipt sendReceipt(message); session.onReceiptsExpected(); } } }); } public void chatInvalidated(LLChat chat) { // TODO } }); mUser = new Contact(new XmppAddress(mServiceName), userName); // Initiate Link-local message session mService.init(); debug(TAG, "logged in"); setState(LOGGED_IN, null); } private InetAddress getMyAddress(final String serviceName, boolean doLock) { WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo connectionInfo = wifi.getConnectionInfo(); if (connectionInfo == null || connectionInfo.getBSSID() == null) { Log.w(TAG, "Not connected to wifi. This may not work."); // Get the IP the usual Java way try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress; } } } } catch (SocketException e) { Log.e(TAG, "while enumerating interfaces", e); return null; } } int ip = connectionInfo.getIpAddress(); InetAddress address; try { address = InetAddress.getByAddress(new byte[] { (byte) ((ip) & 0xff), (byte) ((ip >> 8) & 0xff), (byte) ((ip >> 16) & 0xff), (byte) ((ip >> 24) & 0xff) }); } catch (UnknownHostException e) { Log.e(TAG, "unknown host exception when converting ip address"); return null; } if (doLock) { mcLock = wifi.createMulticastLock(serviceName); mcLock.acquire(); // HIGH_PERF is only available on android-12 and above int wifiMode; try { wifiMode = (Integer) WifiManager.class.getField("WIFI_MODE_FULL_HIGH_PERF").get( null); } catch (Exception e) { wifiMode = WifiManager.WIFI_MODE_FULL; } wifiLock = wifi.createWifiLock(wifiMode, serviceName); wifiLock.acquire(); } return address; } private void releaseLocks() { if (mcLock != null) mcLock.release(); mcLock = null; if (wifiLock != null) wifiLock.release(); wifiLock = null; } public void sendReceipt(org.jivesoftware.smack.packet.Message msg) { debug(TAG, "sending XEP-0184 ack to " + msg.getFrom() + " id=" + msg.getPacketID()); org.jivesoftware.smack.packet.Message ack = new org.jivesoftware.smack.packet.Message( msg.getFrom(), msg.getType()); ack.addExtension(new DeliveryReceipts.DeliveryReceipt(msg.getPacketID())); sendPacket(ack); } void disconnected(ImErrorInfo info) { Log.w(TAG, "disconnected"); setState(DISCONNECTED, info); } protected static int parsePresence(LLPresence presence, boolean offline) { if (offline) return Presence.OFFLINE; int type = Presence.AVAILABLE; Mode rmode = presence.getStatus(); if (rmode == Mode.away) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; return type; } protected static String parseAddressBase(String from) { return from.replaceFirst("/.*", ""); } protected static String parseAddressName(String from) { return from.replaceFirst("@.*", ""); } @Override public void logoutAsync() { // TODO invoke join() here? execute(new Runnable() { @Override public void run() { logout(); } }); } // Force immediate logout public synchronized void logout() { if (mService != null) { mService.close(); mService = null; } } @Override public void suspend() { execute(new Runnable() { @Override public void run() { do_suspend(); } }); } private void do_suspend() { debug(TAG, "suspend"); setState(SUSPENDED, null); logout(); } private ChatSession findOrCreateSession(String address) { ChatSession session = mSessionManager.findSession(address); if (session == null) { Contact contact = findOrCreateContact(parseAddressName(address), address); session = mSessionManager.createChatSession(contact); } return session; } Contact findOrCreateContact(String name, String address) { Contact contact = mContactListManager.getContact(address); if (contact == null) { contact = makeContact(name, address); } return contact; } private static Contact makeContact(String name, String address) { Contact contact = new Contact(new XmppAddress(address), name); return contact; } private final class XmppChatSessionManager extends ChatSessionManager { @Override public void sendMessageAsync(ChatSession session, Message message) { org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message( message.getTo().getAddress(), org.jivesoftware.smack.packet.Message.Type.chat); msg.addExtension(new DeliveryReceipts.DeliveryReceiptRequest()); msg.setBody(message.getBody()); debug(TAG, "sending packet ID " + msg.getPacketID()); message.setID(msg.getPacketID()); sendPacket(msg); } ChatSession findSession(String address) { for (Iterator<ChatSession> iter = mSessions.iterator(); iter.hasNext();) { ChatSession session = iter.next(); if (session.getParticipant().getAddress().getAddress().equals(address)) return session; } return null; } } public ChatSession findSession(String address) { return mSessionManager.findSession(address); } public ChatSession createChatSession(Contact contact) { return mSessionManager.createChatSession(contact); } public class XmppContactListManager extends ContactListManager { public XmppContactListManager () { super(); } private void do_loadContactLists() { String generalGroupName = "Buddies"; Collection<Contact> contacts = new ArrayList<Contact>(); ContactList cl = new ContactList(mUser.getAddress(), generalGroupName, true, contacts, this); notifyContactListCreated(cl); notifyContactListsLoaded(); } @Override protected void setListNameAsync(final String name, final ContactList list) { execute(new Runnable() { @Override public void run() { // TODO } }); } @Override public String normalizeAddress(String address) { return new XmppAddress(address).getBareAddress(); } @Override public void loadContactListsAsync() { execute(new Runnable() { @Override public void run() { do_loadContactLists(); } }); } private void handlePresenceChanged(LLPresence presence, boolean offline) { if (presence.getServiceName().equals(mServiceName)) return; //this is from us! // Create default lists on first presence received if (getState() != ContactListManager.LISTS_LOADED) { loadContactListsAsync(); } String name = presence.getNick(); String address = presence.getJID(); if (address == null) //sometimes with zeroconf/bonjour there may not be a JID address = presence.getServiceName(); XmppAddress xaddress = new XmppAddress(address); if (name == null) name = xaddress.getUser(); Contact contact = findOrCreateContact(name,xaddress.getAddress()); try { if (!mContactListManager.getDefaultContactList().containsContact(contact)) { mContactListManager.getDefaultContactList().addExistingContact(contact); notifyContactListUpdated(mContactListManager.getDefaultContactList(), ContactListListener.LIST_CONTACT_ADDED, contact); } } catch (ImException e) { LogCleaner.error(TAG, "unable to add contact to list", e); } Presence p = new Presence(parsePresence(presence, offline), presence.getMsg(), null, null, Presence.CLIENT_TYPE_DEFAULT); contact.setPresence(p); Contact[] contacts = new Contact[] { contact }; notifyContactsPresenceUpdated(contacts); } @Override protected ImConnection getConnection() { return LLXmppConnection.this; } @Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { // TODO } @Override protected void doDeleteContactListAsync(ContactList list) { // TODO delete contact list debug(TAG, "delete contact list " + list.getName()); } @Override protected void doCreateContactListAsync(String name, Collection<Contact> contacts, boolean isDefault) { // TODO create contact list debug(TAG, "create contact list " + name + " default " + isDefault); } @Override protected void doBlockContactAsync(String address, boolean block) { // TODO block contact } private void doAddContact(String name, String address, ContactList list) { Contact contact = makeContact(name, address); if (!containsContact(contact)) notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact); } private void doAddContact(String name, String address) { try { doAddContact(name, address, getDefaultContactList()); } catch (ImException e) { Log.e(TAG, "Failed to add contact", e); } } @Override protected void doAddContactToListAsync(String address, ContactList list) throws ImException { debug(TAG, "add contact to " + list.getName()); // TODO } @Override public void declineSubscriptionRequest(String contact) { debug(TAG, "decline subscription"); // TODO } @Override public void approveSubscriptionRequest(String contact) { debug(TAG, "approve subscription"); // TODO } @Override public Contact createTemporaryContact(String address) { debug(TAG, "create temporary " + address); return makeContact(parseAddressName(address), address); } } @Override public void networkTypeChanged() { super.networkTypeChanged(); } @Override protected void setState(int state, ImErrorInfo error) { debug(TAG, "setState to " + state); super.setState(state, error); } public static void debug(String tag, String msg) { Log.d(tag, msg); } @Override public void handle(Callback[] arg0) throws IOException { for (Callback cb : arg0) { debug(TAG, cb.toString()); } } @Override public void reestablishSessionAsync(Map<String, String> sessionContext) { execute(new Runnable() { public void run() { do_login(); } }); } @Override public void sendHeartbeat(long heartbeatInterval) { InetAddress newAddress = getMyAddress(mServiceName, false); if (!ipAddress.equals(newAddress)) { debug(TAG, "new address, reconnect"); execute(new Runnable() { public void run() { do_suspend(); do_login(); } }); } } }
src/info/guardianproject/otr/app/im/plugin/xmpp/LLXmppConnection.java
package info.guardianproject.otr.app.im.plugin.xmpp; import info.guardianproject.otr.app.im.engine.ChatGroupManager; import info.guardianproject.otr.app.im.engine.ChatSession; import info.guardianproject.otr.app.im.engine.ChatSessionManager; import info.guardianproject.otr.app.im.engine.Contact; import info.guardianproject.otr.app.im.engine.ContactList; import info.guardianproject.otr.app.im.engine.ContactListListener; import info.guardianproject.otr.app.im.engine.ContactListManager; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.engine.ImException; import info.guardianproject.otr.app.im.engine.Message; import info.guardianproject.otr.app.im.engine.Presence; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.util.LogCleaner; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.harmony.javax.security.auth.callback.Callback; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.jivesoftware.smack.JmDNSService; import org.jivesoftware.smack.LLChat; import org.jivesoftware.smack.LLChatListener; import org.jivesoftware.smack.LLMessageListener; import org.jivesoftware.smack.LLPresence; import org.jivesoftware.smack.LLPresence.Mode; import org.jivesoftware.smack.LLPresenceListener; import org.jivesoftware.smack.LLService; import org.jivesoftware.smack.LLServiceStateListener; import org.jivesoftware.smack.SmackConfiguration; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.LLServiceDiscoveryManager; import android.content.ContentResolver; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.MulticastLock; import android.net.wifi.WifiManager.WifiLock; import android.util.Log; public class LLXmppConnection extends ImConnection implements CallbackHandler { final static String TAG = "Gibberbot.LLXmppConnection"; private XmppContactListManager mContactListManager; private Contact mUser; private XmppChatSessionManager mSessionManager; private ThreadPoolExecutor mExecutor; private long mAccountId = -1; private long mProviderId = -1; private final static int SOTIMEOUT = 15000; private LLService mService; private MulticastLock mcLock; private WifiLock wifiLock; private InetAddress ipAddress; private String mServiceName; private String mResource; static { LLServiceDiscoveryManager.addServiceListener(); } public LLXmppConnection(Context context) { super(context); SmackConfiguration.setPacketReplyTimeout(SOTIMEOUT); // Create a single threaded executor. This will serialize actions on the // underlying connection. createExecutor(); DeliveryReceipts.addExtensionProviders(); String identityResource = "ChatSecure"; String identityType = "phone"; LLServiceDiscoveryManager.setIdentityName(identityResource); LLServiceDiscoveryManager.setIdentityType(identityType); } private void createExecutor() { mExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } private boolean execute(Runnable runnable) { try { mExecutor.execute(runnable); } catch (RejectedExecutionException ex) { return false; } return true; } // Execute a runnable only if we are idle private boolean executeIfIdle(Runnable runnable) { if (mExecutor.getActiveCount() + mExecutor.getQueue().size() == 0) { return execute(runnable); } return false; } public void join() throws InterruptedException { ExecutorService oldExecutor = mExecutor; createExecutor(); oldExecutor.shutdown(); oldExecutor.awaitTermination(10, TimeUnit.SECONDS); } public void sendPacket(final org.jivesoftware.smack.packet.Message message) { execute(new Runnable() { @Override public void run() { LLChat chat; try { chat = mService.getChat(message.getTo()); chat.sendMessage(message); } catch (XMPPException e) { Log.e(TAG, "Could not send message", e); } } }); } @Override protected void doUpdateUserPresenceAsync(Presence presence) { String statusText = presence.getStatusText(); Mode mode = Mode.avail; if (presence.getStatus() == Presence.AWAY) { mode = Mode.away; } else if (presence.getStatus() == Presence.IDLE) { mode = Mode.away; } else if (presence.getStatus() == Presence.DO_NOT_DISTURB) { mode = Mode.dnd; } else if (presence.getStatus() == Presence.OFFLINE) { statusText = "Offline"; } mService.getLocalPresence().setStatus(mode); mService.getLocalPresence().setMsg(statusText); try { mService.updatePresence(mService.getLocalPresence()); } catch (XMPPException e) { Log.e(TAG, "Could not update presence", e); } mUserPresence = presence; notifyUserPresenceUpdated(); } @Override public int getCapability() { return ImConnection.CAPABILITY_SESSION_REESTABLISHMENT; } @Override public ChatGroupManager getChatGroupManager() { return null; } @Override public synchronized ChatSessionManager getChatSessionManager() { if (mSessionManager == null) mSessionManager = new XmppChatSessionManager(); return mSessionManager; } @Override public synchronized XmppContactListManager getContactListManager() { if (mContactListManager == null) mContactListManager = new XmppContactListManager(); return mContactListManager; } @Override public Contact getLoginUser() { return mUser; } @Override public Map<String, String> getSessionContext() { // Empty state for now (but must have at least one key) return Collections.singletonMap("state", "empty"); } @Override public int[] getSupportedPresenceStatus() { return new int[] { Presence.AVAILABLE, Presence.AWAY, Presence.DO_NOT_DISTURB, }; } @Override public void loginAsync(long accountId, String passwordTemp, long providerId, boolean retry) { mAccountId = accountId; mProviderId = providerId; execute(new Runnable() { @Override public void run() { do_login(); } }); } public void do_login() { ContentResolver contentResolver = mContext.getContentResolver(); Imps.ProviderSettings.QueryMap providerSettings = new Imps.ProviderSettings.QueryMap( contentResolver, mProviderId, false, null); // providerSettings is closed in initConnection() String userName = Imps.Account.getUserName(contentResolver, mAccountId); String domain = providerSettings.getDomain(); mResource = providerSettings.getXmppResource(); providerSettings.close(); // close this, which was opened in do_login() try { initConnection(userName, domain); } catch (Exception e) { Log.w(TAG, "login failed", e); ImErrorInfo info = new ImErrorInfo(ImErrorInfo.UNKNOWN_ERROR, e.getMessage()); setState(DISCONNECTED, info); mService = null; } } public void setProxy(String type, String host, int port) { // Ignore proxies for mDNS } // Runs in executor thread private void initConnection(String userName, String domain) throws Exception { setState(LOGGING_IN, null); ipAddress = getMyAddress(TAG, true); if (ipAddress == null) { ImErrorInfo info = new ImErrorInfo(ImErrorInfo.WIFI_NOT_CONNECTED_ERROR, "network connection is required"); setState(DISCONNECTED, info); return; } mUserPresence = new Presence(Presence.AVAILABLE, "", null, null, Presence.CLIENT_TYPE_MOBILE); mServiceName = userName + '@' + ipAddress.getHostAddress();// + '/' + mResource; LLPresence presence = new LLPresence(mServiceName); mService = JmDNSService.create(presence, ipAddress); mService.addServiceStateListener(new LLServiceStateListener() { public void serviceNameChanged(String newName, String oldName) { debug(TAG, "Service named changed from " + oldName + " to " + newName + "."); } public void serviceClosed() { debug(TAG, "Service closed"); if (getState() != SUSPENDED) { setState(DISCONNECTED, null); } releaseLocks(); } public void serviceClosedOnError(Exception e) { debug(TAG, "Service closed on error"); ImErrorInfo info = new ImErrorInfo(ImErrorInfo.UNKNOWN_ERROR, e.getMessage()); setState(DISCONNECTED, info); releaseLocks(); } public void unknownOriginMessage(org.jivesoftware.smack.packet.Message m) { debug(TAG, "This message has unknown origin:"); debug(TAG, m.toXML()); } }); // Adding presence listener. mService.addPresenceListener(new LLPresenceListener() { public void presenceRemove(final LLPresence presence) { execute(new Runnable() { public void run() { mContactListManager.handlePresenceChanged(presence, true); } }); } public void presenceNew(final LLPresence presence) { execute(new Runnable() { public void run() { mContactListManager.handlePresenceChanged(presence, false); } }); } }); debug(TAG, "Preparing link-local service discovery"); LLServiceDiscoveryManager disco = LLServiceDiscoveryManager.getInstanceFor(mService); disco.addFeature(DeliveryReceipts.NAMESPACE); // Start listen for Link-local chats mService.addLLChatListener(new LLChatListener() { public void newChat(LLChat chat) { chat.addMessageListener(new LLMessageListener() { public void processMessage(LLChat chat, org.jivesoftware.smack.packet.Message message) { String address = message.getFrom(); ChatSession session = findOrCreateSession(address); DeliveryReceipts.DeliveryReceipt dr = (DeliveryReceipts.DeliveryReceipt) message .getExtension("received", DeliveryReceipts.NAMESPACE); if (dr != null) { debug(TAG, "got delivery receipt for " + dr.getId()); session.onMessageReceipt(dr.getId()); } if (message.getBody() == null) return; Message rec = new Message(message.getBody()); rec.setTo(mUser.getAddress()); rec.setFrom(session.getParticipant().getAddress()); rec.setDateTime(new Date()); session.onReceiveMessage(rec); if (message.getExtension("request", DeliveryReceipts.NAMESPACE) != null) { debug(TAG, "got delivery receipt request"); // got XEP-0184 request, send receipt sendReceipt(message); session.onReceiptsExpected(); } } }); } public void chatInvalidated(LLChat chat) { // TODO } }); mUser = new Contact(new XmppAddress(mServiceName), userName); // Initiate Link-local message session mService.init(); debug(TAG, "logged in"); setState(LOGGED_IN, null); } private InetAddress getMyAddress(final String serviceName, boolean doLock) { WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo connectionInfo = wifi.getConnectionInfo(); if (connectionInfo == null || connectionInfo.getBSSID() == null) { Log.w(TAG, "Not connected to wifi. This may not work."); // Get the IP the usual Java way try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress; } } } } catch (SocketException e) { Log.e(TAG, "while enumerating interfaces", e); return null; } } int ip = connectionInfo.getIpAddress(); InetAddress address; try { address = InetAddress.getByAddress(new byte[] { (byte) ((ip) & 0xff), (byte) ((ip >> 8) & 0xff), (byte) ((ip >> 16) & 0xff), (byte) ((ip >> 24) & 0xff) }); } catch (UnknownHostException e) { Log.e(TAG, "unknown host exception when converting ip address"); return null; } if (doLock) { mcLock = wifi.createMulticastLock(serviceName); mcLock.acquire(); // HIGH_PERF is only available on android-12 and above int wifiMode; try { wifiMode = (Integer) WifiManager.class.getField("WIFI_MODE_FULL_HIGH_PERF").get( null); } catch (Exception e) { wifiMode = WifiManager.WIFI_MODE_FULL; } wifiLock = wifi.createWifiLock(wifiMode, serviceName); wifiLock.acquire(); } return address; } private void releaseLocks() { if (mcLock != null) mcLock.release(); mcLock = null; if (wifiLock != null) wifiLock.release(); wifiLock = null; } public void sendReceipt(org.jivesoftware.smack.packet.Message msg) { debug(TAG, "sending XEP-0184 ack to " + msg.getFrom() + " id=" + msg.getPacketID()); org.jivesoftware.smack.packet.Message ack = new org.jivesoftware.smack.packet.Message( msg.getFrom(), msg.getType()); ack.addExtension(new DeliveryReceipts.DeliveryReceipt(msg.getPacketID())); sendPacket(ack); } void disconnected(ImErrorInfo info) { Log.w(TAG, "disconnected"); setState(DISCONNECTED, info); } protected static int parsePresence(LLPresence presence, boolean offline) { if (offline) return Presence.OFFLINE; int type = Presence.AVAILABLE; Mode rmode = presence.getStatus(); if (rmode == Mode.away) type = Presence.AWAY; else if (rmode == Mode.dnd) type = Presence.DO_NOT_DISTURB; return type; } protected static String parseAddressBase(String from) { return from.replaceFirst("/.*", ""); } protected static String parseAddressName(String from) { return from.replaceFirst("@.*", ""); } @Override public void logoutAsync() { // TODO invoke join() here? execute(new Runnable() { @Override public void run() { logout(); } }); } // Force immediate logout public synchronized void logout() { if (mService != null) { mService.close(); mService = null; } } @Override public void suspend() { execute(new Runnable() { @Override public void run() { do_suspend(); } }); } private void do_suspend() { debug(TAG, "suspend"); setState(SUSPENDED, null); logout(); } private ChatSession findOrCreateSession(String address) { ChatSession session = mSessionManager.findSession(address); if (session == null) { Contact contact = findOrCreateContact(parseAddressName(address), address); session = mSessionManager.createChatSession(contact); } return session; } Contact findOrCreateContact(String name, String address) { Contact contact = mContactListManager.getContact(address); if (contact == null) { contact = makeContact(name, address); } return contact; } private static Contact makeContact(String name, String address) { Contact contact = new Contact(new XmppAddress(address), name); return contact; } private final class XmppChatSessionManager extends ChatSessionManager { @Override public void sendMessageAsync(ChatSession session, Message message) { org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message( message.getTo().getAddress(), org.jivesoftware.smack.packet.Message.Type.chat); msg.addExtension(new DeliveryReceipts.DeliveryReceiptRequest()); msg.setBody(message.getBody()); debug(TAG, "sending packet ID " + msg.getPacketID()); message.setID(msg.getPacketID()); sendPacket(msg); } ChatSession findSession(String address) { for (Iterator<ChatSession> iter = mSessions.iterator(); iter.hasNext();) { ChatSession session = iter.next(); if (session.getParticipant().getAddress().getAddress().equals(address)) return session; } return null; } } public ChatSession findSession(String address) { return mSessionManager.findSession(address); } public ChatSession createChatSession(Contact contact) { return mSessionManager.createChatSession(contact); } public class XmppContactListManager extends ContactListManager { public XmppContactListManager () { super(); } private void do_loadContactLists() { String generalGroupName = "Buddies"; Collection<Contact> contacts = new ArrayList<Contact>(); ContactList cl = new ContactList(mUser.getAddress(), generalGroupName, true, contacts, this); notifyContactListCreated(cl); notifyContactListsLoaded(); } @Override protected void setListNameAsync(final String name, final ContactList list) { execute(new Runnable() { @Override public void run() { // TODO } }); } @Override public String normalizeAddress(String address) { return new XmppAddress(address).getBareAddress(); } @Override public void loadContactListsAsync() { execute(new Runnable() { @Override public void run() { do_loadContactLists(); } }); } private void handlePresenceChanged(LLPresence presence, boolean offline) { if (presence.getServiceName().equals(mServiceName)) return; //this is from us! // Create default lists on first presence received if (getState() != ContactListManager.LISTS_LOADED) { loadContactListsAsync(); } String name = presence.getNick(); String address = presence.getJID(); if (address == null) //sometimes with zeroconf/bonjour there may not be a JID address = presence.getServiceName(); XmppAddress xaddress = new XmppAddress(address); if (name == null) name = xaddress.getUser(); Contact contact = findOrCreateContact(name,xaddress.getAddress()); try { if (!mContactListManager.getDefaultContactList().containsContact(contact)) { mContactListManager.addContactToListAsync(xaddress.getAddress(), mContactListManager.getDefaultContactList()); notifyContactListUpdated(mContactListManager.getDefaultContactList(), ContactListListener.LIST_CONTACT_ADDED, contact); } } catch (ImException e) { LogCleaner.error(TAG, "unable to add contact to list", e); } Presence p = new Presence(parsePresence(presence, offline), presence.getMsg(), null, null, Presence.CLIENT_TYPE_DEFAULT); contact.setPresence(p); Contact[] contacts = new Contact[] { contact }; notifyContactsPresenceUpdated(contacts); } @Override protected ImConnection getConnection() { return LLXmppConnection.this; } @Override protected void doRemoveContactFromListAsync(Contact contact, ContactList list) { // TODO } @Override protected void doDeleteContactListAsync(ContactList list) { // TODO delete contact list debug(TAG, "delete contact list " + list.getName()); } @Override protected void doCreateContactListAsync(String name, Collection<Contact> contacts, boolean isDefault) { // TODO create contact list debug(TAG, "create contact list " + name + " default " + isDefault); } @Override protected void doBlockContactAsync(String address, boolean block) { // TODO block contact } private void doAddContact(String name, String address, ContactList list) { Contact contact = makeContact(name, address); if (!containsContact(contact)) notifyContactListUpdated(list, ContactListListener.LIST_CONTACT_ADDED, contact); } private void doAddContact(String name, String address) { try { doAddContact(name, address, getDefaultContactList()); } catch (ImException e) { Log.e(TAG, "Failed to add contact", e); } } @Override protected void doAddContactToListAsync(String address, ContactList list) throws ImException { debug(TAG, "add contact to " + list.getName()); // TODO } @Override public void declineSubscriptionRequest(String contact) { debug(TAG, "decline subscription"); // TODO } @Override public void approveSubscriptionRequest(String contact) { debug(TAG, "approve subscription"); // TODO } @Override public Contact createTemporaryContact(String address) { debug(TAG, "create temporary " + address); return makeContact(parseAddressName(address), address); } } @Override public void networkTypeChanged() { super.networkTypeChanged(); } @Override protected void setState(int state, ImErrorInfo error) { debug(TAG, "setState to " + state); super.setState(state, error); } public static void debug(String tag, String msg) { Log.d(tag, msg); } @Override public void handle(Callback[] arg0) throws IOException { for (Callback cb : arg0) { debug(TAG, cb.toString()); } } @Override public void reestablishSessionAsync(Map<String, String> sessionContext) { execute(new Runnable() { public void run() { do_login(); } }); } @Override public void sendHeartbeat(long heartbeatInterval) { InetAddress newAddress = getMyAddress(mServiceName, false); if (!ipAddress.equals(newAddress)) { debug(TAG, "new address, reconnect"); execute(new Runnable() { public void run() { do_suspend(); do_login(); } }); } } }
fix local link setup, and mark messages as INCOMING
src/info/guardianproject/otr/app/im/plugin/xmpp/LLXmppConnection.java
fix local link setup, and mark messages as INCOMING
<ide><path>rc/info/guardianproject/otr/app/im/plugin/xmpp/LLXmppConnection.java <ide> } <ide> mService.getLocalPresence().setStatus(mode); <ide> mService.getLocalPresence().setMsg(statusText); <add> <ide> try { <ide> mService.updatePresence(mService.getLocalPresence()); <ide> } catch (XMPPException e) { <ide> <ide> setState(LOGGING_IN, null); <ide> <del> ipAddress = getMyAddress(TAG, true); <add> mServiceName = userName + '@' + domain;// + '/' + mResource; <add> <add> ipAddress = getMyAddress(mServiceName, true); <ide> if (ipAddress == null) { <ide> ImErrorInfo info = new ImErrorInfo(ImErrorInfo.WIFI_NOT_CONNECTED_ERROR, <ide> "network connection is required"); <ide> <ide> mUserPresence = new Presence(Presence.AVAILABLE, "", null, null, <ide> Presence.CLIENT_TYPE_MOBILE); <del> <del> mServiceName = userName + '@' + ipAddress.getHostAddress();// + '/' + mResource; <ide> <ide> LLPresence presence = new LLPresence(mServiceName); <add> presence.setNick(userName); <add> presence.setJID(mServiceName); <add> presence.setServiceName(mServiceName); <ide> <ide> mService = JmDNSService.create(presence, ipAddress); <ide> mService.addServiceStateListener(new LLServiceStateListener() { <ide> rec.setTo(mUser.getAddress()); <ide> rec.setFrom(session.getParticipant().getAddress()); <ide> rec.setDateTime(new Date()); <add> <add> rec.setType(Imps.MessageType.INCOMING); <ide> session.onReceiveMessage(rec); <ide> <ide> if (message.getExtension("request", DeliveryReceipts.NAMESPACE) != null) { <ide> <ide> try { <ide> <add> <ide> if (!mContactListManager.getDefaultContactList().containsContact(contact)) <del> { <del> mContactListManager.addContactToListAsync(xaddress.getAddress(), mContactListManager.getDefaultContactList()); <del> notifyContactListUpdated(mContactListManager.getDefaultContactList(), ContactListListener.LIST_CONTACT_ADDED, contact); <add> { <add> mContactListManager.getDefaultContactList().addExistingContact(contact); <add> notifyContactListUpdated(mContactListManager.getDefaultContactList(), ContactListListener.LIST_CONTACT_ADDED, contact); <ide> } <ide> <ide> } catch (ImException e) {
JavaScript
apache-2.0
80225d97f9e346268d7376626ce134670ef7b2d9
0
numbas/editor,numbas/editor,numbas/editor
var viewModel; $(document).ready(function() { var builtinRulesets = ['basic','unitFactor','unitPower','unitDenominator','zeroFactor','zeroTerm','zeroPower','noLeadingMinus','collectNumbers','simplifyFractions','zeroBase','constantsFirst','sqrtProduct','sqrtDivision','sqrtSquare','trig','otherNumbers'] var jmeTypes = []; var forbiddenJmeTypes = ['op','name','function']; for(var type in Numbas.jme.types) { var t = Numbas.jme.types[type].prototype.type; if(t && jmeTypes.indexOf(t)==-1 && forbiddenJmeTypes.indexOf(t)==-1) { jmeTypes.push(t); } } function Question(data) { var q = this; Editor.EditorItem.apply(this); this.resources = ko.observableArray([]); this.extensions = ko.observableArray([]); this.statement = Editor.contentObservable(''); this.advice = Editor.contentObservable(''); var rulesets = this.rulesets = ko.observableArray([]); this.functions = ko.observableArray([]); this.variables = ko.observableArray([]); this.questionScope = ko.observable(); this.variableGroups = ko.observableArray([]); this.editVariableGroup = ko.observable(null); this.autoCalculateVariables = ko.observable(true); this.currentVariable = ko.observable(null); this.variablesTest = { condition: ko.observable(''), conditionError: ko.observable(false), conditionSatisfied: ko.observable(true), // was the condition satisfied when generating a preview set of values? maxRuns: ko.observable(100), totalRuns: ko.observable(0), totalErrors: ko.observable(0), totalCorrect: ko.observable(0), advice: ko.observable(''), running_time: ko.observable(3), running: ko.observable(false), time_remaining: ko.observable(0) }; this.parts = ko.observableArray([]); //for image attribute modal this.imageModal = { width: ko.observable(0), height: ko.observable(0), title: ko.observable(''), alt: ko.observable('') } //for iframe attribute modal this.iframeModal = { width: ko.observable(0), height: ko.observable(0) } this.mainTabs([ new Editor.Tab('settings','Settings','cog'), new Editor.Tab('statement','Statement','blackboard'), new Editor.Tab('variables','Variables','th-list'), new Editor.Tab('variabletesting','Variable testing','dashboard'), new Editor.Tab( 'parts', 'Parts', 'list' ), new Editor.Tab('advice','Advice','blackboard'), new Editor.Tab('extensions','Extensions & scripts','wrench'), new Editor.Tab('resources','Resources','picture'), new Editor.Tab('exams','Exams using this question','book'), new Editor.Tab('network','Other versions','link'), new Editor.Tab('history','Editing history','time') ]); if(item_json.editable) { var adviceTab = new Editor.Tab('access','Access','lock'); this.mainTabs.splice(6,0,adviceTab); } this.currentTab(this.mainTabs()[0]); this.add_to_basket = function() { Editor.add_question_to_basket(item_json.itemJSON.id); } this.saveResources = ko.computed(function() { var resources = this.resources(); var out = []; for(var i=0;i<resources.length;i++) { var res = resources[i]; if(res.progress()==1) { out.push({ pk: res.pk() }); } } return out; },this); for(var i=0;i<item_json.numbasExtensions.length;i++) { var ext = item_json.numbasExtensions[i]; ext.used = ko.observable(false); this.extensions.push(ext); } this.usedExtensions = ko.computed(function() { return this.extensions().filter(function(e){return e.used()}); },this); this.allsets = ko.computed(function() { return builtinRulesets.concat(this.rulesets().map(function(r){return r.name()})).sort(); },this); this.preamble = { css: ko.observable(''), js: ko.observable('') }; this.baseVariableGroup = new VariableGroup(this,{name:'Ungrouped variables'}); this.baseVariableGroup.fixed = true; this.allVariableGroups = ko.computed(function() { var l = this.variableGroups(); return l.concat(this.baseVariableGroup); },this); // this changes whenever there's a change to a variable name or definition, or a variables is added or removed (or similar to the functions) this.lastVariableChange = ko.computed(function() { this.variables().map(function(v) { v.definition(); v.name(); }); this.functions().map(function(f) { f.name(); f.definition(); f.parameters(); f.type(); f.language(); }); return new Date(); },this); this.variablesTest.time_remaining_display = ko.computed(function() { return this.time_remaining()+' '+Numbas.util.pluralise(this.time_remaining(),'second','seconds'); },this.variablesTest); // reset the advice whenever the condition changes or there's a change to the variables ko.computed(function() { this.variablesTest.condition(); this.lastVariableChange(); this.variablesTest.advice(''); },this); this.variableErrors = ko.computed(function() { var variables = this.variables(); for(var i=0;i<variables.length;i++) { if(variables[i].nameError() || variables[i].error()) return true; } return false; },this); this.addVariableBefore = function() { var n = q.variables.indexOf(this); var v = new Variable(q); q.variables.splice(n,0,v); } this.goToVariable = function(name) { var v = q.getVariable(name); if(!v) { return; } q.currentVariable(v); q.currentTab(q.getTab('variables')); } this.expand_all_parts = function() { q.allParts().map(function(p) { p.open(true); }); } this.collapse_all_parts = function() { q.allParts().map(function(p) { p.open(false); }); } // all parts in this question, including child parts such as gaps and steps this.allParts = ko.computed(function() { var o = []; this.parts().map(function(p) { o.push(p); if(p.type().name=='gapfill') { o = o.concat(p.gaps()); } o = o.concat(p.steps()); }); return o; },this); ko.computed(function() { if(!this.autoCalculateVariables()) return; //the ko dependency checker seems not to pay attention to what happens in the computeVariables method, so access the variable bits here to give it a prompt this.functions().map(function(v) { v.name(); v.definition(); v.parameters(); }); this.variables().map(function(v) { v.name(); v.definition(); }); this.generateVariablePreview(); },this).extend({throttle:300}); if(data) { this.load(data); } if(item_json.editable) { this.deleteResource = function(res) { q.resources.remove(res); } this.init_output(); this.save = ko.computed(function() { return { content: this.output(), extensions: this.usedExtensions().map(function(e){return e.pk}), tags: this.tags(), subjects: this.subjects().filter(function(s){return s.used()}).map(function(s){return s.pk}), topics: this.topics().filter(function(t){return t.used()}).map(function(t){return t.pk}), ability_levels: this.used_ability_levels().map(function(al){return al.pk}), resources: this.saveResources(), metadata: this.metadata() }; },this); this.init_save(); this.section_tasks = { 'settings': [ Editor.nonempty_task('Give the question a name.',this.name), Editor.nonempty_task('Fill out the question description.',this.description), Editor.nonempty_task('Select a licence defining usage rights.',this.licence) ], 'statement': [ Editor.nonempty_task('Write a question statement.',this.statement) ], 'parts': [ {text: 'Create at least one part.', done: ko.computed(function(){ return this.parts().length>0 },this)} ], 'advice': [ Editor.nonempty_task('Write a worked solution to the question.',this.advice) ] } this.init_tasks(); } if(window.history !== undefined) { this.load_state(); var state = window.history.state || {}; if('currentVariable' in state) { var variables = this.variables(); for(var i=0;i<variables.length;i++) { var variable = variables[i]; if(variable.name().toLowerCase()==state.currentVariable) { this.currentVariable(variable); break; } } } Editor.computedReplaceState('currentVariable',ko.computed(function(){ var v = this.currentVariable(); if(v) { return v.name().toLowerCase(); } else { return undefined; } },this)); } } Question.prototype = { versionJSON: function() { var obj = { id: this.id, JSONContent: this.toJSON(), numbasVersion: Editor.numbasVersion, name: this.name(), author: item_json.itemJSON.author, copy_of: item_json.itemJSON.copy_of, extensions: this.usedExtensions().map(function(e){return e.pk}), tags: this.tags(), resources: this.saveResources(), metadata: this.metadata() }; if(item_json.editable) { obj.public_access = this.public_access(); } return obj; }, deleteItem: function(q,e) { if(window.confirm('Really delete this question?')) { $(e.target).find('form').submit(); } }, addRuleset: function() { this.rulesets.push(new Ruleset(this)); }, addFunction: function(q,e,n) { var f = new CustomFunction(this); if(n!=undefined) this.functions.splice(n,0,f); else this.functions.push(f); return f; }, addVariable: function(q,e,n) { var v = new Variable(this); if(n!=undefined) this.variables.splice(n,0,v); else this.variables.push(v); this.currentVariable(v); return v; }, addVariableGroup: function() { var vg = new VariableGroup(this); this.variableGroups.push(vg); return vg; }, getVariable: function(name) { name = name.toLowerCase(); var variables = this.variables(); for(var i = 0; i<variables.length;i++) { if(variables[i].name().toLowerCase() == name) { return variables[i]; } } }, getVariableGroup: function(name) { var groups = this.allVariableGroups(); for(var i=0;i<groups.length;i++) { if(groups[i].name()==name) { return groups[i]; } } var vg = new VariableGroup(this,{name:name}); this.variableGroups.push(vg); return vg; }, addPart: function() { var p = new Part(this,null,this.parts); this.parts.push(p); return p; }, loadPart: function(data) { var p = new Part(this,null,this.parts,data); this.parts.push(p); return p; }, getPart: function(path) { return this.parts()[0]; var re_path = /^p(\d+)(?:g(\d+)|s(\d+))?$/; var m = re_path.exec(path); var i = parseInt(m[1]); var p = this.parts()[i]; if(m[2]) { var g = parseInt(m[2]); return p.gaps()[g]; } else if(m[3]) { var s = parseInt(m[3]); return p.steps()[s]; } else { return p; } }, generateVariablePreview: function() { if(!Numbas.jme) { var q = this; Numbas.init = function() { q.generateVariablePreview(); }; return; } this.functions().map(function(f) { f.error(''); }); this.variables().map(function(v) { if(!v.locked.peek()) { v.error(''); v.value(''); } }); var prep = this.prepareVariables(); this.variables().map(function(v) { var name = v.name().toLowerCase(); if(prep.todo[name]) { v.dependencies(prep.todo[name].vars); } else { v.dependencies([]); } }); var conditionSatisfied = false; var results; var runs = 0; var maxRuns = this.variablesTest.maxRuns(); while(runs<maxRuns && !conditionSatisfied) { var results = this.computeVariables(prep); conditionSatisfied = results.conditionSatisfied; runs += 1; } this.variablesTest.conditionSatisfied(conditionSatisfied); // fill in observables if(conditionSatisfied) { this.variables().map(function(v) { if(v.locked.peek()) { return; } var name = v.name().toLowerCase(); var result = results.variables[name]; if(!result) { v.value(null); return; } if('value' in result) { v.value(result.value); } if('error' in result) { v.error(result.error); } }); } this.questionScope(results.scope); }, // get everything ready to compute variables - make functions, and work out dependency graph prepareVariables: function() { var jme = Numbas.jme; var scopes = [jme.builtinScope]; var extensions = this.extensions().filter(function(e){return e.used()}); for(var i=0;i<extensions.length;i++) { var extension = extensions[i].location; if(extension in Numbas.extensions && 'scope' in Numbas.extensions[extension]) { scopes.push(Numbas.extensions[extension].scope); } } var scope = new jme.Scope(scopes); //create functions this.functions().map(function(f) { try { var fn = { name: f.name().toLowerCase(), definition: f.definition(), language: f.language(), outtype: f.type(), parameters: f.parameters().map(function(p) { if(!p.name()) { throw(new Error('A parameter is unnamed.')); } return { name: p.name(), type: p.type() } }) }; var cfn = jme.variables.makeFunction(fn,scope); if(scope.functions[cfn.name]===undefined) scope.functions[cfn.name] = []; scope.functions[cfn.name].push(cfn); } catch(e) { f.error(e.message); } }); //make structure of variables to evaluate var todo = {} this.variables().map(function(v) { var name = v.name().toLowerCase(); if(!v.name()) { return; } if(v.definitionError()) { v.error(v.definitionError()); return; } if(!v.definition()) { todo[name] = { v: v, tree: null, vars: [] }; return; } if(v.locked.peek()) { scope.variables[v.name()] = v.value(); } try { var tree = jme.compile(v.definition(),scope,true); var vars = jme.findvars(tree); v.error(''); } catch(e) { v.error(e.message); return; } todo[name] = { v: v, tree: tree, vars: vars } }); var condition; try { condition = Numbas.jme.compile(this.variablesTest.condition()); this.variablesTest.conditionError(false); } catch(e) { this.variablesTest.conditionError(e.message); condition = null; } return { scope: scope, todo: todo, condition: condition }; }, /* Given a list of variable names, return a list of names of the dependencies of those variables which have some random element */ randomDependencies: function(vars) { var d = this.prepareVariables(); var scope = d.scope; var todo = d.todo; var deps = Numbas.jme.variables.variableDependants(todo,vars); var randoms = []; for(var name in deps) { if(Numbas.jme.isRandom(deps[name].tree,scope)) { randoms.push(name); } } return randoms; }, computeVariables: function(prep) { var result = {variables: {}}; var jme = Numbas.jme; var scope = result.scope = new jme.Scope([prep.scope]); var todo = prep.todo; function computeVariable(name) { try { var value = jme.variables.computeVariable(name,todo,scope); result.variables[name] = {value: value}; } catch(e) { result.variables[name] = {error: e.message}; result.error = true; } } if(prep.condition) { var condition_vars = jme.findvars(prep.condition); condition_vars.map(function(name) { computeVariable(name); }); try { result.conditionSatisfied = Numbas.jme.evaluate(prep.condition,scope).value; } catch(e) { this.variablesTest.conditionError(e.message); result.conditionSatisfied = false; return result; } } else { result.conditionSatisfied = true; } if(result.conditionSatisfied) { //evaluate variables for(var x in todo) { computeVariable(x); } } return result; }, cancelVariablesTest: function() { this.variablesTest.cancel = true; }, testVariables: function() { var running_time = parseFloat(this.variablesTest.running_time()); var start = new Date() var end = start.getTime()+running_time*1000; var runs = 0; var errors = 0; var correct = 0; var q = this; var prep = this.prepareVariables(); this.variablesTest.time_remaining(running_time); this.variablesTest.cancel = false; this.variablesTest.running(true); function finish() { q.variablesTest.running(false); var timeTaken = ((new Date())-start)/1000; var timePerRun = timeTaken/runs; q.variablesTest.totalRuns(runs); q.variablesTest.totalErrors(errors); q.variablesTest.totalCorrect(correct); var probPass = correct/runs; var probFail = 1-probPass; var probError = errors/runs; // calculate 95% confidence interval for probPass var z = 1.9599639845400545; var n = runs; var p = probPass; var confidence = { lower: (1/(1+z*z/n))*(p+z*z/(2*n)-z*Math.sqrt(p*(1-p)/n+z*z/(4*n*n))), upper: (1/(1+z*z/n))*(p+z*z/(2*n)+z*Math.sqrt(p*(1-p)/n+z*z/(4*n*n))) }; var suggestedRuns = Math.ceil(Math.log(1/1000)/Math.log(probFail)); if(suggestedRuns<1) { suggestedRuns = 1; } var probSucceedInTime = 1-Math.pow(probFail,1/timePerRun); function round(n,precision) { precision = precision || 2; return Numbas.math.niceNumber(n,{precisionType:'sigfig',precision:3}); } if(correct==0) { q.variablesTest.advice('The condition was never satisfied. That means it\'s either really unlikely or impossible.'); } else { q.variablesTest.advice( '<p>The condition was satisfied <strong>'+round(probPass*100)+'%</strong> of the time, over <strong>'+runs+'</strong> runs, with <strong>'+round(probError*100)+'%</strong> of runs aborted due to errors. The mean computation time for one run was <strong>'+round(timePerRun)+'</strong> seconds.</p>'+ '<p>Successfully generating a set of variables will take on average <strong>'+round(timePerRun*(1/probPass))+'</strong> seconds on this device.</p>'+ '<p>In order to fail at most 1 in every 1000 times the question is run, you should set the max. runs to <strong>'+suggestedRuns+'</strong>, taking at most <strong>'+round(timePerRun*suggestedRuns)+'</strong> seconds on this device.</p>'+ '<p>If you want to allow at most <strong>1 second</strong> to generate a set of variables, i.e. set max. runs to <strong>'+round(1/timePerRun)+'</strong>, this device\'s chance of succeeding is <strong>'+round(probSucceedInTime*100)+'%</strong>.</p>' ); } } var ot = Math.ceil(running_time); function test() { var t = new Date(); if(q.variablesTest.cancel || t>end) { finish(); } else { var diff = Math.ceil((end-t)/1000); if(diff!=ot) { ot = diff; q.variablesTest.time_remaining(diff); } try { runs += 1; var run = q.computeVariables(prep); } catch(e) { q.variablesTest.running(false); return; } if(run.conditionSatisfied) { correct += 1; } if(run.error) { errors += 1; } setTimeout(test,1); } } test(); }, toJSON: function() { var rulesets = {}; this.rulesets().map(function(r){ rulesets[r.name()] = r.sets(); }); var variables = {}; this.variables().map(function(v) { variables[v.name()] = v.toJSON(); }); var ungrouped_variables = this.baseVariableGroup.variables().map(function(v){ return v.name(); }); var groups = []; this.variableGroups().map(function(g) { groups.push({ name: g.name(), variables: g.variables().map(function(v){return v.name()}) }); }); var functions = {}; this.functions().map(function(f) { functions[f.name()] = f.toJSON(); }); return { name: this.realName(), tags: this.tags(), metadata: this.metadata(), statement: this.statement(), advice: this.advice(), rulesets: rulesets, extensions: this.extensions().filter(function(e){return e.used()}).map(function(e){return e.location}), variables: variables, variablesTest: { condition: this.variablesTest.condition(), maxRuns: this.variablesTest.maxRuns() }, ungrouped_variables: ungrouped_variables, variable_groups: groups, functions: functions, preamble: { js: this.preamble.js(), css: this.preamble.css() }, parts: this.parts().map(function(p){return p.toJSON();}) } }, reset: function() { this.resources([]); this.realtags([]); this.rulesets([]); this.functions([]); this.variables([]); this.variableGroups([]); this.baseVariableGroup.variables([]); this.parts([]); this.extensions().map(function(e){ e.used(false); }); }, load: function(data) { Editor.EditorItem.prototype.load.apply(this,[data]); var q = this; if('extensions' in data) { this.extensions().map(function(e) { if(data.extensions.indexOf(e.location)>=0) e.used(true); }); } if('resources' in data) { data.resources.map(function(rd) { this.resources.push(new Editor.Resource(rd)); },this); } contentData = data.JSONContent; tryLoad(contentData,['name','statement','advice'],this); if('variables' in contentData) { for(var x in contentData.variables) { var v = new Variable(this,contentData.variables[x]); this.variables.push(v); } } if('variable_groups' in contentData) { contentData.variable_groups.map(function(gdata) { var vg = q.getVariableGroup(gdata.name); gdata.variables.map(function(variable_name) { var v = q.getVariable(variable_name); if(v) { vg.variables.push(v); q.baseVariableGroup.variables.remove(v); } }); }); } if('ungrouped_variables' in contentData) { contentData.ungrouped_variables.map(function(variable_name) { var v = q.getVariable(variable_name); if(v) { q.baseVariableGroup.variables.remove(v); q.baseVariableGroup.variables.push(v); } }); } this.selectFirstVariable(); if('variablesTest' in contentData) { tryLoad(contentData.variablesTest,['condition','maxRuns'],this.variablesTest); } if('functions' in contentData) { for(var x in contentData.functions) { contentData.functions[x].name = x; this.functions.push(new CustomFunction(this,contentData.functions[x])); } } if('preamble' in contentData) { tryLoad(contentData.preamble,['css','js'],this.preamble); } if('rulesets' in contentData) { for(var x in contentData.rulesets) { this.rulesets.push(new Ruleset(this,{name: x, sets:contentData.rulesets[x]})); } } if('parts' in contentData) { contentData.parts.map(function(pd) { this.loadPart(pd); },this); } try{ this.tags(data.tags); } catch(e) { this.tags([]); } }, selectFirstVariable: function() { if(this.variables().length) { var groups = this.allVariableGroups(); for(var i=0;i<groups.length;i++) { if(groups[i].variables().length) { this.currentVariable(groups[i].variables()[0]); return; } } } this.currentVariable(null); }, insertImage: function(image) { $('#imagePickModal').modal('hide'); var ed = viewModel.currentTinyMCE; if(!ed) { return; } var name = image.name(); var html; switch(image.filetype()) { case 'html': html = '<div><iframe src="'+image.url()+'"></div>'; break; default: html = '<img src="'+image.url()+'">'; } ed.execCommand('mceInsertContent',false,html); }, changeImageAttributes: function() { $(this.imageModal.selectedNode) .css({ width: this.imageModal.width(), height: this.imageModal.height() }); $(this.imageModal.selectedNode) .removeAttr('data-mce-style') $(this.imageModal.selectedNode) .attr('alt',this.imageModal.alt()) $(this.imageModal.selectedNode) .attr('title',this.imageModal.title()) ; $('#imageAttributeModal').modal('hide'); var ed = viewModel.currentTinyMCE; ed.fire('change'); }, changeIframeAttributes: function() { $(this.iframeModal.selectedNode) .css({ width: this.iframeModal.width(), height: this.iframeModal.height() }) .removeAttr('data-mce-style') ; $('#iframeAttributeModal').modal('hide'); var ed = viewModel.currentTinyMCE; ed.onChange.dispatch(); } }; Question.prototype.__proto__ = Editor.EditorItem.prototype; function Ruleset(exam,data) { this.name = ko.observable(''); this.sets = ko.observableArray([]); this.allsets = exam.allsets; this.remove = function() { exam.rulesets.remove(this); }; if(data) this.load(data); } Ruleset.prototype = { load: function(data) { var ruleset = this; this.name(data.name); data.sets.map(function(set){ ruleset.sets.push(set); }); } }; var re_name = /^{?((?:(?:[a-zA-Z]+):)*)((?:\$?[a-zA-Z_][a-zA-Z0-9_]*'*)|\?)}?$/i; function VariableGroup(q,data) { var vg = this; this.fixed = false; this.name = ko.observable('Unnamed group'); this.isEditing = ko.computed({ write: function(v) { if(v) { q.editVariableGroup(vg); } else if(q.editVariableGroup()==vg) { q.editVariableGroup(null); } }, read: function() { return q.editVariableGroup()==vg; } },this); this.endEdit = function() { vg.isEditing(false); } this.displayName = ko.computed(function() { return this.name() ? this.name() : 'Unnamed group' },this); this.variables = ko.observableArray([]); ko.computed(function() { vg.variables().map(function(v) { v.group(vg); }); },this); this.receivedVariables = ko.observableArray([]); ko.computed(function() { var received = this.receivedVariables(); if(received.length) { this.variables(this.variables().concat(received)); this.receivedVariables([]); } },this); this.addVariable = function() { var v = q.addVariable(); this.variables.push(v); return v; } if(data) { tryLoad(data,['name'],this); } this.remove = function() { q.variableGroups.remove(this); this.variables().map(function(v) { q.baseVariableGroup.variables.push(v); }); this.variables([]); } } VariableGroup.prototype = { sort: function() { this.variables(this.variables().sort(function(a,b){ a = a.name().toLowerCase(); b = b.name().toLowerCase(); return a>b ? 1 : a==b ? 0 : -1; })); } } function Variable(q,data) { this.question = q; this._name = ko.observable(''); this.name = ko.computed({ read: function() { return this._name().trim(); }, write: function(v) { return this._name(v); } },this); this.group = ko.observable(null); this.nameError = ko.computed(function() { var name = this.name(); if(name=='') return ''; var variables = q.variables(); for(var i=0;i<variables.length;i++) { var v = variables[i]; if(v!=this && v.name().toLowerCase()==name.toLowerCase()) return 'There\'s already a variable with this name.'; } if(!re_name.test(name)) { return 'This variable name is invalid.'; } return ''; },this); this.description = ko.observable(''); this.templateType = ko.observable(this.templateTypes[0]); function InexhaustibleList() { var _arr = ko.observableArray([]); function addValue(v) { v = v || ''; var _obs = ko.observable(v); var obj; var obs = ko.computed({ read: function() { return _obs(); }, write: function(v) { var arr = _arr(); if(v && obj==arr[arr.length-1]) { addValue(''); } return _obs(v); } }); function onBlur() { var arr = _arr(); if(arr.indexOf(this)<arr.length-1 && !this.value()) _arr.remove(obj); } obj = {value: obs, onBlur: onBlur}; _arr.push(obj); return obs; } addValue(); var arr = ko.computed({ read: function() { return _arr().slice(0,-1).map(function(v){return v.value()}); }, write: function(a) { _arr([]); for(var i=0;i<a.length;i++) { addValue(a[i]); } addValue(); } }); arr.edit = _arr; return arr; } this.templateTypeValues = { 'anything': { definition: ko.observable('') }, 'number': { value: ko.observable(0) }, 'range': { min: ko.observable(0), max: ko.observable(1), step: ko.observable(1) }, 'randrange': { min: ko.observable(0), max: ko.observable(1), step: ko.observable(1) }, 'string': { value: ko.observable('') }, 'long string': { value: ko.observable('') }, 'list of numbers': { commaValue: ko.observable('') }, 'list of strings': { values: InexhaustibleList() }, 'json': { value: ko.observable(''), prettyPrint: function() { var v = this.templateTypeValues.json.value(); try { var data = JSON.parse(v); this.templateTypeValues.json.value(JSON.stringify(data,null,4)); } catch(e) { } } } }; this.editDefinition = this.templateTypeValues['anything'].definition; this.templateTypeValues['list of numbers'].values = ko.computed(function() { var commaValue = this.commaValue(); if(!commaValue.trim()) return []; var numbers = commaValue.split(/\s+|\s*,\s*/g); numbers = numbers .map(function(n) { return parseFloat(n); }) .filter(function(n) { return !isNaN(n); }) ; return numbers; },this.templateTypeValues['list of numbers']); this.definitionError = ko.observable(null); this.definition = ko.computed({ read: function() { this.definitionError(null); var templateType = this.templateType().id; var val = this.templateTypeValues[templateType]; var treeToJME = Numbas.jme.display.treeToJME; var wrapValue = Numbas.jme.wrapValue; try { switch(templateType) { case 'anything': return val.definition()+''; case 'number': var n = parseFloat(val.value()); if(isNaN(n)) { throw("Value is not a number"); } return treeToJME({tok: wrapValue(parseFloat(val.value()))}); case 'range': var min = parseFloat(val.min()); var max = parseFloat(val.max()); var step = parseFloat(val.step()); if(isNaN(min)) { throw('Minimum value is not a number'); } else if(isNaN(max)) { throw('Maximum value is not a number'); } else if(isNaN(step)) { throw("Step value is not a number"); } var tree = Numbas.jme.compile('a..b#c'); tree.args[0].args[0] = {tok: wrapValue(parseFloat(val.min()))}; tree.args[0].args[1] = {tok: wrapValue(parseFloat(val.max()))}; tree.args[1] = {tok: wrapValue(parseFloat(val.step()))}; return treeToJME(tree); case 'randrange': var min = parseFloat(val.min()); var max = parseFloat(val.max()); var step = parseFloat(val.step()); if(isNaN(min)) { throw('Minimum value is not a number'); } else if(isNaN(max)) { throw('Maximum value is not a number'); } else if(isNaN(step)) { throw("Step value is not a number"); } var tree = Numbas.jme.compile('random(a..b#c)'); tree.args[0].args[0].args[0] = {tok: wrapValue(parseFloat(val.min()))}; tree.args[0].args[0].args[1] = {tok: wrapValue(parseFloat(val.max()))}; tree.args[0].args[1] = {tok: wrapValue(parseFloat(val.step()))}; return treeToJME(tree); case 'string': case 'long string': return treeToJME({tok: wrapValue(val.value())}); case 'list of numbers': case 'list of strings': return treeToJME({tok: wrapValue(val.values())}); case 'json': JSON.parse(val.value()); var json = treeToJME({tok: wrapValue(val.value())}); return 'json_decode(safe('+json+'))'; } } catch(e) { this.definitionError(e); return; } } },this); this.dependencies = ko.observableArray([]); this.isDependency = ko.computed(function() { var currentVariable = q.currentVariable(); if(!currentVariable) return false; return currentVariable.dependencies().contains(this.name().toLowerCase()); },this); this.dependenciesObjects = ko.computed(function() { var deps = this.dependencies(); return this.dependencies().map(function(name) { var obj = q.getVariable(name); if(obj) { name = obj.name(); } var out = { name: name, obj: obj, notdefined: !obj, title: !obj ? 'Not defined. Click to add this variable.' : '', setCurrent: function() { if(obj) { q.currentVariable(obj); } else { var v = q.addVariable(); v.name(name); q.baseVariableGroup.variables.push(v); } } }; return out; }); },this); this.usedIn = ko.computed(function() { var v = this; return q.variables().filter(function(v2) { return v2.dependencies().contains(v.name().toLowerCase()); }); },this); this.value = ko.observable(''); this.thisLocked = ko.observable(false); this.locked = ko.computed(function() { return this.usedIn().some(function(v){return v.locked()}) || this.thisLocked(); },this); this.error = ko.observable(''); this.anyError = ko.computed(function() { if(this.question.variablesTest.conditionError()) { return "Error in testing condition"; } else if(!(this.question.variablesTest.conditionSatisfied())) { return "Testing condition not satisfied"; } else { return this.error(); } },this); this.display = ko.computed(function() { var v; if(this.anyError()) { return this.anyError(); } else if(v = this.value()) { switch(v.type) { case 'string': return Numbas.util.escapeHTML(v.value); case 'list': return 'List of '+v.value.length+' '+Numbas.util.pluralise(v.value.length,'item','items'); case 'html': if(v.value.length==1 && v.value[0].tagName=='IMG') { var src = v.value[0].getAttribute('src'); return '<img src="'+src+'" title="'+src+'">'; } return 'HTML node'; default: return Numbas.jme.display.treeToJME({tok:v}); } } else { return ''; } },this); this.remove = function() { q.variables.remove(this); this.group().variables.remove(this); if(this==q.currentVariable()) { q.selectFirstVariable(); } }; if(data) this.load(data); } Variable.prototype = { templateTypes: [ {id: 'anything', name: 'JME code'}, {id: 'number', name: 'Number'}, {id: 'range', name: 'Range of numbers'}, {id: 'randrange', name: 'Random number from a range'}, {id: 'string', name: 'Short text string'}, {id: 'long string', name: 'Long text string'}, {id: 'list of numbers', name: 'List of numbers'}, {id: 'list of strings', name: 'List of short text strings'}, {id: 'json', name: 'JSON data'} ], load: function(data) { tryLoad(data,['name','description'],this); if('templateType' in data) { for(var i=0;i<this.templateTypes.length;i++) { if(this.templateTypes[i].id==data.templateType) { this.templateType(this.templateTypes[i]); break; } } } if('definition' in data) { this.definitionToTemplate(data.definition); } this.question.baseVariableGroup.variables.push(this); }, toJSON: function() { var obj = { name: this.name(), group: this.group() ? this.group().name() : null, definition: this.definition(), description: this.description(), templateType: this.templateType().id, } return obj; }, definitionToTemplate: function(definition) { var templateType = this.templateType().id; var templateTypeValues = this.templateTypeValues[templateType]; try { var tree = Numbas.jme.compile(definition); switch(templateType) { case 'anything': templateTypeValues.definition(definition); break; case 'number': templateTypeValues.value(Numbas.jme.evaluate(definition,Numbas.jme.builtinScope).value); break; case 'range': var rule = new Numbas.jme.display.Rule('?;a..?;b#?;c',[]); var m = rule.match(tree); templateTypeValues.min(Numbas.jme.evaluate(m.a,Numbas.jme.builtinScope).value); templateTypeValues.max(Numbas.jme.evaluate(m.b,Numbas.jme.builtinScope).value); templateTypeValues.step(Numbas.jme.evaluate(m.c,Numbas.jme.builtinScope).value); break; case 'randrange': var rule = new Numbas.jme.display.Rule('random(?;a..?;b#?;c)',[]); var m = rule.match(tree); templateTypeValues.min(Numbas.jme.evaluate(m.a,Numbas.jme.builtinScope).value); templateTypeValues.max(Numbas.jme.evaluate(m.b,Numbas.jme.builtinScope).value); templateTypeValues.step(Numbas.jme.evaluate(m.c,Numbas.jme.builtinScope).value); break; case 'string': case 'long string': templateTypeValues.value(tree.tok.value); break; case 'list of numbers': templateTypeValues.commaValue(tree.args.map(function(t){return Numbas.jme.evaluate(t,Numbas.jme.builtinScope).value}).join(' , ')); break; case 'list of strings': templateTypeValues.values(tree.args.map(function(t){return t.tok.value})); case 'json': templateTypeValues.value(tree.args[0].tok.value); } } catch(e) { console.log(e); } }, toggleLocked: function(v,e) { this.thisLocked(!this.thisLocked()); e.preventDefault(); } } function CustomFunction(q,data) { this.name = ko.observable(''); this.types = jmeTypes; this.parameters = ko.observableArray([]) this.type = ko.observable('number'); this.definition = ko.observable(''); this.languages = ['jme','javascript']; this.language = ko.observable('jme'); this.error = ko.observable(''); this.remove = function() { if(confirm("Remove this function?")) q.functions.remove(this); }; if(data) this.load(data); } CustomFunction.prototype = { load: function(data) { var f = this; tryLoad(data,['name','type','definition','language'],this); if('parameters' in data) { data.parameters.map(function(p) { f.parameters.push(new FunctionParameter(f,p[0],p[1])); }); } }, toJSON: function() { var parameters = this.parameters().map(function(p) { return [p.name(), p.type()]; }); return { parameters: parameters, type: this.type(), language: this.language(), definition: this.definition() }; }, addParameter: function() { this.parameters.push(new FunctionParameter(this,'','number')); } }; function FunctionParameter(f,name,type) { this.name = ko.observable(name); this.type = ko.observable(type); this.remove = function() { f.parameters.remove(this); } }; function Script(name,displayName,defaultOrder,helpURL) { this.name = name; this.orderOptions = [ {niceName: 'instead of', value: 'instead'}, {niceName: 'after', value: 'after'}, {niceName: 'before', value: 'before'} ]; this.orderItem = ko.observable(this.orderOptions[0]); this.order = ko.computed({ read: function() { return this.orderItem().value; }, write: function(value) { for(var i=0;i<this.orderOptions.length;i++) { if(this.orderOptions[i].value==value) { return this.orderItem(this.orderOptions[i]); } } } },this); this.order(defaultOrder); this.displayName = displayName; this.script = ko.observable(''); this.helpURL = helpURL; this.active = ko.computed(function() { return this.script().trim().length>0; },this); } function Part(q,parent,parentList,data) { var p = this; this.q = q; this.prompt = Editor.contentObservable(''); this.parent = ko.observable(parent); this.parentList = parentList; this.open = ko.observable(true); this.toggleOpen = function() { p.open(!p.open()); } this.types = partTypes.map(function(data){return new PartType(p,data);}); this.isRootPart = ko.computed(function() { return !this.parent(); },this); this.isGap = ko.computed(function(){ return this.parent() && this.parent().type().name=='gapfill' && !this.parent().steps().contains(this); },this); this.isStep = ko.computed(function() { return this.parent() && this.parent().steps().contains(this); },this); var nonGapTypes = ['information','gapfill']; this.availableTypes = ko.computed(function() { var nonStepTypes = ['gapfill']; if(this.isGap()) return this.types.filter(function(t){return nonGapTypes.indexOf(t.name)==-1}); else if(this.isStep()) return this.types.filter(function(t){return nonStepTypes.indexOf(t.name)==-1}); else return this.types; },this); this.type = ko.observable(this.availableTypes()[0]); this.canBeReplacedWithGap = ko.computed(function() { return !(this.isGap() || this.isStep() || nonGapTypes.indexOf(this.type().name)>=0); },this); this.indexLabel = ko.computed(function() { var i = this.parentList.indexOf(this); if(this.isGap() || this.isStep()) { i = i; } else { i = Numbas.util.letterOrdinal(i); } return i; },this); this.levelName = ko.computed(function() { return this.isGap() ? 'gap' : this.isStep() ? 'step' : 'part'; },this); this.header = ko.computed(function() { if(this.isGap()) { return 'Gap '+this.indexLabel()+'. '; } else if(this.isStep()) { return 'Step '+this.indexLabel()+'. '; } else if(this.isRootPart()) { return 'Part '+this.indexLabel()+') '; } },this); this.path = ko.computed(function() { var i = Math.max(this.parentList.indexOf(this),0); if(this.isGap()) { return this.parent().path()+'g'+i; } else if(this.isStep()) { return this.parent().path()+'s'+i; } else { return 'p'+i; } },this); this.nicePath = ko.computed(function() { return Numbas.util.capitalise(Numbas.util.nicePartName(this.path())); },this); this.tabs = ko.computed(function() { var tabs = []; if(!this.isGap()) tabs.push(new Editor.Tab('prompt','Prompt','blackboard')); if(this.type().has_marks) tabs.push(new Editor.Tab('marking','Marking','pencil')); tabs = tabs.concat(this.type().tabs); tabs.push(new Editor.Tab('scripts','Scripts','wrench')); tabs.push(new Editor.Tab('adaptivemarking','Adaptive marking','transfer')); return tabs; },this); this.realCurrentTab = ko.observable(this.tabs()[0]); this.currentTab = ko.computed({ read: function() { if(this.tabs().indexOf(this.realCurrentTab())==-1) { this.realCurrentTab(this.tabs()[0]); return this.tabs()[0]; } else return this.realCurrentTab(); }, write: this.realCurrentTab },this); this.marks = ko.observable(1); this.realMarks = ko.computed(function() { switch(this.type().name) { case 'information': case 'gapfill': case 'm_n_x': case 'm_n_2': case '1_n_2': return 0; default: return this.marks(); } },this); this.steps = ko.observableArray([]); this.stepsPenalty = ko.observable(0); this.gaps = ko.observableArray([]); this.addGap = function() { var gap = new Part(p.q,p,p.gaps); p.gaps.push(gap); } this.showCorrectAnswer = ko.observable(true); this.variableReplacements = ko.observableArray([]); this.addVariableReplacement = function() { p.variableReplacements.push(new VariableReplacement(p)); } this.deleteVariableReplacement = function(vr) { p.variableReplacements.remove(vr); } this.variableReplacementStrategies = [ {name: 'originalfirst', niceName: 'Try without replacements first'}, {name: 'alwaysreplace', niceName: 'Always replace variables'} ]; this.variableReplacementStrategy = ko.observable(this.variableReplacementStrategies[0]) this.replacementRandomDependencies = ko.computed(function() { var names = this.variableReplacements().map(function(vr) {return vr.variable()}); var randomDependencies = this.q.randomDependencies(names); return randomDependencies; },this); this.scripts = [ new Script('constructor','When the part is created','after','http://numbas-editor.readthedocs.io/en/latest/question/reference.html#term-when-the-part-is-created'), new Script('mark','Mark student\'s answer','instead','http://numbas-editor.readthedocs.io/en/latest/question/reference.html#term-mark-student-s-answer'), new Script('validate','Validate student\'s answer','instead','http://numbas-editor.readthedocs.io/en/latest/question/reference.html#term-validate-student-s-answer') ]; this.types.map(function(t){p[t.name] = t.model}); if(data) this.load(data); } Part.prototype = { copy: function() { var data = this.toJSON(); var p = new Part(this.q,this.parent(),this.parentList,data); this.parentList.push(p); p.scrollTo(); }, scrollTo: function() { var p = this; setTimeout(function() {window.scrollTo(0,$('.part[data-path="'+p.path()+'"]').offset().top-10)},0); }, replaceWithGapfill: function() { var gapFill = new Part(this.q,this.parent(),this.parentList); gapFill.setType('gapfill'); this.parentList.splice(this.parentList.indexOf(this),1,gapFill); gapFill.gaps.push(this); this.parentList = gapFill.gaps; this.parent(gapFill); gapFill.prompt(this.prompt()+'\n<p>[[0]]</p>'); this.prompt(''); gapFill.steps(this.steps()); gapFill.steps().map(function(step){ step.parent(gapFill); step.parentList = gapFill.steps; }); this.steps([]); }, canMove: function(direction) { var parentList = ko.utils.unwrapObservable(this.parentList); switch(direction) { case 'up': return parentList.indexOf(this)>0; case 'down': return parentList.indexOf(this)<parentList.length-1; } }, addStep: function() { var step = new Part(this.q,this,this.steps); this.steps.push(step); }, remove: function() { if(confirm("Remove this part?")) { this.parentList.remove(this); } }, moveUp: function() { var i = this.parentList.indexOf(this); if(i>0) { this.parentList.remove(this); ko.tasks.runEarly(); this.parentList.splice(i-1,0,this); this.scrollTo(); } }, moveDown: function() { var i = this.parentList.indexOf(this); this.parentList.remove(this); ko.tasks.runEarly(); this.parentList.splice(i+1,0,this); this.scrollTo(); }, setType: function(name) { name = name.toLowerCase(); for(var i=0;i<this.types.length;i++) { if(this.types[i].name == name) { this.type(this.types[i]); return; } } }, toJSON: function() { var o = { type: this.type().name, marks: this.realMarks(), showCorrectAnswer: this.showCorrectAnswer(), scripts: {}, variableReplacements: this.variableReplacements().map(function(vr){return vr.toJSON()}), variableReplacementStrategy: this.variableReplacementStrategy().name }; if(this.prompt()) o.prompt = this.prompt(); if(this.steps().length) { o.stepsPenalty = this.stepsPenalty(), o.steps = this.steps().map(function(s){return s.toJSON();}); } this.scripts.map(function(s) { if(s.active()) { o.scripts[s.name] = { script: s.script(), order: s.order() }; } }); try{ this.type().toJSON(o); }catch(e) { console.log(e); console.log(e.stack); throw(e); } return o; }, load: function(data) { var p = this; for(var i=0;i<this.types.length;i++) { if(this.types[i].name == data.type.toLowerCase()) this.type(this.types[i]); } tryLoad(data,['marks','prompt','stepsPenalty','showCorrectAnswer'],this); if(data.steps) { var parentPart = this.isGap() ? this.parent : this; data.steps.map(function(s) { this.steps.push(new Part(this.q,this,this.steps,s)); },parentPart); } if(data.scripts) { for(var name in data.scripts) { for(var i=0;i<this.scripts.length;i++) { if(this.scripts[i].name==name) { tryLoad(data.scripts[name],['script','order'],this.scripts[i]); break; } } } } p.variableReplacementStrategies.map(function(s) { if(s.name==data.variableReplacementStrategy) { p.variableReplacementStrategy(s); } }); if(data.variableReplacements) { data.variableReplacements.map(function(d) { var vr = new VariableReplacement(p,d); p.variableReplacements.push(vr); }); } try{ this.type().load(data); }catch(e){ console.log(e); console.log(e.stack); throw(e); } } }; function VariableReplacement(part,data) { this.part = part; this.variable = ko.observable(''); this.replacement = ko.observable(null); this.must_go_first = ko.observable(false); this.availableParts = ko.computed(function() { var p = this.part return p.q.allParts().filter(function(p2){ return p!=p2; }); },this); if(data) { this.load(data); } } VariableReplacement.prototype = { toJSON: function() { return { variable: this.variable(), part: this.replacement(), must_go_first: this.must_go_first() } }, load: function(data) { tryLoad(data,['variable','must_go_first'],this); var path = data.part; this.replacement(data.part); } } function PartType(part,data) { this.name = data.name; this.part = part; this.niceName = data.niceName; this.has_marks = data.has_marks || false; this.tabs = data.tabs || []; this.model = data.model ? data.model(part) : {}; this.toJSONFn = data.toJSON || function() {}; this.loadFn = data.load || function() {}; } PartType.prototype = { toJSON: function(data) { this.toJSONFn.apply(this.model,[data,this.part]); }, load: function(data) { this.loadFn.apply(this.model,[data,this.part]); } }; var partTypes = [ { name: 'information', niceName: 'Information only' }, { name: 'extension', niceName: 'Extension', has_marks: true }, { name: 'gapfill', niceName: 'Gap-fill', has_marks: true, toJSON: function(data,part) { if(part.gaps().length) { data.gaps = part.gaps().map(function(g) { return g.toJSON(); }); } }, load: function(data,part) { if(data.gaps) { data.gaps.map(function(g) { part.gaps.push(new Part(part.q,part,part.gaps,g)); }); } } }, { name:'jme', niceName: 'Mathematical expression', has_marks: true, tabs: [ new Editor.Tab('checking-accuracy','Accuracy','scale'), new Editor.Tab('restrictions','String restrictions','text-background') ], model: function() { var model = { answer: ko.observable(''), answerSimplification: ko.observable(''), showPreview: ko.observable(true), checkingTypes: [ {name:'absdiff',niceName:'Absolute difference', accuracy: ko.observable(0.001)}, {name:'reldiff',niceName:'Relative difference', accuracy: ko.observable(0.001)}, {name:'dp',niceName:'Decimal points', accuracy: ko.observable(3)}, {name:'sigfig',niceName:'Significant figures', accuracy: ko.observable(3)} ], failureRate: ko.observable(1), vset: { points: ko.observable(5), start: ko.observable(0), end: ko.observable(1) }, maxlength: { length: ko.observable(0), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, minlength: { length: ko.observable(0), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, musthave: { strings: ko.observableArray([]), showStrings: ko.observable(false), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, notallowed: { strings: ko.observableArray([]), showStrings: ko.observable(false), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, checkVariableNames: ko.observable(false), expectedVariableNames: ko.observableArray([]) }; model.checkingType = ko.observable(model.checkingTypes[0]); return model; }, toJSON: function(data) { data.answer = this.answer(); if(this.answerSimplification()) data.answersimplification = this.answerSimplification(); data.showpreview = this.showPreview(); data.checkingtype = this.checkingType().name; data.checkingaccuracy = this.checkingType().accuracy(); data.vsetrangepoints = this.vset.points(); data.vsetrange = [this.vset.start(),this.vset.end()]; data.checkvariablenames = this.checkVariableNames(); data.expectedvariablenames = this.expectedVariableNames(); if(this.maxlength.length()) { data.maxlength = { length: this.maxlength.length(), partialCredit: this.maxlength.partialCredit(), message: this.maxlength.message() }; } if(this.minlength.length()) { data.minlength = { length: this.minlength.length(), partialCredit: this.minlength.partialCredit(), message: this.minlength.message() }; } if(this.musthave.strings().length) { data.musthave = { strings: this.musthave.strings(), showStrings: this.musthave.showStrings(), partialCredit: this.musthave.partialCredit(), message: this.musthave.message() }; } if(this.notallowed.strings().length) { data.notallowed = { strings: this.notallowed.strings(), showStrings: this.notallowed.showStrings(), partialCredit: this.notallowed.partialCredit(), message: this.notallowed.message() }; } }, load: function(data) { tryLoad(data,['answer','answerSimplification','checkVariableNames','expectedVariableNames','showPreview'],this); for(var i=0;i<this.checkingTypes.length;i++) { if(this.checkingTypes[i].name == data.checkingtype) this.checkingType(this.checkingTypes[i]); } tryLoad(data,'checkingaccuracy',this.checkingType(),'accuracy'); tryLoad(data,'vsetrangepoints',this.vset,'points'); if('vsetrange' in data) { this.vset.start(data.vsetrange[0]); this.vset.end(data.vsetrange[1]); } tryLoad(data.maxlength,['length','partialCredit','message'],this.maxlength); tryLoad(data.minlength,['length','partialCredit','message'],this.minlength); tryLoad(data.musthave,['strings','showStrings','partialCredit','message'],this.musthave); tryLoad(data.notallowed,['strings','showStrings','partialCredt','message'],this.notallowed); } }, { name:'numberentry', niceName: 'Number entry', has_marks: true, tabs: [], model: function() { var model = { minValue: ko.observable(''), maxValue: ko.observable(''), correctAnswerFraction: ko.observable(false), integerAnswer: ko.observable(false), integerPartialCredit: ko.observable(0), allowFractions: ko.observable(false), precisionTypes: [ {name: 'none', niceName: 'None'}, {name: 'dp', niceName: 'Decimal places'}, {name: 'sigfig', niceName: 'Significant figures'} ], precision: ko.observable(0), precisionPartialCredit: ko.observable(0), precisionMessage: ko.observable('You have not given your answer to the correct precision.'), strictPrecision: ko.observable(true), showPrecisionHint: ko.observable(true) }; model.notationStyles = [ { code: 'plain', name: 'English (Plain)', description: 'No thousands separator; dot for decimal point.', }, { code: 'en', name:'English', description:'Commas separate thousands; dot for decimal point.', }, { code: 'si-en', name:'SI (English)', description:'Spaces separate thousands; dot for decimal point.', }, { code: 'si-fr', name:'SI (French)', description:'Spaces separate thousands; comma for decimal point.', }, { code: 'eu', name: 'Continental', description:'Dots separate thousands; comma for decimal point.', }, { code: 'plain-eu', name:'Continental (Plain)', description:'No thousands separator; comma for decimal point.', }, { code: 'ch', name:'Swiss', description:'Apostrophes separate thousands; dot for decimal point.', }, { code: 'in', name:'Indian', description:'Commas separate groups; rightmost group is 3 digits, other groups 2 digits; dot for decimal point.', } ]; model.allowedNotationStyles = ko.observableArray(model.notationStyles.filter(function(s){return ['plain','en','si-en'].contains(s.code)})); model.correctAnswerStyle = ko.observable(model.allowedNotationStyles()[0] || model.notationStyles[0]); model.precisionType = ko.observable(model.precisionTypes[0]); model.precisionWord = ko.computed(function() { switch(this.precisionType().name) { case 'dp': return 'Digits'; case 'sigfig': return 'Significant figures'; } },model); return model; }, toJSON: function(data) { data.minValue = this.minValue(); data.maxValue = this.maxValue(); data.correctAnswerFraction = this.correctAnswerFraction(); if(this.integerAnswer()) { data.integerAnswer = this.integerAnswer(); data.integerPartialCredit= this.integerPartialCredit(); } data.allowFractions = this.allowFractions(); if(this.precisionType().name!='none') { data.precisionType = this.precisionType().name; data.precision = this.precision(); data.precisionPartialCredit = this.precisionPartialCredit(); data.precisionMessage = this.precisionMessage(); data.strictPrecision = this.strictPrecision(); data.showPrecisionHint = this.showPrecisionHint(); } data.notationStyles = this.allowedNotationStyles().map(function(s){return s.code}); if(this.correctAnswerStyle()) { data.correctAnswerStyle = this.correctAnswerStyle().code; } }, load: function(data) { tryLoad(data,['minValue','maxValue','correctAnswerFraction','integerAnswer','integerPartialCredit','allowFractions','precision','precisionPartialCredit','precisionMessage','precisionType','strictPrecision','showPrecisionHint'],this); if('answer' in data) { this.minValue(data.answer); this.maxValue(data.answer); } for(var i=0;i<this.precisionTypes.length;i++) { if(this.precisionTypes[i].name == this.precisionType()) this.precisionType(this.precisionTypes[i]); } if('notationStyles' in data) { this.allowedNotationStyles(this.notationStyles.filter(function(s) { return data.notationStyles.contains(s.code); })); } if('correctAnswerStyle' in data) { var style = this.notationStyles.filter(function(s){return s.code==data.correctAnswerStyle})[0]; if(style) { this.correctAnswerStyle(style); } } } }, { name: 'matrix', niceName: 'Matrix entry', has_marks: true, tabs: [], model: function() { var model = { correctAnswer: ko.observable(''), correctAnswerFractions: ko.observable(false), numRows: ko.observable(1), numColumns: ko.observable(1), allowResize: ko.observable(true), tolerance: ko.observable(0), markPerCell: ko.observable(false), allowFractions: ko.observable(false), precisionTypes: [ {name: 'none', niceName: 'None'}, {name: 'dp', niceName: 'Decimal places'}, {name: 'sigfig', niceName: 'Significant figures'} ], precision: ko.observable(0), precisionPartialCredit: ko.observable(0), precisionMessage: ko.observable('You have not given your answer to the correct precision.'), strictPrecision: ko.observable(true) } model.precisionType = ko.observable(model.precisionTypes[0]); model.precisionWord = ko.computed(function() { switch(this.precisionType().name) { case 'dp': return 'Digits'; case 'sigfig': return 'Significant figures'; } },model); return model; }, toJSON: function(data) { data.correctAnswer = this.correctAnswer(); data.correctAnswerFractions = this.correctAnswerFractions(); data.numRows = this.numRows(); data.numColumns = this.numColumns(); data.allowResize = this.allowResize(); data.tolerance = this.tolerance(); data.markPerCell = this.markPerCell(); data.allowFractions = this.allowFractions(); if(this.precisionType().name!='none') { data.precisionType = this.precisionType().name; data.precision = this.precision(); data.precisionPartialCredit = this.precisionPartialCredit(); data.precisionMessage = this.precisionMessage(); data.strictPrecision = this.strictPrecision(); } }, load: function(data) { tryLoad(data,['correctAnswer','correctAnswerFractions','numRows','numColumns','allowResize','tolerance','markPerCell','allowFractions','precision','precisionPartialCredit','precisionMessage','precisionType','strictPrecision'],this); for(var i=0;i<this.precisionTypes.length;i++) { if(this.precisionTypes[i].name == this.precisionType()) this.precisionType(this.precisionTypes[i]); } } }, { name:'patternmatch', niceName: 'Match text pattern', has_marks: true, tabs: [], model: function() { return { answer: ko.observable(''), displayAnswer: Editor.contentObservable(''), caseSensitive: ko.observable(false), partialCredit: ko.observable(0) } }, toJSON: function(data) { data.answer = this.answer(); data.displayAnswer = this.displayAnswer(); if(this.caseSensitive()) { data.caseSensitive = this.caseSensitive(); data.partialCredit = this.partialCredit(); } }, load: function(data) { tryLoad(data,['answer','displayAnswer','caseSensitive','partialCredit'],this); } }, { name:'1_n_2', niceName: 'Choose one from a list', tabs: [ new Editor.Tab('marking','Marking','pencil'), new Editor.Tab('choices','Choices','list') ], model: function(part) { var model = { minMarks: ko.observable(0), maxMarks: ko.observable(0), shuffleChoices: ko.observable(false), displayColumns: ko.observable(0), customMatrix: ko.observable(''), customChoices: ko.observable(false), customChoicesExpression: ko.observable(''), choices: ko.observableArray([]) }; var _customMarking = ko.observable(false); model.customMarking = ko.computed({ read: function() { return _customMarking() || this.customChoices(); }, write: function(v) { return _customMarking(v); } },model); model.addChoice = function() { var c = { content: Editor.contentObservable('Choice '+(model.choices().length+1)), marks: ko.observable(0), distractor: Editor.contentObservable(''), answers: ko.observableArray([]) }; c.remove = function() { model.removeChoice(c); } model.choices.push(c); return c; }; model.removeChoice = function(choice) { model.choices.remove(choice); }; return model; }, toJSON: function(data) { data.minMarks = this.minMarks(); data.maxMarks = this.maxMarks(); data.shuffleChoices = this.shuffleChoices(); data.displayType = 'radiogroup'; data.displayColumns = this.displayColumns(); if(this.customChoices()) { data.choices = this.customChoicesExpression(); } else { var choices = this.choices(); data.choices = choices.map(function(c){return c.content()}); } if(this.customMarking()) { data.matrix = this.customMatrix(); } else { var matrix = []; var distractors = []; for(var i=0;i<choices.length;i++) { matrix.push(choices[i].marks()); distractors.push(choices[i].distractor()); } data.matrix = matrix; } data.distractors = distractors; }, load: function(data) { tryLoad(data,['minMarks','maxMarks','shuffleChoices','displayColumns'],this); if(typeof data.matrix == 'string') { this.customMarking(true); this.customMatrix(data.matrix); } if(typeof data.choices == 'string') { this.customChoices(true); this.customChoicesExpression(data.choices); } else { for(var i=0;i<data.choices.length;i++) { var c = this.addChoice(data.choices[i]); c.content(data.choices[i] || ''); if(!this.customMarking()) { c.marks(data.matrix[i] || 0); } if('distractors' in data) { c.distractor(data.distractors[i] || ''); } } } } }, { name:'m_n_2', niceName: 'Choose several from a list', tabs: [ new Editor.Tab('marking','Marking','pencil'), new Editor.Tab('choices','Choices','list') ], model: function() { var model = { minMarks: ko.observable(0), maxMarks: ko.observable(0), minAnswers: ko.observable(0), maxAnswers: ko.observable(0), shuffleChoices: ko.observable(false), displayColumns: ko.observable(0), customMatrix: ko.observable(''), warningType: ko.observable(''), warningTypes: [ {name: 'none', niceName: 'Do nothing'}, {name: 'warn', niceName: 'Warn'}, {name: 'prevent', niceName: 'Prevent submission'} ], customChoices: ko.observable(false), customChoicesExpression: ko.observable(''), choices: ko.observableArray([]), }; var _customMarking = ko.observable(false); model.customMarking = ko.computed({ read: function() { return _customMarking() || this.customChoices(); }, write: function(v) { return _customMarking(v); } },model); model.addChoice = function() { var c = { content: Editor.contentObservable('Choice '+(model.choices().length+1)), marks: ko.observable(0), distractor: Editor.contentObservable(''), answers: ko.observableArray([]) }; c.remove = function() { model.removeChoice(c); } model.choices.push(c); return c; }; model.removeChoice = function(choice) { model.choices.remove(choice); }; return model; }, toJSON: function(data) { data.minMarks = this.minMarks(); data.maxMarks = this.maxMarks(); data.shuffleChoices = this.shuffleChoices(); data.displayType = 'checkbox'; data.displayColumns = this.displayColumns(); data.minAnswers = this.minAnswers(); data.maxAnswers = this.maxAnswers(); data.warningType = this.warningType().name; if(this.customChoices()) { data.choices = this.customChoicesExpression(); } else { var choices = this.choices(); data.choices = choices.map(function(c){return c.content()}); } if(this.customMarking()) { data.matrix = this.customMatrix(); } else { var matrix = []; var distractors = []; for(var i=0;i<choices.length;i++) { matrix.push(choices[i].marks()); distractors.push(choices[i].distractor()); } data.matrix = matrix; } data.distractors = distractors; }, load: function(data) { tryLoad(data,['minMarks','maxMarks','minAnswers','maxAnswers','shuffleChoices','displayColumns'],this); if(typeof data.matrix == 'string') { this.customMarking(true); this.customMatrix(data.matrix); } for(var i=0;i<this.warningTypes.length;i++) { if(this.warningTypes[i].name==data.warningType) { this.warningType(this.warningTypes[i]); } } if(typeof data.choices == 'string') { this.customChoices(true); this.customChoicesExpression(data.choices); } else { for(var i=0;i<data.choices.length;i++) { var c = this.addChoice(data.choices[i]); c.content(data.choices[i] || ''); if(!this.customMarking()) { c.marks(data.matrix[i] || 0); } if('distractors' in data) { c.distractor(data.distractors[i] || ''); } } } } }, { name:'m_n_x', niceName: 'Match choices with answers', tabs: [ new Editor.Tab('choices','Choices','list'), new Editor.Tab('answers','Answers','list'), new Editor.Tab('matrix','Marking matrix','th'), new Editor.Tab('marking','Marking options','pencil') ], model: function() { var model = { minMarks: ko.observable(0), maxMarks: ko.observable(0), minAnswers: ko.observable(0), maxAnswers: ko.observable(0), shuffleChoices: ko.observable(false), shuffleAnswers: ko.observable(false), displayType:ko.observable(''), customMatrix: ko.observable(''), warningType: ko.observable(''), warningTypes: [ {name: 'none', niceName: 'Do nothing'}, {name: 'warn', niceName: 'Warn'}, {name: 'prevent', niceName: 'Prevent submission'} ], displayTypes: [ {name: 'radiogroup', niceName: 'One from each row'}, {name: 'checkbox', niceName: 'Checkboxes'} ], customChoices: ko.observable(false), customChoicesExpression: ko.observable(''), customAnswers: ko.observable(false), customAnswersExpression: ko.observable(''), choices: ko.observableArray([]), answers: ko.observableArray([]), layoutType: ko.observable('all'), layoutTypes: [ {name: 'all', niceName: 'Show all options'}, {name: 'lowertriangle', niceName: 'Lower triangle'}, {name: 'strictlowertriangle', niceName: 'Lower triangle (no diagonal)'}, {name: 'uppertriangle', niceName: 'Upper triangle'}, {name: 'strict uppertriangle', niceName: 'Upper triangle (no diagonal)'}, {name: 'expression', niceName: 'Custom expression'} ], layoutExpression: ko.observable('') }; model.matrix = Editor.editableGrid( ko.computed(function() { return model.choices().length; }), ko.computed(function() { return model.answers().length; }), function() { return { marks: ko.observable(0), distractor: ko.observable('') } } ); var _customMarking = ko.observable(false); model.customMarking = ko.computed({ read: function() { return _customMarking() || this.customChoices() || this.customAnswers(); }, write: function(v) { return _customMarking(v); } },model); model.addChoice = function() { var c = { content: Editor.contentObservable('Choice '+(model.choices().length+1)), marks: ko.observable(0), distractor: Editor.contentObservable('') }; c.remove = function() { model.removeChoice(c); } model.choices.push(c); return c; }, model.removeChoice = function(choice) { model.choices.remove(choice); }; model.addAnswer = function() { var a = { content: ko.observable('Answer '+(model.answers().length+1)) }; a.remove = function() { model.removeAnswer(a); } model.answers.push(a); return a; }; model.showMarkingMatrix = ko.computed(function() { var hasChoices = model.customChoices() || model.choices().length; var hasAnswers = model.customAnswers() || model.answers().length; return hasChoices && hasAnswers && !model.customMarking(); },this); model.removeAnswer = function(answer) { var n = model.answers.indexOf(answer); model.answers.remove(answer); }; return model; }, toJSON: function(data) { data.minMarks = this.minMarks(); data.maxMarks = this.maxMarks(); data.minAnswers = this.minAnswers(); data.maxAnswers = this.maxAnswers(); data.shuffleChoices = this.shuffleChoices(); data.shuffleAnswers = this.shuffleAnswers(); data.displayType = this.displayType().name; data.warningType = this.warningType().name; if(this.customChoices()) { data.choices = this.customChoicesExpression(); } else { var choices = this.choices(); data.choices = choices.map(function(c){return c.content()}); } if(this.customMarking()) { data.matrix = this.customMatrix(); } else { data.matrix = this.matrix().map(function(r){ return r().map(function(c) { return c.marks() }) }); } data.layout = {type: this.layoutType().name, expression: this.layoutExpression()} if(this.customAnswers()) { data.answers = this.customAnswersExpression(); } else { var answers = this.answers(); data.answers = answers.map(function(a){return a.content()}); } }, load: function(data) { tryLoad(data,['minMarks','maxMarks','minAnswers','maxAnswers','shuffleChoices','shuffleAnswers'],this); for(var i=0;i<this.warningTypes.length;i++) { if(this.warningTypes[i].name==data.warningType) { this.warningType(this.warningTypes[i]); } } for(var i=0;i<this.displayTypes.length;i++) { if(this.displayTypes[i].name==data.displayType) { this.displayType(this.displayTypes[i]); } } if(data.layout) { for(var i=0;i<this.layoutTypes.length;i++) { if(this.layoutTypes[i].name==data.layout.type) { this.layoutType(this.layoutTypes[i]); } } tryLoad(data.layout,['expression'],this,['layoutExpression']); } if(typeof data.answers == 'string') { this.customAnswers(true); this.customAnswersExpression(data.answers); } else { for(var i=0;i<data.answers.length;i++) { var a = this.addAnswer(); a.content(data.answers[i]); } } if(typeof data.choices == 'string') { this.customChoices(true); this.customChoicesExpression(data.choices); } else { for(var i=0;i<data.choices.length;i++) { var c = this.addChoice(data.choices[i]); c.content(data.choices[i]); } } if(typeof data.matrix == 'string') { this.customMarking(true); this.customMatrix(data.matrix); } else { for(var i=0;i<data.matrix.length;i++) { for(var j=0;j<data.matrix[i].length;j++) { this.matrix()[i]()[j].marks(data.matrix[i][j]); } } } } } ]; var deps = ['jme-display','jme-variables','jme','editor-extras']; for(var i=0;i<item_json.numbasExtensions.length;i++) { var extension = item_json.numbasExtensions[i]; if(extension.hasScript) { deps.push('extensions/'+extension.location+'/'+extension.location+'.js'); } } Numbas.queueScript('start-editor',deps,function() { try { viewModel = new Question(item_json.itemJSON); viewModel.set_tab_from_hash(); ko.options.deferUpdates = true; ko.applyBindings(viewModel); try { document.body.classList.add('loaded'); } catch(e) { document.body.className += ' loaded'; } $('.timeline').mathjax(); } catch(e) { $('.page-loading').hide(); $('.page-error') .show() .find('.trace') .html(e.message) ; throw(e); } }); Mousetrap.bind(['ctrl+b','command+b'],function() { window.open(item_json.previewURL,item_json.previewWindow); }); });
editor/static/js/question/edit.js
var viewModel; $(document).ready(function() { var builtinRulesets = ['basic','unitFactor','unitPower','unitDenominator','zeroFactor','zeroTerm','zeroPower','noLeadingMinus','collectNumbers','simplifyFractions','zeroBase','constantsFirst','sqrtProduct','sqrtDivision','sqrtSquare','trig','otherNumbers'] var jmeTypes = []; var forbiddenJmeTypes = ['op','name','function']; for(var type in Numbas.jme.types) { var t = Numbas.jme.types[type].prototype.type; if(t && jmeTypes.indexOf(t)==-1 && forbiddenJmeTypes.indexOf(t)==-1) { jmeTypes.push(t); } } function Question(data) { var q = this; Editor.EditorItem.apply(this); this.resources = ko.observableArray([]); this.extensions = ko.observableArray([]); this.statement = Editor.contentObservable(''); this.advice = Editor.contentObservable(''); var rulesets = this.rulesets = ko.observableArray([]); this.functions = ko.observableArray([]); this.variables = ko.observableArray([]); this.questionScope = ko.observable(); this.variableGroups = ko.observableArray([]); this.editVariableGroup = ko.observable(null); this.autoCalculateVariables = ko.observable(true); this.currentVariable = ko.observable(null); this.variablesTest = { condition: ko.observable(''), conditionError: ko.observable(false), conditionSatisfied: ko.observable(true), // was the condition satisfied when generating a preview set of values? maxRuns: ko.observable(100), totalRuns: ko.observable(0), totalErrors: ko.observable(0), totalCorrect: ko.observable(0), advice: ko.observable(''), running_time: ko.observable(3), running: ko.observable(false), time_remaining: ko.observable(0) }; this.parts = ko.observableArray([]); //for image attribute modal this.imageModal = { width: ko.observable(0), height: ko.observable(0), title: ko.observable(''), alt: ko.observable('') } //for iframe attribute modal this.iframeModal = { width: ko.observable(0), height: ko.observable(0) } this.mainTabs([ new Editor.Tab('settings','Settings','cog'), new Editor.Tab('statement','Statement','blackboard'), new Editor.Tab('variables','Variables','th-list'), new Editor.Tab('variabletesting','Variable testing','dashboard'), new Editor.Tab( 'parts', 'Parts', 'list' ), new Editor.Tab('advice','Advice','blackboard'), new Editor.Tab('extensions','Extensions & scripts','wrench'), new Editor.Tab('resources','Resources','picture'), new Editor.Tab('exams','Exams using this question','book'), new Editor.Tab('network','Other versions','link'), new Editor.Tab('history','Editing history','time') ]); if(item_json.editable) { var adviceTab = new Editor.Tab('access','Access','lock'); this.mainTabs.splice(6,0,adviceTab); } this.currentTab(this.mainTabs()[0]); this.add_to_basket = function() { Editor.add_question_to_basket(item_json.itemJSON.id); } this.saveResources = ko.computed(function() { var resources = this.resources(); var out = []; for(var i=0;i<resources.length;i++) { var res = resources[i]; if(res.progress()==1) { out.push({ pk: res.pk() }); } } return out; },this); for(var i=0;i<item_json.numbasExtensions.length;i++) { var ext = item_json.numbasExtensions[i]; ext.used = ko.observable(false); this.extensions.push(ext); } this.usedExtensions = ko.computed(function() { return this.extensions().filter(function(e){return e.used()}); },this); this.allsets = ko.computed(function() { return builtinRulesets.concat(this.rulesets().map(function(r){return r.name()})).sort(); },this); this.preamble = { css: ko.observable(''), js: ko.observable('') }; this.baseVariableGroup = new VariableGroup(this,{name:'Ungrouped variables'}); this.baseVariableGroup.fixed = true; this.allVariableGroups = ko.computed(function() { var l = this.variableGroups(); return l.concat(this.baseVariableGroup); },this); // this changes whenever there's a change to a variable name or definition, or a variables is added or removed (or similar to the functions) this.lastVariableChange = ko.computed(function() { this.variables().map(function(v) { v.definition(); v.name(); }); this.functions().map(function(f) { f.name(); f.definition(); f.parameters(); f.type(); f.language(); }); return new Date(); },this); this.variablesTest.time_remaining_display = ko.computed(function() { return this.time_remaining()+' '+Numbas.util.pluralise(this.time_remaining(),'second','seconds'); },this.variablesTest); // reset the advice whenever the condition changes or there's a change to the variables ko.computed(function() { this.variablesTest.condition(); this.lastVariableChange(); this.variablesTest.advice(''); },this); this.variableErrors = ko.computed(function() { var variables = this.variables(); for(var i=0;i<variables.length;i++) { if(variables[i].nameError() || variables[i].error()) return true; } return false; },this); this.addVariableBefore = function() { var n = q.variables.indexOf(this); var v = new Variable(q); q.variables.splice(n,0,v); } this.goToVariable = function(name) { var v = q.getVariable(name); if(!v) { return; } q.currentVariable(v); q.currentTab(q.getTab('variables')); } this.expand_all_parts = function() { q.allParts().map(function(p) { p.open(true); }); } this.collapse_all_parts = function() { q.allParts().map(function(p) { p.open(false); }); } // all parts in this question, including child parts such as gaps and steps this.allParts = ko.computed(function() { var o = []; this.parts().map(function(p) { o.push(p); if(p.type().name=='gapfill') { o = o.concat(p.gaps()); } o = o.concat(p.steps()); }); return o; },this); ko.computed(function() { if(!this.autoCalculateVariables()) return; //the ko dependency checker seems not to pay attention to what happens in the computeVariables method, so access the variable bits here to give it a prompt this.functions().map(function(v) { v.name(); v.definition(); v.parameters(); }); this.variables().map(function(v) { v.name(); v.definition(); }); this.generateVariablePreview(); },this).extend({throttle:300}); if(data) { this.load(data); } if(item_json.editable) { this.deleteResource = function(res) { q.resources.remove(res); } this.init_output(); this.save = ko.computed(function() { return { content: this.output(), extensions: this.usedExtensions().map(function(e){return e.pk}), tags: this.tags(), subjects: this.subjects().filter(function(s){return s.used()}).map(function(s){return s.pk}), topics: this.topics().filter(function(t){return t.used()}).map(function(t){return t.pk}), ability_levels: this.used_ability_levels().map(function(al){return al.pk}), resources: this.saveResources(), metadata: this.metadata() }; },this); this.init_save(); this.section_tasks = { 'settings': [ Editor.nonempty_task('Give the question a name.',this.name), Editor.nonempty_task('Fill out the question description.',this.description), Editor.nonempty_task('Select a licence defining usage rights.',this.licence) ], 'statement': [ Editor.nonempty_task('Write a question statement.',this.statement) ], 'parts': [ {text: 'Create at least one part.', done: ko.computed(function(){ return this.parts().length>0 },this)} ], 'advice': [ Editor.nonempty_task('Write a worked solution to the question.',this.advice) ] } this.init_tasks(); } if(window.history !== undefined) { this.load_state(); var state = window.history.state || {}; if('currentVariable' in state) { var variables = this.variables(); for(var i=0;i<variables.length;i++) { var variable = variables[i]; if(variable.name().toLowerCase()==state.currentVariable) { this.currentVariable(variable); break; } } } Editor.computedReplaceState('currentVariable',ko.computed(function(){ var v = this.currentVariable(); if(v) { return v.name().toLowerCase(); } else { return undefined; } },this)); } } Question.prototype = { versionJSON: function() { var obj = { id: this.id, JSONContent: this.toJSON(), numbasVersion: Editor.numbasVersion, name: this.name(), author: item_json.itemJSON.author, copy_of: item_json.itemJSON.copy_of, extensions: this.usedExtensions().map(function(e){return e.pk}), tags: this.tags(), resources: this.saveResources(), metadata: this.metadata() }; if(item_json.editable) { obj.public_access = this.public_access(); } return obj; }, deleteItem: function(q,e) { if(window.confirm('Really delete this question?')) { $(e.target).find('form').submit(); } }, addRuleset: function() { this.rulesets.push(new Ruleset(this)); }, addFunction: function(q,e,n) { var f = new CustomFunction(this); if(n!=undefined) this.functions.splice(n,0,f); else this.functions.push(f); return f; }, addVariable: function(q,e,n) { var v = new Variable(this); if(n!=undefined) this.variables.splice(n,0,v); else this.variables.push(v); this.currentVariable(v); return v; }, addVariableGroup: function() { var vg = new VariableGroup(this); this.variableGroups.push(vg); return vg; }, getVariable: function(name) { name = name.toLowerCase(); var variables = this.variables(); for(var i = 0; i<variables.length;i++) { if(variables[i].name().toLowerCase() == name) { return variables[i]; } } }, getVariableGroup: function(name) { var groups = this.allVariableGroups(); for(var i=0;i<groups.length;i++) { if(groups[i].name()==name) { return groups[i]; } } var vg = new VariableGroup(this,{name:name}); this.variableGroups.push(vg); return vg; }, addPart: function() { var p = new Part(this,null,this.parts); this.parts.push(p); return p; }, loadPart: function(data) { var p = new Part(this,null,this.parts,data); this.parts.push(p); return p; }, getPart: function(path) { return this.parts()[0]; var re_path = /^p(\d+)(?:g(\d+)|s(\d+))?$/; var m = re_path.exec(path); var i = parseInt(m[1]); var p = this.parts()[i]; if(m[2]) { var g = parseInt(m[2]); return p.gaps()[g]; } else if(m[3]) { var s = parseInt(m[3]); return p.steps()[s]; } else { return p; } }, generateVariablePreview: function() { if(!Numbas.jme) { var q = this; Numbas.init = function() { q.generateVariablePreview(); }; return; } this.functions().map(function(f) { f.error(''); }); this.variables().map(function(v) { if(!v.locked.peek()) { v.error(''); v.value(''); } }); var prep = this.prepareVariables(); this.variables().map(function(v) { var name = v.name().toLowerCase(); if(prep.todo[name]) { v.dependencies(prep.todo[name].vars); } else { v.dependencies([]); } }); var conditionSatisfied = false; var results; var runs = 0; var maxRuns = this.variablesTest.maxRuns(); while(runs<maxRuns && !conditionSatisfied) { var results = this.computeVariables(prep); conditionSatisfied = results.conditionSatisfied; runs += 1; } this.variablesTest.conditionSatisfied(conditionSatisfied); // fill in observables if(conditionSatisfied) { this.variables().map(function(v) { if(v.locked.peek()) { return; } var name = v.name().toLowerCase(); var result = results.variables[name]; if(!result) { v.value(null); return; } if('value' in result) { v.value(result.value); } if('error' in result) { v.error(result.error); } }); } this.questionScope(results.scope); }, // get everything ready to compute variables - make functions, and work out dependency graph prepareVariables: function() { var jme = Numbas.jme; var scopes = [jme.builtinScope]; var extensions = this.extensions().filter(function(e){return e.used()}); for(var i=0;i<extensions.length;i++) { var extension = extensions[i].location; if(extension in Numbas.extensions && 'scope' in Numbas.extensions[extension]) { scopes.push(Numbas.extensions[extension].scope); } } var scope = new jme.Scope(scopes); //create functions this.functions().map(function(f) { try { var fn = { name: f.name().toLowerCase(), definition: f.definition(), language: f.language(), outtype: f.type(), parameters: f.parameters().map(function(p) { if(!p.name()) { throw(new Error('A parameter is unnamed.')); } return { name: p.name(), type: p.type() } }) }; var cfn = jme.variables.makeFunction(fn,scope); if(scope.functions[cfn.name]===undefined) scope.functions[cfn.name] = []; scope.functions[cfn.name].push(cfn); } catch(e) { f.error(e.message); } }); //make structure of variables to evaluate var todo = {} this.variables().map(function(v) { var name = v.name().toLowerCase(); if(!v.name()) { return; } if(v.definitionError()) { v.error(v.definitionError()); return; } if(!v.definition()) { todo[name] = { v: v, tree: null, vars: [] }; return; } if(v.locked.peek()) { scope.variables[v.name()] = v.value(); } try { var tree = jme.compile(v.definition(),scope,true); var vars = jme.findvars(tree); v.error(''); } catch(e) { v.error(e.message); return; } todo[name] = { v: v, tree: tree, vars: vars } }); var condition; try { condition = Numbas.jme.compile(this.variablesTest.condition()); this.variablesTest.conditionError(false); } catch(e) { this.variablesTest.conditionError(e.message); condition = null; } return { scope: scope, todo: todo, condition: condition }; }, /* Given a list of variable names, return a list of names of the dependencies of those variables which have some random element */ randomDependencies: function(vars) { var d = this.prepareVariables(); var scope = d.scope; var todo = d.todo; var deps = Numbas.jme.variables.variableDependants(todo,vars); var randoms = []; for(var name in deps) { if(Numbas.jme.isRandom(deps[name].tree,scope)) { randoms.push(name); } } return randoms; }, computeVariables: function(prep) { var result = {variables: {}}; var jme = Numbas.jme; var scope = result.scope = new jme.Scope([prep.scope]); var todo = prep.todo; function computeVariable(name) { try { var value = jme.variables.computeVariable(name,todo,scope); result.variables[name] = {value: value}; } catch(e) { result.variables[name] = {error: e.message}; result.error = true; } } if(prep.condition) { var condition_vars = jme.findvars(prep.condition); condition_vars.map(function(name) { computeVariable(name); }); try { result.conditionSatisfied = Numbas.jme.evaluate(prep.condition,scope).value; } catch(e) { this.variablesTest.conditionError(e.message); result.conditionSatisfied = false; return result; } } else { result.conditionSatisfied = true; } if(result.conditionSatisfied) { //evaluate variables for(var x in todo) { computeVariable(x); } } return result; }, cancelVariablesTest: function() { this.variablesTest.cancel = true; }, testVariables: function() { var running_time = parseFloat(this.variablesTest.running_time()); var start = new Date() var end = start.getTime()+running_time*1000; var runs = 0; var errors = 0; var correct = 0; var q = this; var prep = this.prepareVariables(); this.variablesTest.time_remaining(running_time); this.variablesTest.cancel = false; this.variablesTest.running(true); function finish() { q.variablesTest.running(false); var timeTaken = ((new Date())-start)/1000; var timePerRun = timeTaken/runs; q.variablesTest.totalRuns(runs); q.variablesTest.totalErrors(errors); q.variablesTest.totalCorrect(correct); var probPass = correct/runs; var probFail = 1-probPass; var probError = errors/runs; // calculate 95% confidence interval for probPass var z = 1.9599639845400545; var n = runs; var p = probPass; var confidence = { lower: (1/(1+z*z/n))*(p+z*z/(2*n)-z*Math.sqrt(p*(1-p)/n+z*z/(4*n*n))), upper: (1/(1+z*z/n))*(p+z*z/(2*n)+z*Math.sqrt(p*(1-p)/n+z*z/(4*n*n))) }; var suggestedRuns = Math.ceil(Math.log(1/1000)/Math.log(probFail)); if(suggestedRuns<1) { suggestedRuns = 1; } var probSucceedInTime = 1-Math.pow(probFail,1/timePerRun); function round(n,precision) { precision = precision || 2; return Numbas.math.niceNumber(n,{precisionType:'sigfig',precision:3}); } if(correct==0) { q.variablesTest.advice('The condition was never satisfied. That means it\'s either really unlikely or impossible.'); } else { q.variablesTest.advice( '<p>The condition was satisfied <strong>'+round(probPass*100)+'%</strong> of the time, over <strong>'+runs+'</strong> runs, with <strong>'+round(probError*100)+'%</strong> of runs aborted due to errors. The mean computation time for one run was <strong>'+round(timePerRun)+'</strong> seconds.</p>'+ '<p>Successfully generating a set of variables will take on average <strong>'+round(timePerRun*(1/probPass))+'</strong> seconds on this device.</p>'+ '<p>In order to fail at most 1 in every 1000 times the question is run, you should set the max. runs to <strong>'+suggestedRuns+'</strong>, taking at most <strong>'+round(timePerRun*suggestedRuns)+'</strong> seconds on this device.</p>'+ '<p>If you want to allow at most <strong>1 second</strong> to generate a set of variables, i.e. set max. runs to <strong>'+round(1/timePerRun)+'</strong>, this device\'s chance of succeeding is <strong>'+round(probSucceedInTime*100)+'%</strong>.</p>' ); } } var ot = Math.ceil(running_time); function test() { var t = new Date(); if(q.variablesTest.cancel || t>end) { finish(); } else { var diff = Math.ceil((end-t)/1000); if(diff!=ot) { ot = diff; q.variablesTest.time_remaining(diff); } try { runs += 1; var run = q.computeVariables(prep); } catch(e) { q.variablesTest.running(false); return; } if(run.conditionSatisfied) { correct += 1; } if(run.error) { errors += 1; } setTimeout(test,1); } } test(); }, toJSON: function() { var rulesets = {}; this.rulesets().map(function(r){ rulesets[r.name()] = r.sets(); }); var variables = {}; this.variables().map(function(v) { variables[v.name()] = v.toJSON(); }); var ungrouped_variables = this.baseVariableGroup.variables().map(function(v){ return v.name(); }); var groups = []; this.variableGroups().map(function(g) { groups.push({ name: g.name(), variables: g.variables().map(function(v){return v.name()}) }); }); var functions = {}; this.functions().map(function(f) { functions[f.name()] = f.toJSON(); }); return { name: this.realName(), tags: this.tags(), metadata: this.metadata(), statement: this.statement(), advice: this.advice(), rulesets: rulesets, extensions: this.extensions().filter(function(e){return e.used()}).map(function(e){return e.location}), variables: variables, variablesTest: { condition: this.variablesTest.condition(), maxRuns: this.variablesTest.maxRuns() }, ungrouped_variables: ungrouped_variables, variable_groups: groups, functions: functions, preamble: { js: this.preamble.js(), css: this.preamble.css() }, parts: this.parts().map(function(p){return p.toJSON();}) } }, reset: function() { this.resources([]); this.realtags([]); this.rulesets([]); this.functions([]); this.variables([]); this.variableGroups([]); this.baseVariableGroup.variables([]); this.parts([]); this.extensions().map(function(e){ e.used(false); }); }, load: function(data) { Editor.EditorItem.prototype.load.apply(this,[data]); var q = this; if('extensions' in data) { this.extensions().map(function(e) { if(data.extensions.indexOf(e.location)>=0) e.used(true); }); } if('resources' in data) { data.resources.map(function(rd) { this.resources.push(new Editor.Resource(rd)); },this); } contentData = data.JSONContent; tryLoad(contentData,['name','statement','advice'],this); if('variables' in contentData) { for(var x in contentData.variables) { var v = new Variable(this,contentData.variables[x]); this.variables.push(v); } } if('variable_groups' in contentData) { contentData.variable_groups.map(function(gdata) { var vg = q.getVariableGroup(gdata.name); gdata.variables.map(function(variable_name) { var v = q.getVariable(variable_name); if(v) { vg.variables.push(v); q.baseVariableGroup.variables.remove(v); } }); }); } if('ungrouped_variables' in contentData) { contentData.ungrouped_variables.map(function(variable_name) { var v = q.getVariable(variable_name); if(v) { q.baseVariableGroup.variables.remove(v); q.baseVariableGroup.variables.push(v); } }); } this.selectFirstVariable(); if('variablesTest' in contentData) { tryLoad(contentData.variablesTest,['condition','maxRuns'],this.variablesTest); } if('functions' in contentData) { for(var x in contentData.functions) { contentData.functions[x].name = x; this.functions.push(new CustomFunction(this,contentData.functions[x])); } } if('preamble' in contentData) { tryLoad(contentData.preamble,['css','js'],this.preamble); } if('rulesets' in contentData) { for(var x in contentData.rulesets) { this.rulesets.push(new Ruleset(this,{name: x, sets:contentData.rulesets[x]})); } } if('parts' in contentData) { contentData.parts.map(function(pd) { this.loadPart(pd); },this); } try{ this.tags(data.tags); } catch(e) { this.tags([]); } }, selectFirstVariable: function() { if(this.variables().length) { var groups = this.allVariableGroups(); for(var i=0;i<groups.length;i++) { if(groups[i].variables().length) { this.currentVariable(groups[i].variables()[0]); return; } } } this.currentVariable(null); }, insertImage: function(image) { $('#imagePickModal').modal('hide'); var ed = viewModel.currentTinyMCE; if(!ed) { return; } var name = image.name(); var html; switch(image.filetype()) { case 'html': html = '<div><iframe src="'+image.url()+'"></div>'; break; default: html = '<img src="'+image.url()+'">'; } ed.execCommand('mceInsertContent',false,html); }, changeImageAttributes: function() { $(this.imageModal.selectedNode) .css({ width: this.imageModal.width(), height: this.imageModal.height() }); $(this.imageModal.selectedNode) .removeAttr('data-mce-style') $(this.imageModal.selectedNode) .attr('alt',this.imageModal.alt()) $(this.imageModal.selectedNode) .attr('title',this.imageModal.title()) ; $('#imageAttributeModal').modal('hide'); var ed = viewModel.currentTinyMCE; ed.fire('change'); }, changeIframeAttributes: function() { $(this.iframeModal.selectedNode) .css({ width: this.iframeModal.width(), height: this.iframeModal.height() }) .removeAttr('data-mce-style') ; $('#iframeAttributeModal').modal('hide'); var ed = viewModel.currentTinyMCE; ed.onChange.dispatch(); } }; Question.prototype.__proto__ = Editor.EditorItem.prototype; function Ruleset(exam,data) { this.name = ko.observable(''); this.sets = ko.observableArray([]); this.allsets = exam.allsets; this.remove = function() { exam.rulesets.remove(this); }; if(data) this.load(data); } Ruleset.prototype = { load: function(data) { var ruleset = this; this.name(data.name); data.sets.map(function(set){ ruleset.sets.push(set); }); } }; var re_name = /^{?((?:(?:[a-zA-Z]+):)*)((?:\$?[a-zA-Z_][a-zA-Z0-9_]*'*)|\?)}?$/i; function VariableGroup(q,data) { var vg = this; this.fixed = false; this.name = ko.observable('Unnamed group'); this.isEditing = ko.computed({ write: function(v) { if(v) { q.editVariableGroup(vg); } else if(q.editVariableGroup()==vg) { q.editVariableGroup(null); } }, read: function() { return q.editVariableGroup()==vg; } },this); this.endEdit = function() { vg.isEditing(false); } this.displayName = ko.computed(function() { return this.name() ? this.name() : 'Unnamed group' },this); this.variables = ko.observableArray([]); ko.computed(function() { vg.variables().map(function(v) { v.group(vg); }); },this); this.receivedVariables = ko.observableArray([]); ko.computed(function() { var received = this.receivedVariables(); if(received.length) { this.variables(this.variables().concat(received)); this.receivedVariables([]); } },this); this.addVariable = function() { var v = q.addVariable(); this.variables.push(v); return v; } if(data) { tryLoad(data,['name'],this); } this.remove = function() { q.variableGroups.remove(this); this.variables().map(function(v) { q.baseVariableGroup.variables.push(v); }); this.variables([]); } } VariableGroup.prototype = { sort: function() { this.variables(this.variables().sort(function(a,b){ a = a.name().toLowerCase(); b = b.name().toLowerCase(); return a>b ? 1 : a==b ? 0 : -1; })); } } function Variable(q,data) { this.question = q; this._name = ko.observable(''); this.name = ko.computed({ read: function() { return this._name().trim(); }, write: function(v) { return this._name(v); } },this); this.group = ko.observable(null); this.nameError = ko.computed(function() { var name = this.name(); if(name=='') return ''; var variables = q.variables(); for(var i=0;i<variables.length;i++) { var v = variables[i]; if(v!=this && v.name().toLowerCase()==name.toLowerCase()) return 'There\'s already a variable with this name.'; } if(!re_name.test(name)) { return 'This variable name is invalid.'; } return ''; },this); this.description = ko.observable(''); this.templateType = ko.observable(this.templateTypes[0]); function InexhaustibleList() { var _arr = ko.observableArray([]); function addValue(v) { v = v || ''; var _obs = ko.observable(v); var obj; var obs = ko.computed({ read: function() { return _obs(); }, write: function(v) { var arr = _arr(); if(v && obj==arr[arr.length-1]) { addValue(''); } return _obs(v); } }); function onBlur() { var arr = _arr(); if(arr.indexOf(this)<arr.length-1 && !this.value()) _arr.remove(obj); } obj = {value: obs, onBlur: onBlur}; _arr.push(obj); return obs; } addValue(); var arr = ko.computed({ read: function() { return _arr().slice(0,-1).map(function(v){return v.value()}); }, write: function(a) { _arr([]); for(var i=0;i<a.length;i++) { addValue(a[i]); } addValue(); } }); arr.edit = _arr; return arr; } this.templateTypeValues = { 'anything': { definition: ko.observable('') }, 'number': { value: ko.observable(0) }, 'range': { min: ko.observable(0), max: ko.observable(1), step: ko.observable(1) }, 'randrange': { min: ko.observable(0), max: ko.observable(1), step: ko.observable(1) }, 'string': { value: ko.observable('') }, 'long string': { value: ko.observable('') }, 'list of numbers': { commaValue: ko.observable('') }, 'list of strings': { values: InexhaustibleList() }, 'json': { value: ko.observable(''), prettyPrint: function() { var v = this.templateTypeValues.json.value(); try { var data = JSON.parse(v); this.templateTypeValues.json.value(JSON.stringify(data,null,4)); } catch(e) { } } } }; this.editDefinition = this.templateTypeValues['anything'].definition; this.templateTypeValues['list of numbers'].values = ko.computed(function() { var commaValue = this.commaValue(); if(!commaValue.trim()) return []; var numbers = commaValue.split(/\s+|\s*,\s*/g); numbers = numbers .map(function(n) { return parseFloat(n); }) .filter(function(n) { return !isNaN(n); }) ; return numbers; },this.templateTypeValues['list of numbers']); this.definitionError = ko.observable(null); this.definition = ko.computed({ read: function() { this.definitionError(null); var templateType = this.templateType().id; var val = this.templateTypeValues[templateType]; var treeToJME = Numbas.jme.display.treeToJME; var wrapValue = Numbas.jme.wrapValue; try { switch(templateType) { case 'anything': return val.definition()+''; case 'number': var n = parseFloat(val.value()); if(isNaN(n)) { throw("Value is not a number"); } return treeToJME({tok: wrapValue(parseFloat(val.value()))}); case 'range': var min = parseFloat(val.min()); var max = parseFloat(val.max()); var step = parseFloat(val.step()); if(isNaN(min)) { throw('Minimum value is not a number'); } else if(isNaN(max)) { throw('Maximum value is not a number'); } else if(isNaN(step)) { throw("Step value is not a number"); } var tree = Numbas.jme.compile('a..b#c'); tree.args[0].args[0] = {tok: wrapValue(parseFloat(val.min()))}; tree.args[0].args[1] = {tok: wrapValue(parseFloat(val.max()))}; tree.args[1] = {tok: wrapValue(parseFloat(val.step()))}; return treeToJME(tree); case 'randrange': var min = parseFloat(val.min()); var max = parseFloat(val.max()); var step = parseFloat(val.step()); if(isNaN(min)) { throw('Minimum value is not a number'); } else if(isNaN(max)) { throw('Maximum value is not a number'); } else if(isNaN(step)) { throw("Step value is not a number"); } var tree = Numbas.jme.compile('random(a..b#c)'); tree.args[0].args[0].args[0] = {tok: wrapValue(parseFloat(val.min()))}; tree.args[0].args[0].args[1] = {tok: wrapValue(parseFloat(val.max()))}; tree.args[0].args[1] = {tok: wrapValue(parseFloat(val.step()))}; return treeToJME(tree); case 'string': case 'long string': return treeToJME({tok: wrapValue(val.value())}); case 'list of numbers': case 'list of strings': return treeToJME({tok: wrapValue(val.values())}); case 'json': JSON.parse(val.value()); var json = treeToJME({tok: wrapValue(val.value())}); return 'safe('+json+')'; } } catch(e) { this.definitionError(e); return; } } },this); this.dependencies = ko.observableArray([]); this.isDependency = ko.computed(function() { var currentVariable = q.currentVariable(); if(!currentVariable) return false; return currentVariable.dependencies().contains(this.name().toLowerCase()); },this); this.dependenciesObjects = ko.computed(function() { var deps = this.dependencies(); return this.dependencies().map(function(name) { var obj = q.getVariable(name); if(obj) { name = obj.name(); } var out = { name: name, obj: obj, notdefined: !obj, title: !obj ? 'Not defined. Click to add this variable.' : '', setCurrent: function() { if(obj) { q.currentVariable(obj); } else { var v = q.addVariable(); v.name(name); q.baseVariableGroup.variables.push(v); } } }; return out; }); },this); this.usedIn = ko.computed(function() { var v = this; return q.variables().filter(function(v2) { return v2.dependencies().contains(v.name().toLowerCase()); }); },this); this.value = ko.observable(''); this.thisLocked = ko.observable(false); this.locked = ko.computed(function() { return this.usedIn().some(function(v){return v.locked()}) || this.thisLocked(); },this); this.error = ko.observable(''); this.anyError = ko.computed(function() { if(this.question.variablesTest.conditionError()) { return "Error in testing condition"; } else if(!(this.question.variablesTest.conditionSatisfied())) { return "Testing condition not satisfied"; } else { return this.error(); } },this); this.display = ko.computed(function() { var v; if(this.anyError()) { return this.anyError(); } else if(v = this.value()) { switch(v.type) { case 'string': return Numbas.util.escapeHTML(v.value); case 'list': return 'List of '+v.value.length+' '+Numbas.util.pluralise(v.value.length,'item','items'); case 'html': if(v.value.length==1 && v.value[0].tagName=='IMG') { var src = v.value[0].getAttribute('src'); return '<img src="'+src+'" title="'+src+'">'; } return 'HTML node'; default: return Numbas.jme.display.treeToJME({tok:v}); } } else { return ''; } },this); this.remove = function() { q.variables.remove(this); this.group().variables.remove(this); if(this==q.currentVariable()) { q.selectFirstVariable(); } }; if(data) this.load(data); } Variable.prototype = { templateTypes: [ {id: 'anything', name: 'JME code'}, {id: 'number', name: 'Number'}, {id: 'range', name: 'Range of numbers'}, {id: 'randrange', name: 'Random number from a range'}, {id: 'string', name: 'Short text string'}, {id: 'long string', name: 'Long text string'}, {id: 'list of numbers', name: 'List of numbers'}, {id: 'list of strings', name: 'List of short text strings'}, {id: 'json', name: 'JSON data'} ], load: function(data) { tryLoad(data,['name','description'],this); if('templateType' in data) { for(var i=0;i<this.templateTypes.length;i++) { if(this.templateTypes[i].id==data.templateType) { this.templateType(this.templateTypes[i]); break; } } } if('definition' in data) { this.definitionToTemplate(data.definition); } this.question.baseVariableGroup.variables.push(this); }, toJSON: function() { var obj = { name: this.name(), group: this.group() ? this.group().name() : null, definition: this.definition(), description: this.description(), templateType: this.templateType().id, } return obj; }, definitionToTemplate: function(definition) { var templateType = this.templateType().id; var templateTypeValues = this.templateTypeValues[templateType]; try { var tree = Numbas.jme.compile(definition); switch(templateType) { case 'anything': templateTypeValues.definition(definition); break; case 'number': templateTypeValues.value(Numbas.jme.evaluate(definition,Numbas.jme.builtinScope).value); break; case 'range': var rule = new Numbas.jme.display.Rule('?;a..?;b#?;c',[]); var m = rule.match(tree); templateTypeValues.min(Numbas.jme.evaluate(m.a,Numbas.jme.builtinScope).value); templateTypeValues.max(Numbas.jme.evaluate(m.b,Numbas.jme.builtinScope).value); templateTypeValues.step(Numbas.jme.evaluate(m.c,Numbas.jme.builtinScope).value); break; case 'randrange': var rule = new Numbas.jme.display.Rule('random(?;a..?;b#?;c)',[]); var m = rule.match(tree); templateTypeValues.min(Numbas.jme.evaluate(m.a,Numbas.jme.builtinScope).value); templateTypeValues.max(Numbas.jme.evaluate(m.b,Numbas.jme.builtinScope).value); templateTypeValues.step(Numbas.jme.evaluate(m.c,Numbas.jme.builtinScope).value); break; case 'string': case 'long string': templateTypeValues.value(tree.tok.value); break; case 'list of numbers': templateTypeValues.commaValue(tree.args.map(function(t){return Numbas.jme.evaluate(t,Numbas.jme.builtinScope).value}).join(' , ')); break; case 'list of strings': templateTypeValues.values(tree.args.map(function(t){return t.tok.value})); case 'json': templateTypeValues.value(tree.args[0].tok.value); } } catch(e) { console.log(e); } }, toggleLocked: function(v,e) { this.thisLocked(!this.thisLocked()); e.preventDefault(); } } function CustomFunction(q,data) { this.name = ko.observable(''); this.types = jmeTypes; this.parameters = ko.observableArray([]) this.type = ko.observable('number'); this.definition = ko.observable(''); this.languages = ['jme','javascript']; this.language = ko.observable('jme'); this.error = ko.observable(''); this.remove = function() { if(confirm("Remove this function?")) q.functions.remove(this); }; if(data) this.load(data); } CustomFunction.prototype = { load: function(data) { var f = this; tryLoad(data,['name','type','definition','language'],this); if('parameters' in data) { data.parameters.map(function(p) { f.parameters.push(new FunctionParameter(f,p[0],p[1])); }); } }, toJSON: function() { var parameters = this.parameters().map(function(p) { return [p.name(), p.type()]; }); return { parameters: parameters, type: this.type(), language: this.language(), definition: this.definition() }; }, addParameter: function() { this.parameters.push(new FunctionParameter(this,'','number')); } }; function FunctionParameter(f,name,type) { this.name = ko.observable(name); this.type = ko.observable(type); this.remove = function() { f.parameters.remove(this); } }; function Script(name,displayName,defaultOrder,helpURL) { this.name = name; this.orderOptions = [ {niceName: 'instead of', value: 'instead'}, {niceName: 'after', value: 'after'}, {niceName: 'before', value: 'before'} ]; this.orderItem = ko.observable(this.orderOptions[0]); this.order = ko.computed({ read: function() { return this.orderItem().value; }, write: function(value) { for(var i=0;i<this.orderOptions.length;i++) { if(this.orderOptions[i].value==value) { return this.orderItem(this.orderOptions[i]); } } } },this); this.order(defaultOrder); this.displayName = displayName; this.script = ko.observable(''); this.helpURL = helpURL; this.active = ko.computed(function() { return this.script().trim().length>0; },this); } function Part(q,parent,parentList,data) { var p = this; this.q = q; this.prompt = Editor.contentObservable(''); this.parent = ko.observable(parent); this.parentList = parentList; this.open = ko.observable(true); this.toggleOpen = function() { p.open(!p.open()); } this.types = partTypes.map(function(data){return new PartType(p,data);}); this.isRootPart = ko.computed(function() { return !this.parent(); },this); this.isGap = ko.computed(function(){ return this.parent() && this.parent().type().name=='gapfill' && !this.parent().steps().contains(this); },this); this.isStep = ko.computed(function() { return this.parent() && this.parent().steps().contains(this); },this); var nonGapTypes = ['information','gapfill']; this.availableTypes = ko.computed(function() { var nonStepTypes = ['gapfill']; if(this.isGap()) return this.types.filter(function(t){return nonGapTypes.indexOf(t.name)==-1}); else if(this.isStep()) return this.types.filter(function(t){return nonStepTypes.indexOf(t.name)==-1}); else return this.types; },this); this.type = ko.observable(this.availableTypes()[0]); this.canBeReplacedWithGap = ko.computed(function() { return !(this.isGap() || this.isStep() || nonGapTypes.indexOf(this.type().name)>=0); },this); this.indexLabel = ko.computed(function() { var i = this.parentList.indexOf(this); if(this.isGap() || this.isStep()) { i = i; } else { i = Numbas.util.letterOrdinal(i); } return i; },this); this.levelName = ko.computed(function() { return this.isGap() ? 'gap' : this.isStep() ? 'step' : 'part'; },this); this.header = ko.computed(function() { if(this.isGap()) { return 'Gap '+this.indexLabel()+'. '; } else if(this.isStep()) { return 'Step '+this.indexLabel()+'. '; } else if(this.isRootPart()) { return 'Part '+this.indexLabel()+') '; } },this); this.path = ko.computed(function() { var i = Math.max(this.parentList.indexOf(this),0); if(this.isGap()) { return this.parent().path()+'g'+i; } else if(this.isStep()) { return this.parent().path()+'s'+i; } else { return 'p'+i; } },this); this.nicePath = ko.computed(function() { return Numbas.util.capitalise(Numbas.util.nicePartName(this.path())); },this); this.tabs = ko.computed(function() { var tabs = []; if(!this.isGap()) tabs.push(new Editor.Tab('prompt','Prompt','blackboard')); if(this.type().has_marks) tabs.push(new Editor.Tab('marking','Marking','pencil')); tabs = tabs.concat(this.type().tabs); tabs.push(new Editor.Tab('scripts','Scripts','wrench')); tabs.push(new Editor.Tab('adaptivemarking','Adaptive marking','transfer')); return tabs; },this); this.realCurrentTab = ko.observable(this.tabs()[0]); this.currentTab = ko.computed({ read: function() { if(this.tabs().indexOf(this.realCurrentTab())==-1) { this.realCurrentTab(this.tabs()[0]); return this.tabs()[0]; } else return this.realCurrentTab(); }, write: this.realCurrentTab },this); this.marks = ko.observable(1); this.realMarks = ko.computed(function() { switch(this.type().name) { case 'information': case 'gapfill': case 'm_n_x': case 'm_n_2': case '1_n_2': return 0; default: return this.marks(); } },this); this.steps = ko.observableArray([]); this.stepsPenalty = ko.observable(0); this.gaps = ko.observableArray([]); this.addGap = function() { var gap = new Part(p.q,p,p.gaps); p.gaps.push(gap); } this.showCorrectAnswer = ko.observable(true); this.variableReplacements = ko.observableArray([]); this.addVariableReplacement = function() { p.variableReplacements.push(new VariableReplacement(p)); } this.deleteVariableReplacement = function(vr) { p.variableReplacements.remove(vr); } this.variableReplacementStrategies = [ {name: 'originalfirst', niceName: 'Try without replacements first'}, {name: 'alwaysreplace', niceName: 'Always replace variables'} ]; this.variableReplacementStrategy = ko.observable(this.variableReplacementStrategies[0]) this.replacementRandomDependencies = ko.computed(function() { var names = this.variableReplacements().map(function(vr) {return vr.variable()}); var randomDependencies = this.q.randomDependencies(names); return randomDependencies; },this); this.scripts = [ new Script('constructor','When the part is created','after','http://numbas-editor.readthedocs.io/en/latest/question/reference.html#term-when-the-part-is-created'), new Script('mark','Mark student\'s answer','instead','http://numbas-editor.readthedocs.io/en/latest/question/reference.html#term-mark-student-s-answer'), new Script('validate','Validate student\'s answer','instead','http://numbas-editor.readthedocs.io/en/latest/question/reference.html#term-validate-student-s-answer') ]; this.types.map(function(t){p[t.name] = t.model}); if(data) this.load(data); } Part.prototype = { copy: function() { var data = this.toJSON(); var p = new Part(this.q,this.parent(),this.parentList,data); this.parentList.push(p); p.scrollTo(); }, scrollTo: function() { var p = this; setTimeout(function() {window.scrollTo(0,$('.part[data-path="'+p.path()+'"]').offset().top-10)},0); }, replaceWithGapfill: function() { var gapFill = new Part(this.q,this.parent(),this.parentList); gapFill.setType('gapfill'); this.parentList.splice(this.parentList.indexOf(this),1,gapFill); gapFill.gaps.push(this); this.parentList = gapFill.gaps; this.parent(gapFill); gapFill.prompt(this.prompt()+'\n<p>[[0]]</p>'); this.prompt(''); gapFill.steps(this.steps()); gapFill.steps().map(function(step){ step.parent(gapFill); step.parentList = gapFill.steps; }); this.steps([]); }, canMove: function(direction) { var parentList = ko.utils.unwrapObservable(this.parentList); switch(direction) { case 'up': return parentList.indexOf(this)>0; case 'down': return parentList.indexOf(this)<parentList.length-1; } }, addStep: function() { var step = new Part(this.q,this,this.steps); this.steps.push(step); }, remove: function() { if(confirm("Remove this part?")) { this.parentList.remove(this); } }, moveUp: function() { var i = this.parentList.indexOf(this); if(i>0) { this.parentList.remove(this); ko.tasks.runEarly(); this.parentList.splice(i-1,0,this); this.scrollTo(); } }, moveDown: function() { var i = this.parentList.indexOf(this); this.parentList.remove(this); ko.tasks.runEarly(); this.parentList.splice(i+1,0,this); this.scrollTo(); }, setType: function(name) { name = name.toLowerCase(); for(var i=0;i<this.types.length;i++) { if(this.types[i].name == name) { this.type(this.types[i]); return; } } }, toJSON: function() { var o = { type: this.type().name, marks: this.realMarks(), showCorrectAnswer: this.showCorrectAnswer(), scripts: {}, variableReplacements: this.variableReplacements().map(function(vr){return vr.toJSON()}), variableReplacementStrategy: this.variableReplacementStrategy().name }; if(this.prompt()) o.prompt = this.prompt(); if(this.steps().length) { o.stepsPenalty = this.stepsPenalty(), o.steps = this.steps().map(function(s){return s.toJSON();}); } this.scripts.map(function(s) { if(s.active()) { o.scripts[s.name] = { script: s.script(), order: s.order() }; } }); try{ this.type().toJSON(o); }catch(e) { console.log(e); console.log(e.stack); throw(e); } return o; }, load: function(data) { var p = this; for(var i=0;i<this.types.length;i++) { if(this.types[i].name == data.type.toLowerCase()) this.type(this.types[i]); } tryLoad(data,['marks','prompt','stepsPenalty','showCorrectAnswer'],this); if(data.steps) { var parentPart = this.isGap() ? this.parent : this; data.steps.map(function(s) { this.steps.push(new Part(this.q,this,this.steps,s)); },parentPart); } if(data.scripts) { for(var name in data.scripts) { for(var i=0;i<this.scripts.length;i++) { if(this.scripts[i].name==name) { tryLoad(data.scripts[name],['script','order'],this.scripts[i]); break; } } } } p.variableReplacementStrategies.map(function(s) { if(s.name==data.variableReplacementStrategy) { p.variableReplacementStrategy(s); } }); if(data.variableReplacements) { data.variableReplacements.map(function(d) { var vr = new VariableReplacement(p,d); p.variableReplacements.push(vr); }); } try{ this.type().load(data); }catch(e){ console.log(e); console.log(e.stack); throw(e); } } }; function VariableReplacement(part,data) { this.part = part; this.variable = ko.observable(''); this.replacement = ko.observable(null); this.must_go_first = ko.observable(false); this.availableParts = ko.computed(function() { var p = this.part return p.q.allParts().filter(function(p2){ return p!=p2; }); },this); if(data) { this.load(data); } } VariableReplacement.prototype = { toJSON: function() { return { variable: this.variable(), part: this.replacement(), must_go_first: this.must_go_first() } }, load: function(data) { tryLoad(data,['variable','must_go_first'],this); var path = data.part; this.replacement(data.part); } } function PartType(part,data) { this.name = data.name; this.part = part; this.niceName = data.niceName; this.has_marks = data.has_marks || false; this.tabs = data.tabs || []; this.model = data.model ? data.model(part) : {}; this.toJSONFn = data.toJSON || function() {}; this.loadFn = data.load || function() {}; } PartType.prototype = { toJSON: function(data) { this.toJSONFn.apply(this.model,[data,this.part]); }, load: function(data) { this.loadFn.apply(this.model,[data,this.part]); } }; var partTypes = [ { name: 'information', niceName: 'Information only' }, { name: 'extension', niceName: 'Extension', has_marks: true }, { name: 'gapfill', niceName: 'Gap-fill', has_marks: true, toJSON: function(data,part) { if(part.gaps().length) { data.gaps = part.gaps().map(function(g) { return g.toJSON(); }); } }, load: function(data,part) { if(data.gaps) { data.gaps.map(function(g) { part.gaps.push(new Part(part.q,part,part.gaps,g)); }); } } }, { name:'jme', niceName: 'Mathematical expression', has_marks: true, tabs: [ new Editor.Tab('checking-accuracy','Accuracy','scale'), new Editor.Tab('restrictions','String restrictions','text-background') ], model: function() { var model = { answer: ko.observable(''), answerSimplification: ko.observable(''), showPreview: ko.observable(true), checkingTypes: [ {name:'absdiff',niceName:'Absolute difference', accuracy: ko.observable(0.001)}, {name:'reldiff',niceName:'Relative difference', accuracy: ko.observable(0.001)}, {name:'dp',niceName:'Decimal points', accuracy: ko.observable(3)}, {name:'sigfig',niceName:'Significant figures', accuracy: ko.observable(3)} ], failureRate: ko.observable(1), vset: { points: ko.observable(5), start: ko.observable(0), end: ko.observable(1) }, maxlength: { length: ko.observable(0), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, minlength: { length: ko.observable(0), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, musthave: { strings: ko.observableArray([]), showStrings: ko.observable(false), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, notallowed: { strings: ko.observableArray([]), showStrings: ko.observable(false), partialCredit: ko.observable(0), message: Editor.contentObservable('') }, checkVariableNames: ko.observable(false), expectedVariableNames: ko.observableArray([]) }; model.checkingType = ko.observable(model.checkingTypes[0]); return model; }, toJSON: function(data) { data.answer = this.answer(); if(this.answerSimplification()) data.answersimplification = this.answerSimplification(); data.showpreview = this.showPreview(); data.checkingtype = this.checkingType().name; data.checkingaccuracy = this.checkingType().accuracy(); data.vsetrangepoints = this.vset.points(); data.vsetrange = [this.vset.start(),this.vset.end()]; data.checkvariablenames = this.checkVariableNames(); data.expectedvariablenames = this.expectedVariableNames(); if(this.maxlength.length()) { data.maxlength = { length: this.maxlength.length(), partialCredit: this.maxlength.partialCredit(), message: this.maxlength.message() }; } if(this.minlength.length()) { data.minlength = { length: this.minlength.length(), partialCredit: this.minlength.partialCredit(), message: this.minlength.message() }; } if(this.musthave.strings().length) { data.musthave = { strings: this.musthave.strings(), showStrings: this.musthave.showStrings(), partialCredit: this.musthave.partialCredit(), message: this.musthave.message() }; } if(this.notallowed.strings().length) { data.notallowed = { strings: this.notallowed.strings(), showStrings: this.notallowed.showStrings(), partialCredit: this.notallowed.partialCredit(), message: this.notallowed.message() }; } }, load: function(data) { tryLoad(data,['answer','answerSimplification','checkVariableNames','expectedVariableNames','showPreview'],this); for(var i=0;i<this.checkingTypes.length;i++) { if(this.checkingTypes[i].name == data.checkingtype) this.checkingType(this.checkingTypes[i]); } tryLoad(data,'checkingaccuracy',this.checkingType(),'accuracy'); tryLoad(data,'vsetrangepoints',this.vset,'points'); if('vsetrange' in data) { this.vset.start(data.vsetrange[0]); this.vset.end(data.vsetrange[1]); } tryLoad(data.maxlength,['length','partialCredit','message'],this.maxlength); tryLoad(data.minlength,['length','partialCredit','message'],this.minlength); tryLoad(data.musthave,['strings','showStrings','partialCredit','message'],this.musthave); tryLoad(data.notallowed,['strings','showStrings','partialCredt','message'],this.notallowed); } }, { name:'numberentry', niceName: 'Number entry', has_marks: true, tabs: [], model: function() { var model = { minValue: ko.observable(''), maxValue: ko.observable(''), correctAnswerFraction: ko.observable(false), integerAnswer: ko.observable(false), integerPartialCredit: ko.observable(0), allowFractions: ko.observable(false), precisionTypes: [ {name: 'none', niceName: 'None'}, {name: 'dp', niceName: 'Decimal places'}, {name: 'sigfig', niceName: 'Significant figures'} ], precision: ko.observable(0), precisionPartialCredit: ko.observable(0), precisionMessage: ko.observable('You have not given your answer to the correct precision.'), strictPrecision: ko.observable(true), showPrecisionHint: ko.observable(true) }; model.notationStyles = [ { code: 'plain', name: 'English (Plain)', description: 'No thousands separator; dot for decimal point.', }, { code: 'en', name:'English', description:'Commas separate thousands; dot for decimal point.', }, { code: 'si-en', name:'SI (English)', description:'Spaces separate thousands; dot for decimal point.', }, { code: 'si-fr', name:'SI (French)', description:'Spaces separate thousands; comma for decimal point.', }, { code: 'eu', name: 'Continental', description:'Dots separate thousands; comma for decimal point.', }, { code: 'plain-eu', name:'Continental (Plain)', description:'No thousands separator; comma for decimal point.', }, { code: 'ch', name:'Swiss', description:'Apostrophes separate thousands; dot for decimal point.', }, { code: 'in', name:'Indian', description:'Commas separate groups; rightmost group is 3 digits, other groups 2 digits; dot for decimal point.', } ]; model.allowedNotationStyles = ko.observableArray(model.notationStyles.filter(function(s){return ['plain','en','si-en'].contains(s.code)})); model.correctAnswerStyle = ko.observable(model.allowedNotationStyles()[0] || model.notationStyles[0]); model.precisionType = ko.observable(model.precisionTypes[0]); model.precisionWord = ko.computed(function() { switch(this.precisionType().name) { case 'dp': return 'Digits'; case 'sigfig': return 'Significant figures'; } },model); return model; }, toJSON: function(data) { data.minValue = this.minValue(); data.maxValue = this.maxValue(); data.correctAnswerFraction = this.correctAnswerFraction(); if(this.integerAnswer()) { data.integerAnswer = this.integerAnswer(); data.integerPartialCredit= this.integerPartialCredit(); } data.allowFractions = this.allowFractions(); if(this.precisionType().name!='none') { data.precisionType = this.precisionType().name; data.precision = this.precision(); data.precisionPartialCredit = this.precisionPartialCredit(); data.precisionMessage = this.precisionMessage(); data.strictPrecision = this.strictPrecision(); data.showPrecisionHint = this.showPrecisionHint(); } data.notationStyles = this.allowedNotationStyles().map(function(s){return s.code}); if(this.correctAnswerStyle()) { data.correctAnswerStyle = this.correctAnswerStyle().code; } }, load: function(data) { tryLoad(data,['minValue','maxValue','correctAnswerFraction','integerAnswer','integerPartialCredit','allowFractions','precision','precisionPartialCredit','precisionMessage','precisionType','strictPrecision','showPrecisionHint'],this); if('answer' in data) { this.minValue(data.answer); this.maxValue(data.answer); } for(var i=0;i<this.precisionTypes.length;i++) { if(this.precisionTypes[i].name == this.precisionType()) this.precisionType(this.precisionTypes[i]); } if('notationStyles' in data) { this.allowedNotationStyles(this.notationStyles.filter(function(s) { return data.notationStyles.contains(s.code); })); } if('correctAnswerStyle' in data) { var style = this.notationStyles.filter(function(s){return s.code==data.correctAnswerStyle})[0]; if(style) { this.correctAnswerStyle(style); } } } }, { name: 'matrix', niceName: 'Matrix entry', has_marks: true, tabs: [], model: function() { var model = { correctAnswer: ko.observable(''), correctAnswerFractions: ko.observable(false), numRows: ko.observable(1), numColumns: ko.observable(1), allowResize: ko.observable(true), tolerance: ko.observable(0), markPerCell: ko.observable(false), allowFractions: ko.observable(false), precisionTypes: [ {name: 'none', niceName: 'None'}, {name: 'dp', niceName: 'Decimal places'}, {name: 'sigfig', niceName: 'Significant figures'} ], precision: ko.observable(0), precisionPartialCredit: ko.observable(0), precisionMessage: ko.observable('You have not given your answer to the correct precision.'), strictPrecision: ko.observable(true) } model.precisionType = ko.observable(model.precisionTypes[0]); model.precisionWord = ko.computed(function() { switch(this.precisionType().name) { case 'dp': return 'Digits'; case 'sigfig': return 'Significant figures'; } },model); return model; }, toJSON: function(data) { data.correctAnswer = this.correctAnswer(); data.correctAnswerFractions = this.correctAnswerFractions(); data.numRows = this.numRows(); data.numColumns = this.numColumns(); data.allowResize = this.allowResize(); data.tolerance = this.tolerance(); data.markPerCell = this.markPerCell(); data.allowFractions = this.allowFractions(); if(this.precisionType().name!='none') { data.precisionType = this.precisionType().name; data.precision = this.precision(); data.precisionPartialCredit = this.precisionPartialCredit(); data.precisionMessage = this.precisionMessage(); data.strictPrecision = this.strictPrecision(); } }, load: function(data) { tryLoad(data,['correctAnswer','correctAnswerFractions','numRows','numColumns','allowResize','tolerance','markPerCell','allowFractions','precision','precisionPartialCredit','precisionMessage','precisionType','strictPrecision'],this); for(var i=0;i<this.precisionTypes.length;i++) { if(this.precisionTypes[i].name == this.precisionType()) this.precisionType(this.precisionTypes[i]); } } }, { name:'patternmatch', niceName: 'Match text pattern', has_marks: true, tabs: [], model: function() { return { answer: ko.observable(''), displayAnswer: Editor.contentObservable(''), caseSensitive: ko.observable(false), partialCredit: ko.observable(0) } }, toJSON: function(data) { data.answer = this.answer(); data.displayAnswer = this.displayAnswer(); if(this.caseSensitive()) { data.caseSensitive = this.caseSensitive(); data.partialCredit = this.partialCredit(); } }, load: function(data) { tryLoad(data,['answer','displayAnswer','caseSensitive','partialCredit'],this); } }, { name:'1_n_2', niceName: 'Choose one from a list', tabs: [ new Editor.Tab('marking','Marking','pencil'), new Editor.Tab('choices','Choices','list') ], model: function(part) { var model = { minMarks: ko.observable(0), maxMarks: ko.observable(0), shuffleChoices: ko.observable(false), displayColumns: ko.observable(0), customMatrix: ko.observable(''), customChoices: ko.observable(false), customChoicesExpression: ko.observable(''), choices: ko.observableArray([]) }; var _customMarking = ko.observable(false); model.customMarking = ko.computed({ read: function() { return _customMarking() || this.customChoices(); }, write: function(v) { return _customMarking(v); } },model); model.addChoice = function() { var c = { content: Editor.contentObservable('Choice '+(model.choices().length+1)), marks: ko.observable(0), distractor: Editor.contentObservable(''), answers: ko.observableArray([]) }; c.remove = function() { model.removeChoice(c); } model.choices.push(c); return c; }; model.removeChoice = function(choice) { model.choices.remove(choice); }; return model; }, toJSON: function(data) { data.minMarks = this.minMarks(); data.maxMarks = this.maxMarks(); data.shuffleChoices = this.shuffleChoices(); data.displayType = 'radiogroup'; data.displayColumns = this.displayColumns(); if(this.customChoices()) { data.choices = this.customChoicesExpression(); } else { var choices = this.choices(); data.choices = choices.map(function(c){return c.content()}); } if(this.customMarking()) { data.matrix = this.customMatrix(); } else { var matrix = []; var distractors = []; for(var i=0;i<choices.length;i++) { matrix.push(choices[i].marks()); distractors.push(choices[i].distractor()); } data.matrix = matrix; } data.distractors = distractors; }, load: function(data) { tryLoad(data,['minMarks','maxMarks','shuffleChoices','displayColumns'],this); if(typeof data.matrix == 'string') { this.customMarking(true); this.customMatrix(data.matrix); } if(typeof data.choices == 'string') { this.customChoices(true); this.customChoicesExpression(data.choices); } else { for(var i=0;i<data.choices.length;i++) { var c = this.addChoice(data.choices[i]); c.content(data.choices[i] || ''); if(!this.customMarking()) { c.marks(data.matrix[i] || 0); } if('distractors' in data) { c.distractor(data.distractors[i] || ''); } } } } }, { name:'m_n_2', niceName: 'Choose several from a list', tabs: [ new Editor.Tab('marking','Marking','pencil'), new Editor.Tab('choices','Choices','list') ], model: function() { var model = { minMarks: ko.observable(0), maxMarks: ko.observable(0), minAnswers: ko.observable(0), maxAnswers: ko.observable(0), shuffleChoices: ko.observable(false), displayColumns: ko.observable(0), customMatrix: ko.observable(''), warningType: ko.observable(''), warningTypes: [ {name: 'none', niceName: 'Do nothing'}, {name: 'warn', niceName: 'Warn'}, {name: 'prevent', niceName: 'Prevent submission'} ], customChoices: ko.observable(false), customChoicesExpression: ko.observable(''), choices: ko.observableArray([]), }; var _customMarking = ko.observable(false); model.customMarking = ko.computed({ read: function() { return _customMarking() || this.customChoices(); }, write: function(v) { return _customMarking(v); } },model); model.addChoice = function() { var c = { content: Editor.contentObservable('Choice '+(model.choices().length+1)), marks: ko.observable(0), distractor: Editor.contentObservable(''), answers: ko.observableArray([]) }; c.remove = function() { model.removeChoice(c); } model.choices.push(c); return c; }; model.removeChoice = function(choice) { model.choices.remove(choice); }; return model; }, toJSON: function(data) { data.minMarks = this.minMarks(); data.maxMarks = this.maxMarks(); data.shuffleChoices = this.shuffleChoices(); data.displayType = 'checkbox'; data.displayColumns = this.displayColumns(); data.minAnswers = this.minAnswers(); data.maxAnswers = this.maxAnswers(); data.warningType = this.warningType().name; if(this.customChoices()) { data.choices = this.customChoicesExpression(); } else { var choices = this.choices(); data.choices = choices.map(function(c){return c.content()}); } if(this.customMarking()) { data.matrix = this.customMatrix(); } else { var matrix = []; var distractors = []; for(var i=0;i<choices.length;i++) { matrix.push(choices[i].marks()); distractors.push(choices[i].distractor()); } data.matrix = matrix; } data.distractors = distractors; }, load: function(data) { tryLoad(data,['minMarks','maxMarks','minAnswers','maxAnswers','shuffleChoices','displayColumns'],this); if(typeof data.matrix == 'string') { this.customMarking(true); this.customMatrix(data.matrix); } for(var i=0;i<this.warningTypes.length;i++) { if(this.warningTypes[i].name==data.warningType) { this.warningType(this.warningTypes[i]); } } if(typeof data.choices == 'string') { this.customChoices(true); this.customChoicesExpression(data.choices); } else { for(var i=0;i<data.choices.length;i++) { var c = this.addChoice(data.choices[i]); c.content(data.choices[i] || ''); if(!this.customMarking()) { c.marks(data.matrix[i] || 0); } if('distractors' in data) { c.distractor(data.distractors[i] || ''); } } } } }, { name:'m_n_x', niceName: 'Match choices with answers', tabs: [ new Editor.Tab('choices','Choices','list'), new Editor.Tab('answers','Answers','list'), new Editor.Tab('matrix','Marking matrix','th'), new Editor.Tab('marking','Marking options','pencil') ], model: function() { var model = { minMarks: ko.observable(0), maxMarks: ko.observable(0), minAnswers: ko.observable(0), maxAnswers: ko.observable(0), shuffleChoices: ko.observable(false), shuffleAnswers: ko.observable(false), displayType:ko.observable(''), customMatrix: ko.observable(''), warningType: ko.observable(''), warningTypes: [ {name: 'none', niceName: 'Do nothing'}, {name: 'warn', niceName: 'Warn'}, {name: 'prevent', niceName: 'Prevent submission'} ], displayTypes: [ {name: 'radiogroup', niceName: 'One from each row'}, {name: 'checkbox', niceName: 'Checkboxes'} ], customChoices: ko.observable(false), customChoicesExpression: ko.observable(''), customAnswers: ko.observable(false), customAnswersExpression: ko.observable(''), choices: ko.observableArray([]), answers: ko.observableArray([]), layoutType: ko.observable('all'), layoutTypes: [ {name: 'all', niceName: 'Show all options'}, {name: 'lowertriangle', niceName: 'Lower triangle'}, {name: 'strictlowertriangle', niceName: 'Lower triangle (no diagonal)'}, {name: 'uppertriangle', niceName: 'Upper triangle'}, {name: 'strict uppertriangle', niceName: 'Upper triangle (no diagonal)'}, {name: 'expression', niceName: 'Custom expression'} ], layoutExpression: ko.observable('') }; model.matrix = Editor.editableGrid( ko.computed(function() { return model.choices().length; }), ko.computed(function() { return model.answers().length; }), function() { return { marks: ko.observable(0), distractor: ko.observable('') } } ); var _customMarking = ko.observable(false); model.customMarking = ko.computed({ read: function() { return _customMarking() || this.customChoices() || this.customAnswers(); }, write: function(v) { return _customMarking(v); } },model); model.addChoice = function() { var c = { content: Editor.contentObservable('Choice '+(model.choices().length+1)), marks: ko.observable(0), distractor: Editor.contentObservable('') }; c.remove = function() { model.removeChoice(c); } model.choices.push(c); return c; }, model.removeChoice = function(choice) { model.choices.remove(choice); }; model.addAnswer = function() { var a = { content: ko.observable('Answer '+(model.answers().length+1)) }; a.remove = function() { model.removeAnswer(a); } model.answers.push(a); return a; }; model.showMarkingMatrix = ko.computed(function() { var hasChoices = model.customChoices() || model.choices().length; var hasAnswers = model.customAnswers() || model.answers().length; return hasChoices && hasAnswers && !model.customMarking(); },this); model.removeAnswer = function(answer) { var n = model.answers.indexOf(answer); model.answers.remove(answer); }; return model; }, toJSON: function(data) { data.minMarks = this.minMarks(); data.maxMarks = this.maxMarks(); data.minAnswers = this.minAnswers(); data.maxAnswers = this.maxAnswers(); data.shuffleChoices = this.shuffleChoices(); data.shuffleAnswers = this.shuffleAnswers(); data.displayType = this.displayType().name; data.warningType = this.warningType().name; if(this.customChoices()) { data.choices = this.customChoicesExpression(); } else { var choices = this.choices(); data.choices = choices.map(function(c){return c.content()}); } if(this.customMarking()) { data.matrix = this.customMatrix(); } else { data.matrix = this.matrix().map(function(r){ return r().map(function(c) { return c.marks() }) }); } data.layout = {type: this.layoutType().name, expression: this.layoutExpression()} if(this.customAnswers()) { data.answers = this.customAnswersExpression(); } else { var answers = this.answers(); data.answers = answers.map(function(a){return a.content()}); } }, load: function(data) { tryLoad(data,['minMarks','maxMarks','minAnswers','maxAnswers','shuffleChoices','shuffleAnswers'],this); for(var i=0;i<this.warningTypes.length;i++) { if(this.warningTypes[i].name==data.warningType) { this.warningType(this.warningTypes[i]); } } for(var i=0;i<this.displayTypes.length;i++) { if(this.displayTypes[i].name==data.displayType) { this.displayType(this.displayTypes[i]); } } if(data.layout) { for(var i=0;i<this.layoutTypes.length;i++) { if(this.layoutTypes[i].name==data.layout.type) { this.layoutType(this.layoutTypes[i]); } } tryLoad(data.layout,['expression'],this,['layoutExpression']); } if(typeof data.answers == 'string') { this.customAnswers(true); this.customAnswersExpression(data.answers); } else { for(var i=0;i<data.answers.length;i++) { var a = this.addAnswer(); a.content(data.answers[i]); } } if(typeof data.choices == 'string') { this.customChoices(true); this.customChoicesExpression(data.choices); } else { for(var i=0;i<data.choices.length;i++) { var c = this.addChoice(data.choices[i]); c.content(data.choices[i]); } } if(typeof data.matrix == 'string') { this.customMarking(true); this.customMatrix(data.matrix); } else { for(var i=0;i<data.matrix.length;i++) { for(var j=0;j<data.matrix[i].length;j++) { this.matrix()[i]()[j].marks(data.matrix[i][j]); } } } } } ]; var deps = ['jme-display','jme-variables','jme','editor-extras']; for(var i=0;i<item_json.numbasExtensions.length;i++) { var extension = item_json.numbasExtensions[i]; if(extension.hasScript) { deps.push('extensions/'+extension.location+'/'+extension.location+'.js'); } } Numbas.queueScript('start-editor',deps,function() { try { viewModel = new Question(item_json.itemJSON); viewModel.set_tab_from_hash(); ko.options.deferUpdates = true; ko.applyBindings(viewModel); try { document.body.classList.add('loaded'); } catch(e) { document.body.className += ' loaded'; } $('.timeline').mathjax(); } catch(e) { $('.page-loading').hide(); $('.page-error') .show() .find('.trace') .html(e.message) ; throw(e); } }); Mousetrap.bind(['ctrl+b','command+b'],function() { window.open(item_json.previewURL,item_json.previewWindow); }); });
"JSON code" variables get decoded the template is now `json_decode(safe(<json>))`
editor/static/js/question/edit.js
"JSON code" variables get decoded
<ide><path>ditor/static/js/question/edit.js <ide> case 'json': <ide> JSON.parse(val.value()); <ide> var json = treeToJME({tok: wrapValue(val.value())}); <del> return 'safe('+json+')'; <add> return 'json_decode(safe('+json+'))'; <ide> } <ide> } catch(e) { <ide> this.definitionError(e);
Java
bsd-3-clause
4192b95ce4aa9f643d6cf5d8ab74a51a6e3507e4
0
bluerover/6lbr,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,bluerover/6lbr,arurke/contiki
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: GUI.java,v 1.67 2008/02/07 22:25:26 fros4943 Exp $ */ package se.sics.cooja; import java.awt.*; import java.awt.event.*; import java.beans.PropertyVetoException; import java.io.*; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import se.sics.cooja.MoteType.MoteTypeCreationException; import se.sics.cooja.contikimote.*; import se.sics.cooja.dialogs.*; import se.sics.cooja.plugins.*; /** * Main file of COOJA Simulator. Typically contains a visualizer for the * simulator, but can also be started without visualizer. * * This class loads external Java classes (in project directories), and handles the * COOJA plugins as well as the configuration system. If provides a number of * help methods for the rest of the COOJA system, and is the starting point for * loading and saving simulation configs. * * @author Fredrik Osterlind */ public class GUI { /** * External tools default Win32 settings filename. */ public static final String EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME = "/external_tools_win32.config"; /** * External tools default Mac OS X settings filename. */ public static final String EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME = "/external_tools_macosx.config"; /** * External tools default Linux/Unix settings filename. */ public static final String EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME = "/external_tools_linux.config"; /** * External tools user settings filename. */ public static final String EXTERNAL_TOOLS_USER_SETTINGS_FILENAME = ".cooja.user.properties"; public static File externalToolsUserSettingsFile = new File(System.getProperty("user.home"), EXTERNAL_TOOLS_USER_SETTINGS_FILENAME); private static boolean externalToolsUserSettingsFileReadOnly = false; private static String specifiedContikiPath = null; /** * Logger settings filename. */ public static final String LOG_CONFIG_FILE = "log4j_config.xml"; /** * Default project configuration filename. */ public static final String PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_default.config"; /** * User project configuration filename. */ public static final String PROJECT_CONFIG_FILENAME = "cooja.config"; /** * File filter only showing saved simulations files (*.csc). */ public static final FileFilter SAVED_SIMULATIONS_FILES = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".csc")) { return true; } return false; } public String getDescription() { return "COOJA Configuration files"; } public String toString() { return ".csc"; } }; /** * Main frame for current GUI. Null when COOJA is run without visualizer! */ public static JFrame frame; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(GUI.class); // External tools setting names private static Properties defaultExternalToolsSettings; private static Properties currentExternalToolsSettings; private static final String externalToolsSettingNames[] = new String[] { "PATH_CONTIKI", "PATH_COOJA_CORE_RELATIVE", "PATH_MAKE", "PATH_SHELL", "PATH_C_COMPILER", "COMPILER_ARGS", "PATH_LINKER", "LINK_COMMAND_1", "LINK_COMMAND_2", "PATH_AR", "AR_COMMAND_1", "AR_COMMAND_2", "PATH_OBJDUMP", "OBJDUMP_ARGS", "PATH_JAVAC", "CONTIKI_STANDARD_PROCESSES", "CONTIKI_MAIN_TEMPLATE_FILENAME", "CMD_GREP_PROCESSES", "REGEXP_PARSE_PROCESSES", "CMD_GREP_INTERFACES", "REGEXP_PARSE_INTERFACES", "CMD_GREP_SENSORS", "REGEXP_PARSE_SENSORS", "DEFAULT_PROJECTDIRS", "CORECOMM_TEMPLATE_FILENAME", "MAPFILE_DATA_START", "MAPFILE_DATA_SIZE", "MAPFILE_BSS_START", "MAPFILE_BSS_SIZE", "MAPFILE_VAR_NAME", "MAPFILE_VAR_ADDRESS_1", "MAPFILE_VAR_ADDRESS_2", "MAPFILE_VAR_SIZE_1", "MAPFILE_VAR_SIZE_2", "PARSE_WITH_COMMAND", "PARSE_COMMAND", "COMMAND_VAR_NAME_ADDRESS", "COMMAND_DATA_START", "COMMAND_DATA_END", "COMMAND_BSS_START", "COMMAND_BSS_END", }; private static final int FRAME_NEW_OFFSET = 30; private static final int FRAME_STANDARD_WIDTH = 150; private static final int FRAME_STANDARD_HEIGHT = 300; private GUI myGUI; private Simulation mySimulation; protected GUIEventHandler guiEventHandler = new GUIEventHandler(); private JMenu menuPlugins, menuMoteTypeClasses, menuMoteTypes; private JMenu menuOpenSimulation, menuConfOpenSimulation; private Vector<Class<? extends Plugin>> menuMotePluginClasses; private JDesktopPane myDesktopPane; private Vector<Plugin> startedPlugins = new Vector<Plugin>(); // Platform configuration variables // Maintained via method reparseProjectConfig() private ProjectConfig projectConfig; private Vector<File> currentProjectDirs = new Vector<File>(); private ClassLoader projectDirClassLoader; private Vector<Class<? extends MoteType>> moteTypeClasses = new Vector<Class<? extends MoteType>>(); private Vector<Class<? extends Plugin>> pluginClasses = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends Plugin>> pluginClassesTemporary = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends RadioMedium>> radioMediumClasses = new Vector<Class<? extends RadioMedium>>(); private Vector<Class<? extends IPDistributor>> ipDistributorClasses = new Vector<Class<? extends IPDistributor>>(); private Vector<Class<? extends Positioner>> positionerClasses = new Vector<Class<? extends Positioner>>(); // Mote highlight observable private class HighlightObservable extends Observable { private void highlightMote(Mote mote) { setChanged(); notifyObservers(mote); } } private HighlightObservable moteHighlightObservable = new HighlightObservable(); /** * Creates a new COOJA Simulator GUI. * * @param desktop Desktop pane */ public GUI(JDesktopPane desktop) { myGUI = this; mySimulation = null; myDesktopPane = desktop; if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); } if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); if (specifiedContikiPath != null) { setExternalToolsSetting("PATH_CONTIKI", specifiedContikiPath); } // Register default project directories String defaultProjectDirs = getExternalToolsSetting( "DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null) { String[] defaultProjectDirsArr = defaultProjectDirs.split(";"); if (defaultProjectDirsArr.length > 0) { for (String defaultProjectDir : defaultProjectDirsArr) { File projectDir = new File(defaultProjectDir); if (projectDir.exists() && projectDir.isDirectory()) { currentProjectDirs.add(projectDir); } } } } // Load extendable parts (using current project config) try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading project directories: " + e.getMessage()); e.printStackTrace(); if (myDesktopPane != null) { JOptionPane.showMessageDialog(frame, "Loading project directories failed.\nStack trace printed to console.", "Error", JOptionPane.ERROR_MESSAGE); } } // Start all standard GUI plugins for (Class<? extends Plugin> visPluginClass : pluginClasses) { int pluginType = visPluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { startPlugin(visPluginClass, this, null, null); } } } /** * Add mote highlight observer. * * @see #deleteTickObserver(Observer) * @param newObserver * New observer */ public void addMoteHighligtObserver(Observer newObserver) { moteHighlightObservable.addObserver(newObserver); } /** * Delete an mote highlight observer. * * @see #addTickObserver(Observer) * @param observer * Observer to delete */ public void deleteMoteHighligtObserver(Observer observer) { moteHighlightObservable.deleteObserver(observer); } /** * @return True if simulator is visualized */ public boolean isVisualized() { return frame != null; } /** * EXPERIMENTAL! * Tries to create/remove simulator visualizer. * * @param visualized Visualized */ public void setVisualized(boolean visualized) { if (!isVisualized() && visualized) { configureFrame(myGUI, false); } else { frame.setVisible(false); frame.dispose(); frame = null; } } private Vector<File> getFileHistory() { Vector<File> history = new Vector<File>(); // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); for (String file: historyArray) { history.add(new File(file)); } return history; } private void addToFileHistory(File file) { // Fetch current history String[] history = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); // Create new history String[] newHistory = null; if (history == null || history.length <= 1 && history[0].equals("")) { newHistory = new String[1]; } else { newHistory = new String[Math.min(5, history.length+1)]; System.arraycopy(history, 0, newHistory, 1, newHistory.length-1); } newHistory[0] = file.getAbsolutePath(); // Abort if file added is equal to last file if (history.length >= 1 && file.getAbsolutePath().equals(new File(history[0]).getAbsolutePath())) { return; } String newHistoryConfig = null; for (String path: newHistory) { if (newHistoryConfig == null) { newHistoryConfig = path; } else { newHistoryConfig += ";" + path; } } setExternalToolsSetting("SIMCFG_HISTORY", newHistoryConfig); saveExternalToolsUserSettings(); } private void updateOpenHistoryMenuItems() { menuConfOpenSimulation.removeAll(); JMenuItem browseItem = new JMenuItem("Browse..."); browseItem.setActionCommand("confopen sim"); browseItem.addActionListener(guiEventHandler); menuConfOpenSimulation.add(browseItem); menuConfOpenSimulation.add(new JSeparator()); Vector<File> openFilesHistory = getFileHistory(); for (File file: openFilesHistory) { JMenuItem lastItem = new JMenuItem(file.getName()); lastItem.setActionCommand("confopen last sim"); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); lastItem.addActionListener(guiEventHandler); menuConfOpenSimulation.add(lastItem); } menuOpenSimulation.removeAll(); browseItem = new JMenuItem("Browse..."); browseItem.setActionCommand("open sim"); browseItem.addActionListener(guiEventHandler); menuOpenSimulation.add(browseItem); menuOpenSimulation.add(new JSeparator()); for (File file: openFilesHistory) { JMenuItem lastItem = new JMenuItem(file.getName()); lastItem.setActionCommand("open last sim"); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); lastItem.addActionListener(guiEventHandler); menuOpenSimulation.add(lastItem); } } private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu; JMenuItem menuItem; // File menu menu = new JMenu("File"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateOpenHistoryMenuItems(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); menuItem = new JMenuItem("New simulation"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("new sim"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuItem = new JMenuItem("Reload simulation"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reloadCurrentSimulation(); } }); menu.add(menuItem); menuItem = new JMenuItem("Close simulation"); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.setActionCommand("close sim"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuOpenSimulation = new JMenu("Open simulation"); menuOpenSimulation.setMnemonic(KeyEvent.VK_O); menu.add(menuOpenSimulation); menuConfOpenSimulation = new JMenu("Open & Reconfigure simulation"); menuConfOpenSimulation.setMnemonic(KeyEvent.VK_R); menu.add(menuConfOpenSimulation); menuItem = new JMenuItem("Save simulation"); menuItem.setMnemonic(KeyEvent.VK_S); menuItem.setActionCommand("save sim"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Close all plugins"); menuItem.setActionCommand("close plugins"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Exit"); menuItem.setMnemonic(KeyEvent.VK_X); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("quit"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Simulation menu menu = new JMenu("Simulation"); menu.setMnemonic(KeyEvent.VK_S); menuBar.add(menu); menuItem = new JMenuItem("Open Control"); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", SimControl.class); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuItem = new JMenuItem("Information"); menuItem.setMnemonic(KeyEvent.VK_I); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", SimInformation.class); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Mote type menu menu = new JMenu("Mote Types"); menu.setMnemonic(KeyEvent.VK_T); menuBar.add(menu); // Mote type classes sub menu menuMoteTypeClasses = new JMenu("Create mote type"); menuMoteTypeClasses.setMnemonic(KeyEvent.VK_C); menuMoteTypeClasses.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypeClasses.removeAll(); // Recreate menu items JMenuItem menuItem; for (Class<? extends MoteType> moteTypeClass : moteTypeClasses) { /* Sort mote types according to abstraction level */ String abstractionLevelDescription = GUI.getAbstractionLevelDescriptionOf(moteTypeClass); if(abstractionLevelDescription == null) { abstractionLevelDescription = "[unknown cross-level]"; } /* Check if abstraction description already exists */ JSeparator abstractionLevelSeparator = null; for (Component component: menuMoteTypeClasses.getMenuComponents()) { if (component == null || !(component instanceof JSeparator)) { continue; } JSeparator existing = (JSeparator) component; if (abstractionLevelDescription.equals(existing.getToolTipText())) { abstractionLevelSeparator = existing; break; } } if (abstractionLevelSeparator == null) { abstractionLevelSeparator = new JSeparator(); abstractionLevelSeparator.setToolTipText(abstractionLevelDescription); menuMoteTypeClasses.add(abstractionLevelSeparator); } String description = GUI.getDescriptionOf(moteTypeClass); menuItem = new JMenuItem(description); menuItem.setActionCommand("create mote type"); menuItem.putClientProperty("class", moteTypeClass); menuItem.setToolTipText(abstractionLevelDescription); menuItem.addActionListener(guiEventHandler); /* Add new item directly after cross level separator */ for (int i=0; i < menuMoteTypeClasses.getMenuComponentCount(); i++) { if (menuMoteTypeClasses.getMenuComponent(i) == abstractionLevelSeparator) { menuMoteTypeClasses.add(menuItem, i+1); break; } } } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypeClasses); menuItem = new JMenuItem("Information"); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", MoteTypeInformation.class); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Mote menu menu = new JMenu("Motes"); menu.setMnemonic(KeyEvent.VK_M); menuBar.add(menu); // Mote types sub menu menuMoteTypes = new JMenu("Add motes of type"); menuMoteTypes.setMnemonic(KeyEvent.VK_A); menuMoteTypes.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypes.removeAll(); if (mySimulation == null) { return; } // Recreate menu items JMenuItem menuItem; for (MoteType moteType : mySimulation.getMoteTypes()) { menuItem = new JMenuItem(moteType.getDescription()); menuItem.setActionCommand("add motes"); menuItem.setToolTipText(getDescriptionOf(moteType.getClass())); menuItem.putClientProperty("motetype", moteType); menuItem.addActionListener(guiEventHandler); menuMoteTypes.add(menuItem); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypes); menuItem = new JMenuItem("Remove all motes"); menuItem.setActionCommand("remove all motes"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Plugins menu if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); } else { menuPlugins.setText("Plugins"); } menuPlugins.setMnemonic(KeyEvent.VK_P); menuBar.add(menuPlugins); // Settings menu menu = new JMenu("Settings"); menuBar.add(menu); menuItem = new JMenuItem("External tools paths"); menuItem.setActionCommand("edit paths"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuItem = new JMenuItem("Manage project directories"); menuItem.setActionCommand("manage projects"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Java version: " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); menuItem.setEnabled(false); menu.add(menuItem); // Mote plugins popup menu (not available via menu bar) if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } return menuBar; } private static void configureFrame(final GUI gui, boolean createSimDialog) { // Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); // Create and set up the window. frame = new JFrame("COOJA Simulator"); if (maxSize != null) { frame.setMaximizedBounds(maxSize); } frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Add menu bar frame.setJMenuBar(gui.createMenuBar()); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.setSize(700, 700); frame.setLocationRelativeTo(null); frame.addWindowListener(gui.guiEventHandler); // Restore last frame size and position if (frame != null) { int framePosX = Integer.parseInt(getExternalToolsSetting("FRAME_POS_X", "-1")); int framePosY = Integer.parseInt(getExternalToolsSetting("FRAME_POS_Y", "-1")); int frameWidth = Integer.parseInt(getExternalToolsSetting("FRAME_WIDTH", "-1")); int frameHeight = Integer.parseInt(getExternalToolsSetting("FRAME_HEIGHT", "-1")); if (framePosX >= 0 && framePosY >= 0 && frameWidth > 0 && frameHeight > 0) { frame.setLocation(framePosX, framePosY); frame.setSize(frameWidth, frameHeight); // Assume window was maximized if loaded size matches maximum bounds if (maxSize != null && framePosX == 0 && framePosY == 0 && frameWidth == maxSize.width && frameHeight == maxSize.height) { frame.setExtendedState(JFrame.MAXIMIZED_BOTH); } } } // Display the window. frame.setVisible(true); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } /** * @return Current desktop pane (simulator visualizer) */ public JDesktopPane getDesktopPane() { return myDesktopPane; } /** * Quick-starts a simulation using given parameters. TODO Experimental code * * @param moteTypeID * Mote type ID (if null "mtype1" will be used) * @param projectDirs * GUI project directories * @param sensors * Contiki sensors (if null sensors will be scanned for) * @param coreInterfaces * COOJA core interfaces (if null interfaces will be scanned for) * @param userProcesses * Contiki user processes (if null processes all in given main file * will be added) * @param addAutostartProcesses * Should autostart processes automatically be added? * @param numberOfNodes * Number of nodes to add * @param areaSideLength * Side of node positioning square * @param delayTime * Initial delay time * @param simulationStartinge * Simulation automatically started? * @param filename * Main Contiki process file * @param contikiPath * Contiki path * @return True if simulation was quickstarted correctly */ private static boolean quickStartSimulation(String moteTypeID, Vector<String> projectDirs, Vector<String> sensors, Vector<String> coreInterfaces, Vector<String> userProcesses, boolean addAutostartProcesses, int numberOfNodes, double areaSideLength, int delayTime, boolean simulationStarting, String filename, String contikiPath) { // Create GUI and GUI frame (not visible yet) JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); logger.info("> Creating GUI and main frame (invisible)"); frame = new JFrame("COOJA Simulator"); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Create and set up the content pane. JDesktopPane desktop = new JDesktopPane(); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); GUI gui = new GUI(desktop); // loads external settings and creates initial project config // Add menu bar frame.setSize(700, 700); frame.addWindowListener(gui.guiEventHandler); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.setLocationRelativeTo(null); // Set manual Contiki path if specified if (contikiPath != null) { setExternalToolsSetting("PATH_CONTIKI", contikiPath); } // Parse project directories and create config if (projectDirs == null) { projectDirs = new Vector<String>(); projectDirs.add("."); } // TODO Should add user prop projects as well here... logger.info("> Reparsing project directories and creating config"); for (String projectDir : projectDirs) { logger.info(">> Adding: " + projectDir); // Check if config file exists File configFile = new File(projectDir + File.separatorChar + PROJECT_CONFIG_FILENAME); if (!configFile.exists()) { logger.debug(">>> Creating empty cooja.config file"); try { configFile.createNewFile(); } catch (IOException e) { logger.fatal(">> Error when creating cooja.config file, aborting"); return false; } } gui.currentProjectDirs.add(new File(projectDir)); } try { gui.reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal(">> Error when parsing project directories: " + e.getMessage()); return false; } // Check file permissions and paths logger.info("> Checking paths and file permissions"); if (moteTypeID == null) { moteTypeID = "mtype1"; } File contikiBaseDir = new File(getExternalToolsSetting("PATH_CONTIKI")); File contikiCoreDir = new File(contikiBaseDir, getExternalToolsSetting("PATH_COOJA_CORE_RELATIVE")); File libFile = new File(ContikiMoteType.tempOutputDirectory, moteTypeID + ContikiMoteType.librarySuffix); File mapFile = new File(ContikiMoteType.tempOutputDirectory, moteTypeID + ContikiMoteType.mapSuffix); File depFile = new File(ContikiMoteType.tempOutputDirectory, moteTypeID + ContikiMoteType.dependSuffix); if (libFile.exists()) { libFile.delete(); } if (depFile.exists()) { depFile.delete(); } if (mapFile.exists()) { mapFile.delete(); } if (libFile.exists()) { logger.fatal(">> Can't delete output file, aborting: " + libFile); return false; } if (depFile.exists()) { logger.fatal(">> Can't delete output file, aborting: " + depFile); return false; } if (mapFile.exists()) { logger.fatal(">> Can't delete output file, aborting: " + mapFile); return false; } // Search for main file in current directory (or arg) File mainProcessFile = new File(filename); logger.info(">> Searching main process file: " + mainProcessFile.getAbsolutePath()); if (!mainProcessFile.exists()) { logger.info(">> Searching main process file: " + mainProcessFile.getAbsolutePath()); boolean foundFile = false; for (String projectDir : projectDirs) { mainProcessFile = new File(projectDir, filename); logger.info(">> Searching main process file: " + mainProcessFile.getAbsolutePath()); if (mainProcessFile.exists()) { foundFile = true; break; } } if (!foundFile) { logger.fatal(">> Could not locate main process file, aborting"); return false; } } // Setup compilation arguments logger.info("> Setting up compilation arguments"); Vector<File> filesToCompile = new Vector<File>(); filesToCompile.add(mainProcessFile); // main process file for (String projectDir : projectDirs) { // project directories filesToCompile.add(new File(projectDir)); } String[] projectSources = // project config sources gui.getProjectConfig().getStringArrayValue(ContikiMoteType.class, "C_SOURCES"); for (String projectSource : projectSources) { if (!projectSource.equals("")) { File file = new File(projectSource); if (file.getParent() != null) { // Find which project directory added this file File projectDir = gui.getProjectConfig().getUserProjectDefining( ContikiMoteType.class, "C_SOURCES", projectSource); if (projectDir != null) { // We found a project directory - Add it filesToCompile.add(new File(projectDir.getPath(), file .getParent())); } } filesToCompile.add(new File(file.getName())); } } // Scan for sensors if (sensors == null) { logger.info("> Scanning for sensors"); sensors = new Vector<String>(); Vector<String[]> scannedSensorInfo = ContikiMoteTypeDialog .scanForSensors(contikiCoreDir); for (String projectDir : projectDirs) { // project directories scannedSensorInfo.addAll(ContikiMoteTypeDialog.scanForSensors(new File( projectDir))); } for (String[] sensorInfo : scannedSensorInfo) { // logger.info(">> Found and added: " + sensorInfo[1] + " (" + // sensorInfo[0] + ")"); sensors.add(sensorInfo[1]); } } // Scan for core interfaces if (coreInterfaces == null) { logger.info("> Scanning for core interfaces"); coreInterfaces = new Vector<String>(); Vector<String[]> scannedCoreInterfaceInfo = ContikiMoteTypeDialog .scanForInterfaces(contikiCoreDir); for (String projectDir : projectDirs) { // project directories scannedCoreInterfaceInfo.addAll(ContikiMoteTypeDialog .scanForInterfaces(new File(projectDir))); } for (String[] coreInterfaceInfo : scannedCoreInterfaceInfo) { // logger.info(">> Found and added: " + coreInterfaceInfo[1] + " (" + // coreInterfaceInfo[0] + ")"); coreInterfaces.add(coreInterfaceInfo[1]); } } // Scan for mote interfaces logger.info("> Loading mote interfaces"); String[] moteInterfaces = gui.getProjectConfig().getStringArrayValue( ContikiMoteType.class, "MOTE_INTERFACES"); Vector<Class<? extends MoteInterface>> moteIntfClasses = new Vector<Class<? extends MoteInterface>>(); for (String moteInterface : moteInterfaces) { try { Class<? extends MoteInterface> newMoteInterfaceClass = gui .tryLoadClass(gui, MoteInterface.class, moteInterface); moteIntfClasses.add(newMoteInterfaceClass); // logger.info(">> Loaded mote interface: " + newMoteInterfaceClass); } catch (Exception e) { logger.fatal(">> Failed to load mote interface, aborting: " + moteInterface + ", " + e.getMessage()); return false; } } // Scan for processes if (userProcesses == null) { logger.info("> Scanning for user processes"); userProcesses = new Vector<String>(); Vector<String> autostartProcesses = new Vector<String>(); Vector<String[]> scannedProcessInfo = ContikiMoteTypeDialog .scanForProcesses(contikiCoreDir); for (String projectDir : projectDirs) { // project directories scannedProcessInfo.addAll(ContikiMoteTypeDialog .scanForProcesses(new File(projectDir))); } for (String[] processInfo : scannedProcessInfo) { if (processInfo[0].equals(mainProcessFile.getName())) { logger.info(">> Found and added: " + processInfo[1] + " (" + processInfo[0] + ")"); userProcesses.add(processInfo[1]); if (addAutostartProcesses) { // Parse any autostart processes try { // logger.info(">>> Parsing " + processInfo[0] + " for autostart // processes"); Vector<String> autostarters = ContikiMoteTypeDialog .parseAutostartProcesses(mainProcessFile); if (autostarters != null) { autostartProcesses.addAll(autostarters); } } catch (Exception e) { logger .fatal(">>> Error when parsing autostart processes, aborting: " + e); return false; } } } else { // logger.info(">> Found and ignored: " + processInfo[1] + " (" + // processInfo[0] + ")"); } } if (addAutostartProcesses) { // Add autostart process sources if found logger.info("> Adding autostart processes"); for (String autostartProcess : autostartProcesses) { boolean alreadyExists = false; for (String existingProcess : userProcesses) { if (existingProcess.equals(autostartProcess)) { alreadyExists = true; break; } } if (!alreadyExists) { userProcesses.add(autostartProcess); logger.info(">> Added autostart process: " + autostartProcess); } } } } // Generate Contiki main source file logger.info("> Generating Contiki main source file"); if (!ContikiMoteType.tempOutputDirectory.exists()) { ContikiMoteType.tempOutputDirectory.mkdir(); } if (!ContikiMoteType.tempOutputDirectory.exists()) { logger.fatal(">> Could not create output directory: " + ContikiMoteType.tempOutputDirectory); return false; } try { String generatedFilename = ContikiMoteTypeDialog.generateSourceFile( moteTypeID, sensors, coreInterfaces, userProcesses); // logger.info(">> Generated source file: " + generatedFilename); } catch (Exception e) { logger.fatal(">> Error during file generation, aborting: " + e.getMessage()); return false; } // Compile library logger.info("> Compiling library (Rime comm stack)"); // TODO Warning, assuming Rime communication stack boolean compilationSucceded = ContikiMoteTypeDialog.compileLibrary( moteTypeID, contikiBaseDir, filesToCompile, false, ContikiMoteType.CommunicationStack.RIME, null, System.err); if (!libFile.exists() || !depFile.exists() || !mapFile.exists()) { compilationSucceded = false; } if (compilationSucceded) { // logger.info(">> Compilation complete"); } else { logger.fatal(">> Error during compilation, aborting"); return false; } // Create mote type logger.info("> Creating mote type"); ContikiMoteType moteType; try { moteType = new ContikiMoteType(moteTypeID); } catch (MoteTypeCreationException e) { logger.fatal("Exception when creating mote type: " + e); return false; } moteType.setDescription("Mote type: " + filename); moteType.setContikiBaseDir(contikiBaseDir.getPath()); moteType.setContikiCoreDir(contikiCoreDir.getPath()); moteType.setProjectDirs(new Vector<File>()); moteType.setCompilationFiles(filesToCompile); moteType.setConfig(gui.getProjectConfig()); moteType.setProcesses(userProcesses); moteType.setSensors(sensors); moteType.setCoreInterfaces(coreInterfaces); moteType.setMoteInterfaces(moteIntfClasses); // Create simulation logger.info("> Creating simulation"); Simulation simulation = new Simulation(gui); simulation.setTitle("Quickstarted: " + filename); simulation.setDelayTime(delayTime); simulation.setSimulationTime(0); simulation.setTickTime(1); String radioMediumClassName = null; try { radioMediumClassName = gui.getProjectConfig().getStringArrayValue( GUI.class, "RADIOMEDIUMS")[0]; Class<? extends RadioMedium> radioMediumClass = gui.tryLoadClass(gui, RadioMedium.class, radioMediumClassName); RadioMedium radioMedium = RadioMedium.generateRadioMedium( radioMediumClass, simulation); simulation.setRadioMedium(radioMedium); } catch (Exception e) { logger.fatal(">> Failed to load radio medium, aborting: " + radioMediumClassName + ", " + e); return false; } // Create nodes logger.info("> Creating motes"); Vector<ContikiMote> motes = new Vector<ContikiMote>(); Random random = new Random(); int nextMoteID = 1; int nextIP = 0; for (int i = 0; i < numberOfNodes; i++) { ContikiMote mote = (ContikiMote) moteType.generateMote(simulation); // Set random position if (mote.getInterfaces().getPosition() != null) { mote.getInterfaces().getPosition().setCoordinates( random.nextDouble() * areaSideLength, random.nextDouble() * areaSideLength, 0); } // Set unique mote ID's if (mote.getInterfaces().getMoteID() != null) { mote.getInterfaces().getMoteID().setMoteID(nextMoteID++); } // Set unique IP address if (mote.getInterfaces().getIPAddress() != null) { mote.getInterfaces().getIPAddress().setIPNumber((char) 10, (char) ((nextIP / (254 * 255)) % 255), (char) ((nextIP / 254) % 255), (char) (nextIP % 254 + 1)); nextIP++; } motes.add(mote); } // Add mote type and motes to simulation logger.info("> Adding motes and mote type to simulation"); simulation.addMoteType(moteType); for (Mote mote : motes) { simulation.addMote(mote); } // Add simulation to GUI logger.info("> Adding simulation to GUI"); gui.setSimulation(simulation); // Start plugins and try to place them wisely logger.info("> Starting plugin and showing GUI"); VisPlugin plugin = (VisPlugin) gui.startPlugin(VisState.class, gui, simulation, null); plugin.setLocation(350, 20); plugin = (VisPlugin) gui.startPlugin(VisTraffic.class, gui, simulation, null); plugin.setLocation(350, 340); plugin = (VisPlugin) gui.startPlugin(LogListener.class, gui, simulation, null); plugin.setLocation(20, 420); frame.setJMenuBar(gui.createMenuBar()); // Finally show GUI frame.setVisible(true); if (simulationStarting) { simulation.startSimulation(); } return true; } //// PROJECT CONFIG AND EXTENDABLE PARTS METHODS //// /** * Register new mote type class. * * @param moteTypeClass * Class to register */ public void registerMoteType(Class<? extends MoteType> moteTypeClass) { moteTypeClasses.add(moteTypeClass); } /** * Unregister all mote type classes. */ public void unregisterMoteTypes() { moteTypeClasses.clear(); } /** * @return All registered mote type classes */ public Vector<Class<? extends MoteType>> getRegisteredMoteTypes() { return moteTypeClasses; } /** * Register new IP distributor class * * @param ipDistributorClass * Class to register * @return True if class was registered */ public boolean registerIPDistributor( Class<? extends IPDistributor> ipDistributorClass) { // Check that vector constructor exists try { ipDistributorClass.getConstructor(new Class[] { Vector.class }); } catch (Exception e) { logger.fatal("No vector constructor found of IP distributor: " + ipDistributorClass); return false; } ipDistributorClasses.add(ipDistributorClass); return true; } /** * Unregister all IP distributors. */ public void unregisterIPDistributors() { ipDistributorClasses.clear(); } /** * @return All registered IP distributors */ public Vector<Class<? extends IPDistributor>> getRegisteredIPDistributors() { return ipDistributorClasses; } /** * Register new positioner class. * * @param positionerClass * Class to register * @return True if class was registered */ public boolean registerPositioner(Class<? extends Positioner> positionerClass) { // Check that interval constructor exists try { positionerClass .getConstructor(new Class[] { int.class, double.class, double.class, double.class, double.class, double.class, double.class }); } catch (Exception e) { logger.fatal("No interval constructor found of positioner: " + positionerClass); return false; } positionerClasses.add(positionerClass); return true; } /** * Unregister all positioner classes. */ public void unregisterPositioners() { positionerClasses.clear(); } /** * @return All registered positioner classes */ public Vector<Class<? extends Positioner>> getRegisteredPositioners() { return positionerClasses; } /** * Register new radio medium class. * * @param radioMediumClass * Class to register * @return True if class was registered */ public boolean registerRadioMedium( Class<? extends RadioMedium> radioMediumClass) { // Check that simulation constructor exists try { radioMediumClass.getConstructor(new Class[] { Simulation.class }); } catch (Exception e) { logger.fatal("No simulation constructor found of radio medium: " + radioMediumClass); return false; } radioMediumClasses.add(radioMediumClass); return true; } /** * Unregister all radio medium classes. */ public void unregisterRadioMediums() { radioMediumClasses.clear(); } /** * @return All registered radio medium classes */ public Vector<Class<? extends RadioMedium>> getRegisteredRadioMediums() { return radioMediumClasses; } /** * Builds new project configuration using current project directories settings. * Reregisters mote types, plugins, IP distributors, positioners and radio * mediums. This method may still return true even if all classes could not be * registered, but always returns false if all project directory configuration * files were not parsed correctly. * * Any registered temporary plugins will be saved and reregistered. * * @return True if external configuration files were found and parsed OK */ public void reparseProjectConfig() throws ParseProjectsException { // Backup temporary plugins Vector<Class<? extends Plugin>> oldTempPlugins = (Vector<Class<? extends Plugin>>) pluginClassesTemporary .clone(); // Reset current configuration unregisterMoteTypes(); unregisterPlugins(); unregisterIPDistributors(); unregisterPositioners(); unregisterRadioMediums(); try { // Read default configuration projectConfig = new ProjectConfig(true); } catch (FileNotFoundException e) { logger.fatal("Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } catch (IOException e) { logger.fatal("Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } // Append project directory configurations for (File projectDir : currentProjectDirs) { try { // Append config to general config projectConfig.appendProjectDir(projectDir); } catch (FileNotFoundException e) { logger.fatal("Could not find project config file: " + projectDir); throw (ParseProjectsException) new ParseProjectsException( "Could not find project config file: " + projectDir).initCause(e); } catch (IOException e) { logger.fatal("Error when reading project config file: " + projectDir); throw (ParseProjectsException) new ParseProjectsException( "Error when reading project config file: " + projectDir).initCause(e); } } // Create class loader try { projectDirClassLoader = createClassLoader(currentProjectDirs); } catch (ClassLoaderCreationException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when creating class loader").initCause(e); } // Register mote types String[] moteTypeClassNames = projectConfig.getStringArrayValue(GUI.class, "MOTETYPES"); if (moteTypeClassNames != null) { for (String moteTypeClassName : moteTypeClassNames) { Class<? extends MoteType> moteTypeClass = tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass != null) { registerMoteType(moteTypeClass); // logger.info("Loaded mote type class: " + moteTypeClassName); } else { logger.warn("Could not load mote type class: " + moteTypeClassName); } } } // Register plugins registerPlugin(SimControl.class, false); // Not in menu registerPlugin(SimInformation.class, false); // Not in menu registerPlugin(MoteTypeInformation.class, false); // Not in menu String[] pluginClassNames = projectConfig.getStringArrayValue(GUI.class, "PLUGINS"); if (pluginClassNames != null) { for (String pluginClassName : pluginClassNames) { Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass != null) { registerPlugin(pluginClass); // logger.info("Loaded plugin class: " + pluginClassName); } else { logger.warn("Could not load plugin class: " + pluginClassName); } } } // Reregister temporary plugins again if (oldTempPlugins != null) { for (Class<? extends Plugin> pluginClass : oldTempPlugins) { if (registerTemporaryPlugin(pluginClass)) { // logger.info("Reregistered temporary plugin class: " + // getDescriptionOf(pluginClass)); } else { logger.warn("Could not reregister temporary plugin class: " + getDescriptionOf(pluginClass)); } } } // Register IP distributors String[] ipDistClassNames = projectConfig.getStringArrayValue(GUI.class, "IP_DISTRIBUTORS"); if (ipDistClassNames != null) { for (String ipDistClassName : ipDistClassNames) { Class<? extends IPDistributor> ipDistClass = tryLoadClass(this, IPDistributor.class, ipDistClassName); if (ipDistClass != null) { registerIPDistributor(ipDistClass); // logger.info("Loaded IP distributor class: " + ipDistClassName); } else { logger .warn("Could not load IP distributor class: " + ipDistClassName); } } } // Register positioners String[] positionerClassNames = projectConfig.getStringArrayValue( GUI.class, "POSITIONERS"); if (positionerClassNames != null) { for (String positionerClassName : positionerClassNames) { Class<? extends Positioner> positionerClass = tryLoadClass(this, Positioner.class, positionerClassName); if (positionerClass != null) { registerPositioner(positionerClass); // logger.info("Loaded positioner class: " + positionerClassName); } else { logger .warn("Could not load positioner class: " + positionerClassName); } } } // Register radio mediums String[] radioMediumsClassNames = projectConfig.getStringArrayValue( GUI.class, "RADIOMEDIUMS"); if (radioMediumsClassNames != null) { for (String radioMediumClassName : radioMediumsClassNames) { Class<? extends RadioMedium> radioMediumClass = tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { registerRadioMedium(radioMediumClass); // logger.info("Loaded radio medium class: " + radioMediumClassName); } else { logger.warn("Could not load radio medium class: " + radioMediumClassName); } } } } /** * Returns the current project configuration common to the entire simulator. * * @return Current project configuration */ public ProjectConfig getProjectConfig() { return projectConfig; } /** * Returns the current project directories common to the entire simulator. * * @return Current project directories. */ public Vector<File> getProjectDirs() { return currentProjectDirs; } // // PLUGIN METHODS //// /** * Show a started plugin in working area. * * @param plugin * Internal frame to add */ public void showPlugin(VisPlugin plugin) { int nrFrames = myDesktopPane.getAllFrames().length; myDesktopPane.add(plugin); // Set standard size if not specified by plugin itself if (plugin.getWidth() <= 0 || plugin.getHeight() <= 0) { plugin.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); } // Set location if not already visible if (!plugin.isVisible()) { plugin.setLocation((nrFrames + 1) * FRAME_NEW_OFFSET, (nrFrames + 1) * FRAME_NEW_OFFSET); plugin.setVisible(true); } // Deselect all other plugins before selecting the new one try { for (JInternalFrame existingPlugin : myDesktopPane.getAllFrames()) { existingPlugin.setSelected(false); } plugin.setSelected(true); } catch (Exception e) { // Ignore } // Mote plugin to front myDesktopPane.moveToFront(plugin); } /** * Remove a plugin from working area. * * @param plugin * Plugin to remove * @param askUser * If plugin is the last one, ask user if we should remove current * simulation also? */ public void removePlugin(Plugin plugin, boolean askUser) { // Clear any allocated resources and remove plugin plugin.closePlugin(); startedPlugins.remove(plugin); // Dispose plugin if it has visualizer if (plugin instanceof VisPlugin) { ((VisPlugin) plugin).dispose(); } if (getSimulation() != null && askUser && startedPlugins.isEmpty()) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } doRemoveSimulation(false); } } /** * Starts a plugin of given plugin class with given arguments. * * @param pluginClass * Plugin class * @param gui * GUI passed as argument to all plugins * @param simulation * Simulation passed as argument to mote and simulation plugins * @param mote * Mote passed as argument to mote plugins * @return Start plugin if any */ public Plugin startPlugin(Class<? extends Plugin> pluginClass, GUI gui, Simulation simulation, Mote mote) { // Check that plugin class is registered if (!pluginClasses.contains(pluginClass)) { logger.fatal("Plugin class not registered: " + pluginClass); return null; } // Check that visualizer plugin is not started without GUI if (!isVisualized()) { try { pluginClass.asSubclass(VisPlugin.class); // Cast succeded, plugin is visualizer plugin! logger.fatal("Can't start visualizer plugin (no GUI): " + pluginClass); return null; } catch (ClassCastException e) { } } // Construct plugin depending on plugin type Plugin newPlugin = null; int pluginType = pluginClass.getAnnotation(PluginType.class).value(); try { if (pluginType == PluginType.MOTE_PLUGIN) { if (mote == null) { logger.fatal("Can't start mote plugin (no mote selected)"); return null; } newPlugin = pluginClass.getConstructor( new Class[] { Mote.class, Simulation.class, GUI.class }) .newInstance(mote, simulation, gui); // Tag plugin with mote newPlugin.tagWithObject(mote); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { if (simulation == null) { logger.fatal("Can't start simulation plugin (no simulation)"); return null; } newPlugin = pluginClass.getConstructor( new Class[] { Simulation.class, GUI.class }).newInstance( simulation, gui); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { if (gui == null) { logger.fatal("Can't start COOJA plugin (no GUI)"); return null; } newPlugin = pluginClass.getConstructor(new Class[] { GUI.class }) .newInstance(gui); } } catch (Exception e) { logger.fatal("Exception thrown when starting plugin: " + e); e.printStackTrace(); return null; } if (newPlugin == null) { return null; } // Add to active plugins list startedPlugins.add(newPlugin); // Show plugin if visualizer type if (newPlugin instanceof VisPlugin) { myGUI.showPlugin((VisPlugin) newPlugin); } return newPlugin; } /** * Register a plugin to be included in the GUI. The plugin will be visible in * the menubar. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerPlugin(Class<? extends Plugin> newPluginClass) { return registerPlugin(newPluginClass, true); } /** * Register a temporary plugin to be included in the GUI. The plugin will be * visible in the menubar. This plugin will automatically be unregistered if * the current simulation is removed. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerTemporaryPlugin(Class<? extends Plugin> newPluginClass) { if (pluginClasses.contains(newPluginClass)) { return false; } boolean returnVal = registerPlugin(newPluginClass, true); if (!returnVal) { return false; } pluginClassesTemporary.add(newPluginClass); return true; } /** * Unregister a plugin class. Removes any plugin menu items links as well. * * @param pluginClass * Plugin class to unregister */ public void unregisterPlugin(Class<? extends Plugin> pluginClass) { // Remove (if existing) plugin class menu items for (Component menuComponent : menuPlugins.getMenuComponents()) { if (menuComponent.getClass().isAssignableFrom(JMenuItem.class)) { JMenuItem menuItem = (JMenuItem) menuComponent; if (menuItem.getClientProperty("class").equals(pluginClass)) { menuPlugins.remove(menuItem); } } } if (menuMotePluginClasses.contains(pluginClass)) { menuMotePluginClasses.remove(pluginClass); } // Remove from plugin vectors (including temporary) if (pluginClasses.contains(pluginClass)) { pluginClasses.remove(pluginClass); } if (pluginClassesTemporary.contains(pluginClass)) { pluginClassesTemporary.remove(pluginClass); } } /** * Register a plugin to be included in the GUI. * * @param newPluginClass * New plugin to register * @param addToMenu * Should this plugin be added to the dedicated plugins menubar? * @return True if this plugin was registered ok, false otherwise */ private boolean registerPlugin(Class<? extends Plugin> newPluginClass, boolean addToMenu) { // Get description annotation (if any) String description = getDescriptionOf(newPluginClass); // Get plugin type annotation (required) int pluginType; if (newPluginClass.isAnnotationPresent(PluginType.class)) { pluginType = newPluginClass.getAnnotation(PluginType.class).value(); } else { pluginType = PluginType.UNDEFINED_PLUGIN; } // Check that plugin type is valid and constructor exists try { if (pluginType == PluginType.MOTE_PLUGIN) { newPluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, GUI.class }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { newPluginClass .getConstructor(new Class[] { Simulation.class, GUI.class }); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { newPluginClass.getConstructor(new Class[] { GUI.class }); } else { logger.fatal("Could not find valid plugin type annotation in class " + newPluginClass); return false; } } catch (NoSuchMethodException e) { logger.fatal("Could not find valid constructor in class " + newPluginClass + ": " + e); return false; } if (addToMenu && menuPlugins != null) { // Create 'start plugin'-menu item JMenuItem menuItem = new JMenuItem(description); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", newPluginClass); menuItem.addActionListener(guiEventHandler); menuPlugins.add(menuItem); if (pluginType == PluginType.MOTE_PLUGIN) { // Disable previous menu item and add new item to mote plugins menu menuItem.setEnabled(false); menuItem.setToolTipText("Mote plugin"); menuMotePluginClasses.add(newPluginClass); } } pluginClasses.add(newPluginClass); return true; } /** * Unregister all plugin classes, including temporary plugins. */ public void unregisterPlugins() { if (menuPlugins != null) { menuPlugins.removeAll(); } if (menuMotePluginClasses != null) { menuMotePluginClasses.clear(); } pluginClasses.clear(); pluginClassesTemporary.clear(); } /** * Return a mote plugins submenu for given mote. * * @param mote Mote * @return Mote plugins menu */ public JMenu createMotePluginsSubmenu(Mote mote) { JMenu menuMotePlugins = new JMenu("Open mote plugin for " + mote); for (Class<? extends Plugin> motePluginClass: menuMotePluginClasses) { JMenuItem menuItem = new JMenuItem(getDescriptionOf(motePluginClass)); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", motePluginClass); menuItem.putClientProperty("mote", mote); menuItem.addActionListener(guiEventHandler); menuMotePlugins.add(menuItem); } return menuMotePlugins; } // // GUI CONTROL METHODS //// /** * @return Current simulation */ public Simulation getSimulation() { return mySimulation; } public void setSimulation(Simulation sim) { if (sim != null) { doRemoveSimulation(false); } mySimulation = sim; // Set frame title if (frame != null) { frame.setTitle("COOJA Simulator" + " - " + sim.getTitle()); } // Open standard plugins (if none opened already) if (startedPlugins.size() == 0) { for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.SIM_STANDARD_PLUGIN) { startPlugin(pluginClass, this, sim, null); } } } } /** * Creates a new mote type of the given mote type class. * * @param moteTypeClass * Mote type class */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass) { if (mySimulation == null) { logger.fatal("Can't create mote type (no simulation)"); return; } // Stop simulation (if running) mySimulation.stopSimulation(); // Create mote type MoteType newMoteType = null; boolean moteTypeOK = false; try { newMoteType = moteTypeClass.newInstance(); moteTypeOK = newMoteType.configureAndInit(frame, mySimulation, isVisualized()); } catch (InstantiationException e) { logger.fatal("Exception when creating mote type: " + e); return; } catch (IllegalAccessException e) { logger.fatal("Exception when creating mote type: " + e); return; } catch (MoteTypeCreationException e) { logger.fatal("Exception when creating mote type: " + e); return; } // Add mote type to simulation if (newMoteType != null && moteTypeOK) { mySimulation.addMoteType(newMoteType); } } /** * Remove current simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doRemoveSimulation(boolean askForConfirmation) { if (mySimulation != null) { if (askForConfirmation) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Close all started non-GUI plugins for (Object startedPlugin : startedPlugins.toArray()) { int pluginType = startedPlugin.getClass().getAnnotation( PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { removePlugin((Plugin) startedPlugin, false); } } // Delete simulation mySimulation.deleteObservers(); mySimulation.stopSimulation(); mySimulation = null; // Unregister temporary plugin classes Enumeration<Class<? extends Plugin>> pluginClasses = pluginClassesTemporary .elements(); while (pluginClasses.hasMoreElements()) { unregisterPlugin(pluginClasses.nextElement()); } // Reset frame title frame.setTitle("COOJA Simulator"); } } /** * Load a simulation configuration file from disk * * @param askForConfirmation Ask for confirmation before removing any current simulation * @param quick Quick-load simulation * @param configFile Configuration file to load, if null a dialog will appear */ public void doLoadConfig(boolean askForConfirmation, final boolean quick, File configFile) { if (CoreComm.hasLibraryBeenLoaded()) { JOptionPane .showMessageDialog( frame, "Shared libraries has already been loaded.\nYou need to restart the simulator!", "Can't load simulation", JOptionPane.ERROR_MESSAGE); return; } if (askForConfirmation && mySimulation != null) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } doRemoveSimulation(false); // Check already selected file, or select file using filechooser if (configFile != null) { if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file"); return; } } else { JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); // Suggest file using history Vector<File> history = getFileHistory(); if (history != null && history.size() > 0) { File suggestedFile = getFileHistory().firstElement(); fc.setSelectedFile(suggestedFile); } int returnVal = fc.showOpenDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { configFile = fc.getSelectedFile(); // Try adding extension if not founds if (!configFile.exists()) { configFile = new File(configFile.getParent(), configFile.getName() + SAVED_SIMULATIONS_FILES); } if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file"); return; } } else { logger.info("Load command cancelled by user..."); return; } } // Load simulation in separate thread, while showing progress monitor final JDialog progressDialog = new JDialog(frame, "Loading", true); final File fileToLoad = configFile; final Thread loadThread = new Thread(new Runnable() { public void run() { Simulation newSim = null; try { newSim = loadSimulationConfig(fileToLoad, quick); addToFileHistory(fileToLoad); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } catch (UnsatisfiedLinkError e) { showErrorDialog(frame, "Simulation load error", e, false); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } newSim = null; } catch (SimulationCreationException e) { showErrorDialog(frame, "Simulation load error", e, false); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } newSim = null; } if (newSim != null) { myGUI.setSimulation(newSim); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); JProgressBar progressBar; JButton button; progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread != null && loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.pack(); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); if (quick) { SwingUtilities.invokeLater(new Runnable() { public void run() { progressDialog.setVisible(true); } }); } } /** * Reloads current simulation. * This may include recompiling libraries and renaming mote type identifiers. */ private void reloadCurrentSimulation() { if (getSimulation() == null) { logger.fatal("No simulation to reload"); return; } final JDialog progressDialog = new JDialog(frame, "Reloading", true); final Thread loadThread = new Thread(new Runnable() { public void run() { // Create mappings to new mote type identifiers Properties moteTypeNames = new Properties(); for (MoteType moteType: getSimulation().getMoteTypes()) { if (moteType.getClass().equals(ContikiMoteType.class)) { // Suggest new identifier int counter = 0; String testIdentifier = ""; boolean identifierOK = false; while (!identifierOK) { counter++; testIdentifier = ContikiMoteTypeDialog.ID_PREFIX + counter; identifierOK = true; // Check if identifier already reserved for some other type if (moteTypeNames.containsValue(testIdentifier)) { identifierOK = false; } // Check if identifier is already used by some other type for (MoteType existingMoteType : getSimulation().getMoteTypes()) { if (existingMoteType != moteType && existingMoteType.getIdentifier().equals(testIdentifier)) { identifierOK = false; break; } } // Check if library file with given identifier has already been loaded if (identifierOK && CoreComm.hasLibraryFileBeenLoaded(new File( ContikiMoteType.tempOutputDirectory, testIdentifier + ContikiMoteType.librarySuffix))) { identifierOK = false; } } moteTypeNames.setProperty(moteType.getIdentifier(), testIdentifier); } } // Get current simulation configuration Element simulationElement = new Element("simulation"); simulationElement.addContent(getSimulation().getConfigXML()); Collection<Element> pluginsConfig = getPluginsConfigXML(); // Scan and replace old configuration mote type names Element root = new Element("simconf"); root.addContent(simulationElement); if (pluginsConfig != null) { root.addContent(pluginsConfig); } Document doc = new Document(root); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); String configXML = outputter.outputString(doc); Enumeration oldNames = moteTypeNames.keys(); while (oldNames.hasMoreElements()) { String oldName = (String) oldNames.nextElement(); configXML = configXML.replaceAll(">" + oldName + "<", ">" + moteTypeNames.get(oldName) + "<"); } // Reload altered simulation config boolean shouldRetry = false; do { try { shouldRetry = false; myGUI.doRemoveSimulation(false); Simulation newSim = loadSimulationConfig(new StringReader(configXML), true); myGUI.setSimulation(newSim); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } } while (shouldRetry); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); // Display progress dialog while reloading JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); JButton button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread != null && loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.pack(); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); progressDialog.setVisible(true); } /** * Save current simulation configuration to disk * * @param askForConfirmation * Ask for confirmation before overwriting file */ public void doSaveConfig(boolean askForConfirmation) { if (mySimulation != null) { mySimulation.stopSimulation(); JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); // Suggest file using history Vector<File> history = getFileHistory(); if (history != null && history.size() > 0) { File suggestedFile = getFileHistory().firstElement(); fc.setSelectedFile(suggestedFile); } int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = fc.getSelectedFile(); if (!fc.accept(saveFile)) { saveFile = new File(saveFile.getParent(), saveFile.getName() + SAVED_SIMULATIONS_FILES); } if (saveFile.exists()) { if (askForConfirmation) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane .showOptionDialog( frame, "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } } if (!saveFile.exists() || saveFile.canWrite()) { saveSimulationConfig(saveFile); addToFileHistory(saveFile); } else { logger.fatal("No write access to file"); } } else { logger.info("Save command cancelled by user..."); } } } /** * Add new mote to current simulation */ public void doAddMotes(MoteType moteType) { if (mySimulation != null) { mySimulation.stopSimulation(); Vector<Mote> newMotes = AddMoteDialog.showDialog(frame, mySimulation, moteType); if (newMotes != null) { for (Mote newMote : newMotes) { mySimulation.addMote(newMote); } } } else { logger.warn("No simulation active"); } } /** * Create a new simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doCreateSimulation(boolean askForConfirmation) { if (askForConfirmation && mySimulation != null) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Create new simulation doRemoveSimulation(false); Simulation newSim = new Simulation(this); boolean createdOK = CreateSimDialog.showDialog(frame, newSim); if (createdOK) { myGUI.setSimulation(newSim); } } /** * Quit program * * @param askForConfirmation * Should we ask for confirmation before quitting? */ public void doQuit(boolean askForConfirmation) { if (askForConfirmation) { String s1 = "Quit"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "Sure you want to quit?", "Close COOJA Simulator", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Clean up resources Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } // Restore last frame size and position if (frame != null) { setExternalToolsSetting("FRAME_POS_X", "" + frame.getLocationOnScreen().x); setExternalToolsSetting("FRAME_POS_Y", "" + frame.getLocationOnScreen().y); setExternalToolsSetting("FRAME_WIDTH", "" + frame.getWidth()); setExternalToolsSetting("FRAME_HEIGHT", "" + frame.getHeight()); saveExternalToolsUserSettings(); } System.exit(0); } // // EXTERNAL TOOLS SETTINGS METHODS //// /** * @return Number of external tools settings */ public static int getExternalToolsSettingsCount() { return externalToolsSettingNames.length; } /** * Get name of external tools setting at given index. * * @param index * Setting index * @return Name */ public static String getExternalToolsSettingName(int index) { return externalToolsSettingNames[index]; } /** * @param name * Name of setting * @return Value */ public static String getExternalToolsSetting(String name) { return currentExternalToolsSettings.getProperty(name); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsSetting(String name, String defaultValue) { return currentExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsDefaultSetting(String name, String defaultValue) { return defaultExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param newVal * New value */ public static void setExternalToolsSetting(String name, String newVal) { currentExternalToolsSettings.setProperty(name, newVal); } /** * Load external tools settings from default file. */ public static void loadExternalToolsDefaultSettings() { String osName = System.getProperty("os.name").toLowerCase(); String filename = GUI.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; if (osName.startsWith("win")) { filename = GUI.EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME; } else if (osName.startsWith("mac os x")) { filename = GUI.EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME; } logger.info("Loading external tools user settings from: " + filename); try { InputStream in = GUI.class.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " not found"); } Properties settings = new Properties(); settings.load(in); in.close(); currentExternalToolsSettings = settings; defaultExternalToolsSettings = (Properties) currentExternalToolsSettings.clone(); } catch (IOException e) { // Error while importing default properties logger.warn( "Error when reading external tools settings from " + filename, e); } finally { if (currentExternalToolsSettings == null) { defaultExternalToolsSettings = new Properties(); currentExternalToolsSettings = new Properties(); } } } /** * Load user values from external properties file */ public static void loadExternalToolsUserSettings() { try { FileInputStream in = new FileInputStream(externalToolsUserSettingsFile); Properties settings = new Properties(); settings.load(in); in.close(); Enumeration en = settings.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); setExternalToolsSetting(key, settings.getProperty(key)); } } catch (FileNotFoundException e) { // No default configuration file found, using default } catch (IOException e) { // Error while importing saved properties, using default logger.warn("Error when reading default settings from " + externalToolsUserSettingsFile); } } /** * Save external tools user settings to file. */ public static void saveExternalToolsUserSettings() { if (externalToolsUserSettingsFileReadOnly) { return; } try { FileOutputStream out = new FileOutputStream(externalToolsUserSettingsFile); Properties differingSettings = new Properties(); Enumeration keyEnum = currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = getExternalToolsDefaultSetting(key, ""); String currentSetting = getExternalToolsSetting(key, ""); if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "COOJA External Tools (User specific)"); out.close(); } catch (FileNotFoundException ex) { // Could not open settings file for writing, aborting logger.warn("Could not save external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } catch (IOException ex) { // Could not open settings file for writing, aborting logger.warn("Error while saving external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } } // // GUI EVENT HANDLER //// private class GUIEventHandler implements ActionListener, WindowListener { public void windowDeactivated(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { myGUI.doQuit(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("new sim")) { myGUI.doCreateSimulation(true); } else if (e.getActionCommand().equals("close sim")) { myGUI.doRemoveSimulation(true); } else if (e.getActionCommand().equals("confopen sim")) { myGUI.doLoadConfig(true, false, null); } else if (e.getActionCommand().equals("confopen last sim")) { File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); myGUI.doLoadConfig(true, false, file); } else if (e.getActionCommand().equals("open sim")) { myGUI.doLoadConfig(true, true, null); } else if (e.getActionCommand().equals("open last sim")) { File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); myGUI.doLoadConfig(true, true, file); } else if (e.getActionCommand().equals("save sim")) { myGUI.doSaveConfig(true); } else if (e.getActionCommand().equals("quit")) { myGUI.doQuit(true); } else if (e.getActionCommand().equals("create mote type")) { myGUI.doCreateMoteType((Class<? extends MoteType>) ((JMenuItem) e .getSource()).getClientProperty("class")); } else if (e.getActionCommand().equals("add motes")) { myGUI.doAddMotes((MoteType) ((JMenuItem) e.getSource()) .getClientProperty("motetype")); } else if (e.getActionCommand().equals("edit paths")) { ExternalToolsDialog.showDialog(frame); } else if (e.getActionCommand().equals("close plugins")) { Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } } else if (e.getActionCommand().equals("remove all motes")) { if (getSimulation() != null) { if (getSimulation().isRunning()) { getSimulation().stopSimulation(); } while (getSimulation().getMotesCount() > 0) { getSimulation().removeMote(getSimulation().getMote(0)); } } } else if (e.getActionCommand().equals("manage projects")) { Vector<File> newProjects = ProjectDirectoriesDialog.showDialog(frame, currentProjectDirs, null); if (newProjects != null) { currentProjectDirs = newProjects; try { reparseProjectConfig(); } catch (ParseProjectsException e2) { logger.fatal("Error when loading projects: " + e2.getMessage()); e2.printStackTrace(); if (myGUI.isVisualized()) { JOptionPane.showMessageDialog(frame, "Error when loading projects.\nStack trace printed to console.", "Error", JOptionPane.ERROR_MESSAGE); } return; } } } else if (e.getActionCommand().equals("start plugin")) { Class<? extends VisPlugin> pluginClass = (Class<? extends VisPlugin>) ((JMenuItem) e .getSource()).getClientProperty("class"); Mote mote = (Mote) ((JMenuItem) e.getSource()).getClientProperty("mote"); startPlugin(pluginClass, myGUI, mySimulation, mote); } else { logger.warn("Unhandled action: " + e.getActionCommand()); } } } // // VARIOUS HELP METHODS //// /** * Help method that tries to load and initialize a class with given name. * * @param <N> * Class extending given class type * @param classType * Class type * @param className * Class name * @return Class extending given class type or null if not found */ public <N extends Object> Class<? extends N> tryLoadClass( Object callingObject, Class<N> classType, String className) { if (callingObject != null) { try { return callingObject.getClass().getClassLoader().loadClass(className) .asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } try { return Class.forName(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } try { if (projectDirClassLoader != null) { return projectDirClassLoader.loadClass(className).asSubclass( classType); } } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } return null; } public ClassLoader createProjectDirClassLoader(Vector<File> projectsDirs) throws ParseProjectsException, ClassLoaderCreationException { if (projectDirClassLoader == null) { reparseProjectConfig(); } return createClassLoader(projectDirClassLoader, projectsDirs); } private ClassLoader createClassLoader(Vector<File> currentProjectDirs) throws ClassLoaderCreationException { return createClassLoader(ClassLoader.getSystemClassLoader(), currentProjectDirs); } private File findJarFile(File projectDir, String jarfile) { File fp = new File(jarfile); if (!fp.exists()) { fp = new File(projectDir, jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/lib/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "lib/" + jarfile); } return fp.exists() ? fp : null; } private ClassLoader createClassLoader(ClassLoader parent, Vector<File> projectDirs) throws ClassLoaderCreationException { if (projectDirs == null || projectDirs.isEmpty()) { return parent; } // Combine class loader from all project directories (including any // specified JAR files) ArrayList<URL> urls = new ArrayList<URL>(); for (int j = projectDirs.size() - 1; j >= 0; j--) { File projectDir = projectDirs.get(j); try { urls.add((new File(projectDir, "java")).toURI().toURL()); // Read configuration to check if any JAR files should be loaded ProjectConfig projectConfig = new ProjectConfig(false); projectConfig.appendProjectDir(projectDir); String[] projectJarFiles = projectConfig.getStringArrayValue( GUI.class, "JARFILES"); if (projectJarFiles != null && projectJarFiles.length > 0) { for (String jarfile : projectJarFiles) { File jarpath = findJarFile(projectDir, jarfile); if (jarpath == null) { throw new FileNotFoundException(jarfile); } urls.add(jarpath.toURI().toURL()); } } } catch (Exception e) { logger.fatal("Error when trying to read JAR-file in " + projectDir + ": " + e); throw (ClassLoaderCreationException) new ClassLoaderCreationException( "Error when trying to read JAR-file in " + projectDir).initCause(e); } } URL[] urlsArray = urls.toArray(new URL[urls.size()]); return new URLClassLoader(urlsArray, parent); } /** * Help method that returns the description for given object. This method * reads from the object's class annotations if existing. Otherwise it returns * the simple class name of object's class. * * @param object * Object * @return Description */ public static String getDescriptionOf(Object object) { return getDescriptionOf(object.getClass()); } /** * Help method that returns the description for given class. This method reads * from class annotations if existing. Otherwise it returns the simple class * name. * * @param clazz * Class * @return Description */ public static String getDescriptionOf(Class<? extends Object> clazz) { if (clazz.isAnnotationPresent(ClassDescription.class)) { return clazz.getAnnotation(ClassDescription.class).value(); } return clazz.getSimpleName(); } /** * Help method that returns the abstraction level description for given mote type class. * * @param clazz * Class * @return Description */ public static String getAbstractionLevelDescriptionOf(Class<? extends MoteType> clazz) { if (clazz.isAnnotationPresent(AbstractionLevelDescription.class)) { return clazz.getAnnotation(AbstractionLevelDescription.class).value(); } return null; } /** * Load configurations and create a GUI. * * @param args * null */ public static void main(String[] args) { // Configure logger if ((new File(LOG_CONFIG_FILE)).exists()) { DOMConfigurator.configure(LOG_CONFIG_FILE); } else { // Used when starting from jar DOMConfigurator.configure(GUI.class.getResource("/" + LOG_CONFIG_FILE)); } // Parse general command arguments for (String element : args) { if (element.startsWith("-contiki=")) { String arg = element.substring("-contiki=".length()); GUI.specifiedContikiPath = arg; } if (element.startsWith("-external_tools_config=")) { String arg = element.substring("-external_tools_config=".length()); File specifiedExternalToolsConfigFile = new File(arg); if (!specifiedExternalToolsConfigFile.exists()) { logger.fatal("Specified external tools configuration not found: " + specifiedExternalToolsConfigFile); specifiedExternalToolsConfigFile = null; System.exit(1); } else { GUI.externalToolsUserSettingsFile = specifiedExternalToolsConfigFile; GUI.externalToolsUserSettingsFileReadOnly = true; } } } // Check if simulator should be quick-started if (args.length > 0 && args[0].startsWith("-quickstart=")) { String filename = args[0].substring("-quickstart=".length()); String moteTypeID = "mtype1"; Vector<String> projectDirs = null; Vector<String> sensors = null; Vector<String> coreInterfaces = null; Vector<String> userProcesses = null; boolean addAutostartProcesses = true; int numberOfNodes = 100; double areaSideLength = 100; int delayTime = 5; boolean startSimulation = true; String contikiPath = null; // Parse arguments for (int i = 1; i < args.length; i++) { if (args[i].startsWith("-id=")) { moteTypeID = args[i].substring("-id=".length()); } else if (args[i].startsWith("-projects=")) { String arg = args[i].substring("-projects=".length()); String[] argArray = arg.split(","); projectDirs = new Vector<String>(); for (String argValue : argArray) { projectDirs.add(argValue); } } else if (args[i].startsWith("-sensors=")) { String arg = args[i].substring("-sensors=".length()); String[] argArray = arg.split(","); sensors = new Vector<String>(); for (String argValue : argArray) { sensors.add(argValue); } } else if (args[i].startsWith("-interfaces=")) { String arg = args[i].substring("-interfaces=".length()); String[] argArray = arg.split(","); coreInterfaces = new Vector<String>(); for (String argValue : argArray) { coreInterfaces.add(argValue); } } else if (args[i].startsWith("-processes=")) { String arg = args[i].substring("-processes=".length()); String[] argArray = arg.split(","); userProcesses = new Vector<String>(); for (String argValue : argArray) { userProcesses.add(argValue); } } else if (args[i].equals("-noautostartscan")) { addAutostartProcesses = false; } else if (args[i].equals("-paused")) { startSimulation = false; } else if (args[i].startsWith("-nodes=")) { String arg = args[i].substring("-nodes=".length()); numberOfNodes = Integer.parseInt(arg); } else if (args[i].startsWith("-contiki=")) { String arg = args[i].substring("-contiki=".length()); contikiPath = arg; } else if (args[i].startsWith("-delay=")) { String arg = args[i].substring("-delay=".length()); delayTime = Integer.parseInt(arg); } else if (args[i].startsWith("-side=")) { String arg = args[i].substring("-side=".length()); areaSideLength = Double.parseDouble(arg); } else { logger.fatal("Unknown argument, aborting: " + args[i]); System.exit(1); } } boolean ok = quickStartSimulation(moteTypeID, projectDirs, sensors, coreInterfaces, userProcesses, addAutostartProcesses, numberOfNodes, areaSideLength, delayTime, startSimulation, filename, contikiPath); if (!ok) { System.exit(1); } } else if (args.length > 0 && args[0].startsWith("-nogui")) { // No GUI start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = new JDesktopPane(); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); new GUI(desktop); } }); } else { // Regular start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = new JDesktopPane(); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); GUI gui = new GUI(desktop); configureFrame(gui, false); } }); } } /** * Loads a simulation configuration from given file. * * When loading Contiki mote types, the libraries must be recompiled. User may * change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public Simulation loadSimulationConfig(File file, boolean quick) throws UnsatisfiedLinkError, SimulationCreationException { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(file); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick); } catch (JDOMException e) { logger.fatal("Config not wellformed: " + e.getMessage()); return null; } catch (IOException e) { logger.fatal("IOException: " + e.getMessage()); return null; } } private Simulation loadSimulationConfig(StringReader stringReader, boolean quick) throws SimulationCreationException { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(stringReader); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "IO Exception: " + e.getMessage()).initCause(e); } } private Simulation loadSimulationConfig(Element root, boolean quick) throws SimulationCreationException { Simulation newSim = null; try { // Check that config file version is correct if (!root.getName().equals("simconf")) { logger.fatal("Not a valid COOJA simulation config!"); return null; } // Create new simulation from config for (Object element : root.getChildren()) { if (((Element) element).getName().equals("simulation")) { Collection<Element> config = ((Element) element).getChildren(); newSim = new Simulation(this); boolean createdOK = newSim.setConfigXML(config, !quick); if (!createdOK) { logger.info("Simulation not loaded"); return null; } } } // Restart plugins from config setPluginsConfigXML(root.getChildren(), newSim, !quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "No access to configuration file: " + e.getMessage()).initCause(e); } catch (MoteTypeCreationException e) { throw (SimulationCreationException) new SimulationCreationException( "Mote type creation error: " + e.getMessage()).initCause(e); } catch (Exception e) { throw (SimulationCreationException) new SimulationCreationException( "Unknown error: " + e.getMessage()).initCause(e); } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File, boolean) * @param file * File to write */ public void saveSimulationConfig(File file) { try { // Create simulation configL Element root = new Element("simconf"); Element simulationElement = new Element("simulation"); simulationElement.addContent(mySimulation.getConfigXML()); root.addContent(simulationElement); // Create started plugins config Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } // Create and write to document Document doc = new Document(root); FileOutputStream out = new FileOutputStream(file); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); e.printStackTrace(); } } /** * Returns started plugins config. * * @return Config or null */ public Collection<Element> getPluginsConfigXML() { Vector<Element> config = new Vector<Element>(); // Loop through all started plugins // (Only return config of non-GUI plugins) Element pluginElement, pluginSubElement; for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class) .value(); // Ignore GUI plugins if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { continue; } pluginElement = new Element("plugin"); pluginElement.setText(startedPlugin.getClass().getName()); // Create mote argument config (if mote plugin) if (pluginType == PluginType.MOTE_PLUGIN && startedPlugin.getTag() != null) { pluginSubElement = new Element("mote_arg"); Mote taggedMote = (Mote) startedPlugin.getTag(); for (int moteNr = 0; moteNr < mySimulation.getMotesCount(); moteNr++) { if (mySimulation.getMote(moteNr) == taggedMote) { pluginSubElement.setText(Integer.toString(moteNr)); pluginElement.addContent(pluginSubElement); break; } } } // Create plugin specific configuration Collection pluginXML = startedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("plugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } // If plugin is visualizer plugin, create visualization arguments if (startedPlugin instanceof VisPlugin) { VisPlugin startedVisPlugin = (VisPlugin) startedPlugin; pluginSubElement = new Element("width"); pluginSubElement.setText("" + startedVisPlugin.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + getDesktopPane().getComponentZOrder(startedVisPlugin)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + startedVisPlugin.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + startedVisPlugin.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + startedVisPlugin.getLocation().y); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("minimized"); pluginSubElement.setText(new Boolean(startedVisPlugin.isIcon()) .toString()); pluginElement.addContent(pluginSubElement); } config.add(pluginElement); } return config; } /** * Starts plugins with arguments in given config. * * @param configXML * Config XML elements * @param simulation * Simulation on which to start plugins * @return True if all plugins started, false otherwise */ public boolean setPluginsConfigXML(Collection<Element> configXML, Simulation simulation, boolean visAvailable) { for (Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("plugin")) { // Read plugin class String pluginClassName = pluginElement.getText().trim(); Class<? extends Plugin> visPluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (visPluginClass == null) { logger.fatal("Could not load plugin class: " + pluginClassName); return false; } // Parse plugin mote argument (if any) Mote mote = null; for (Element pluginSubElement : (List<Element>) pluginElement .getChildren()) { if (pluginSubElement.getName().equals("mote_arg")) { int moteNr = Integer.parseInt(pluginSubElement.getText()); if (moteNr >= 0 && moteNr < simulation.getMotesCount()) { mote = simulation.getMote(moteNr); } } } // Start plugin (before applying rest of config) Plugin startedPlugin = startPlugin(visPluginClass, this, simulation, mote); // Apply plugin specific configuration for (Element pluginSubElement : (List<Element>) pluginElement .getChildren()) { if (pluginSubElement.getName().equals("plugin_config")) { startedPlugin.setConfigXML(pluginSubElement.getChildren(), visAvailable); } } // If plugin is visualizer plugin, parse visualization arguments if (startedPlugin instanceof VisPlugin) { Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); VisPlugin startedVisPlugin = (VisPlugin) startedPlugin; for (Element pluginSubElement : (List<Element>) pluginElement .getChildren()) { if (pluginSubElement.getName().equals("width") && size != null) { size.width = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); // Save z order as temporary client property startedVisPlugin.putClientProperty("zorder", zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { try { startedVisPlugin.setIcon(Boolean.parseBoolean(pluginSubElement .getText())); } catch (PropertyVetoException e) { // Ignoring } } } } } } // For all started visplugins, check if they have a zorder property try { for (JInternalFrame plugin : getDesktopPane().getAllFrames()) { if (plugin.getClientProperty("zorder") != null) { getDesktopPane().setComponentZOrder(plugin, ((Integer) plugin.getClientProperty("zorder")).intValue()); plugin.putClientProperty("zorder", null); } } } catch (Exception e) { // Ignore errors } return true; } public class ParseProjectsException extends Exception { public ParseProjectsException(String message) { super(message); } } public class ClassLoaderCreationException extends Exception { public ClassLoaderCreationException(String message) { super(message); } } public class SimulationCreationException extends Exception { public SimulationCreationException(String message) { super(message); } } /** * Shows a simple dialog with information about the thrown exception. A user * may watch the stack trace and, if the exception is a * MoteTypeCreationException, watch compilation output. * * @param parentComponent * Parent component * @param title * Title of error window * @param exception * Exception causing window to be shown * @param retryAvailable * If true, a retry option is available */ public static boolean showErrorDialog(Component parentComponent, final String title, Throwable exception, boolean retryAvailable) { MessageList compilationOutput = null; MessageList stackTrace = null; String message = title; // Create message if (exception != null) { message = exception.getMessage(); } // Create stack trace message list if (exception != null) { stackTrace = new MessageList(); PrintStream printStream = stackTrace.getInputStream(MessageList.NORMAL); exception.printStackTrace(printStream); } // Create compilation out message list (if available) if (exception != null && exception instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception) .getCompilationOutput(); } else if (exception != null && exception.getCause() != null && exception.getCause() instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception.getCause()) .hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception.getCause()) .getCompilationOutput(); } // Create error dialog final JDialog errorDialog; if (parentComponent instanceof Dialog) { errorDialog = new JDialog((Dialog) parentComponent, title, true); } else if (parentComponent instanceof Frame) { errorDialog = new JDialog((Frame) parentComponent, title, true); } else { logger.fatal("Bad parent for error dialog"); errorDialog = new JDialog((Frame) null, title + " (Java stack trace)"); } final JPanel errorPanel = new JPanel(); errorPanel.setLayout(new BoxLayout(errorPanel, BoxLayout.Y_AXIS)); errorPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Box messageBox = Box.createHorizontalBox(); // Icon myIcon = (Icon)DefaultLookup.get(errorPanel, null, // "OptionPane.errorIcon"); // messageBox.add(new JLabel(myIcon)); messageBox.add(Box.createHorizontalGlue()); messageBox.add(new JLabel(message)); messageBox.add(Box.createHorizontalGlue()); Box buttonBox = Box.createHorizontalBox(); if (compilationOutput != null) { final MessageList listToDisplay = compilationOutput; final String titleToDisplay = title + " (Compilation output)"; JButton showCompilationButton = new JButton("Show compilation output"); showCompilationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JDialog messageListDialog = new JDialog(errorDialog, titleToDisplay); JPanel messageListPanel = new JPanel(new BorderLayout()); messageListPanel.add(BorderLayout.CENTER, new JScrollPane( listToDisplay)); messageListPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); messageListPanel.setVisible(true); messageListDialog.getContentPane().add(messageListPanel); messageListDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); messageListDialog.pack(); messageListDialog.setLocationRelativeTo(errorDialog); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); if (maxSize != null && (messageListDialog.getSize().getWidth() > maxSize.getWidth() || messageListDialog .getSize().getHeight() > maxSize.getHeight())) { Dimension newSize = new Dimension(); newSize.height = Math.min((int) maxSize.getHeight(), (int) messageListDialog.getSize().getHeight()); newSize.width = Math.min((int) maxSize.getWidth(), (int) messageListDialog.getSize().getWidth()); messageListDialog.setSize(newSize); } messageListDialog.setVisible(true); } }); buttonBox.add(showCompilationButton); } if (stackTrace != null) { final MessageList listToDisplay = stackTrace; final String titleToDisplay = title + " (Java stack trace)"; JButton showTraceButton = new JButton("Show Java stack trace"); showTraceButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JDialog messageListDialog = new JDialog(errorDialog, titleToDisplay); JPanel messageListPanel = new JPanel(new BorderLayout()); messageListPanel.add(BorderLayout.CENTER, new JScrollPane( listToDisplay)); messageListPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); messageListPanel.setVisible(true); messageListDialog.getContentPane().add(messageListPanel); messageListDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); messageListDialog.pack(); messageListDialog.setLocationRelativeTo(errorDialog); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); if (maxSize != null && (messageListDialog.getSize().getWidth() > maxSize.getWidth() || messageListDialog .getSize().getHeight() > maxSize.getHeight())) { Dimension newSize = new Dimension(); newSize.height = Math.min((int) maxSize.getHeight(), (int) messageListDialog.getSize().getHeight()); newSize.width = Math.min((int) maxSize.getWidth(), (int) messageListDialog.getSize().getWidth()); messageListDialog.setSize(newSize); } messageListDialog.setVisible(true); } }); buttonBox.add(showTraceButton); } if (retryAvailable) { JButton retryButton = new JButton("Retry"); retryButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { errorDialog.dispose(); errorDialog.setTitle("-RETRY-"); } }); buttonBox.add(retryButton); } final JButton closeButton = new JButton("Close"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { errorDialog.dispose(); } }); buttonBox.add(closeButton); // Dispose on escape key InputMap inputMap = errorDialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "dispose"); AbstractAction cancelAction = new AbstractAction(){ public void actionPerformed(ActionEvent e) { closeButton.doClick(); } }; errorDialog.getRootPane().getActionMap().put("dispose", cancelAction); errorPanel.add(messageBox); errorPanel.add(Box.createVerticalStrut(20)); errorPanel.add(buttonBox); errorDialog.getContentPane().add(errorPanel); errorDialog.pack(); errorDialog.setLocationRelativeTo(parentComponent); errorDialog.setVisible(true); if (errorDialog.getTitle().equals("-RETRY-")) { return true; } return false; } /** * This method can be used by various different modules in the simulator to * indicate for example that a mote has been selected. All mote highlight * listeners will be notified. An example application of mote highlightinh is * a simulator visualizer that highlights the mote. * * @see #addMoteHighligtObserver(Observer) * @param m * Mote to highlight */ public void signalMoteHighlight(Mote m) { moteHighlightObservable.highlightMote(m); } }
tools/cooja/java/se/sics/cooja/GUI.java
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $Id: GUI.java,v 1.66 2008/02/07 10:30:19 fros4943 Exp $ */ package se.sics.cooja; import java.awt.*; import java.awt.event.*; import java.beans.PropertyVetoException; import java.io.*; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import se.sics.cooja.MoteType.MoteTypeCreationException; import se.sics.cooja.contikimote.*; import se.sics.cooja.dialogs.*; import se.sics.cooja.plugins.*; /** * Main file of COOJA Simulator. Typically contains a visualizer for the * simulator, but can also be started without visualizer. * * This class loads external Java classes (in project directories), and handles the * COOJA plugins as well as the configuration system. If provides a number of * help methods for the rest of the COOJA system, and is the starting point for * loading and saving simulation configs. * * @author Fredrik Osterlind */ public class GUI { /** * External tools default Win32 settings filename. */ public static final String EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME = "/external_tools_win32.config"; /** * External tools default Mac OS X settings filename. */ public static final String EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME = "/external_tools_macosx.config"; /** * External tools default Linux/Unix settings filename. */ public static final String EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME = "/external_tools_linux.config"; /** * External tools user settings filename. */ public static final String EXTERNAL_TOOLS_USER_SETTINGS_FILENAME = ".cooja.user.properties"; public static File externalToolsUserSettingsFile = new File(System.getProperty("user.home"), EXTERNAL_TOOLS_USER_SETTINGS_FILENAME); private static boolean externalToolsUserSettingsFileReadOnly = false; private static String specifiedContikiPath = null; /** * Logger settings filename. */ public static final String LOG_CONFIG_FILE = "log4j_config.xml"; /** * Default project configuration filename. */ public static final String PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_default.config"; /** * User project configuration filename. */ public static final String PROJECT_CONFIG_FILENAME = "cooja.config"; /** * File filter only showing saved simulations files (*.csc). */ public static final FileFilter SAVED_SIMULATIONS_FILES = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".csc")) { return true; } return false; } public String getDescription() { return "COOJA Configuration files"; } public String toString() { return ".csc"; } }; /** * Main frame for current GUI. Null when COOJA is run without visualizer! */ public static JFrame frame; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(GUI.class); // External tools setting names private static Properties defaultExternalToolsSettings; private static Properties currentExternalToolsSettings; private static final String externalToolsSettingNames[] = new String[] { "PATH_CONTIKI", "PATH_COOJA_CORE_RELATIVE", "PATH_MAKE", "PATH_SHELL", "PATH_C_COMPILER", "COMPILER_ARGS", "PATH_LINKER", "LINK_COMMAND_1", "LINK_COMMAND_2", "PATH_AR", "AR_COMMAND_1", "AR_COMMAND_2", "PATH_OBJDUMP", "OBJDUMP_ARGS", "PATH_JAVAC", "CONTIKI_STANDARD_PROCESSES", "CONTIKI_MAIN_TEMPLATE_FILENAME", "CMD_GREP_PROCESSES", "REGEXP_PARSE_PROCESSES", "CMD_GREP_INTERFACES", "REGEXP_PARSE_INTERFACES", "CMD_GREP_SENSORS", "REGEXP_PARSE_SENSORS", "DEFAULT_PROJECTDIRS", "CORECOMM_TEMPLATE_FILENAME", "MAPFILE_DATA_START", "MAPFILE_DATA_SIZE", "MAPFILE_BSS_START", "MAPFILE_BSS_SIZE", "MAPFILE_VAR_NAME", "MAPFILE_VAR_ADDRESS_1", "MAPFILE_VAR_ADDRESS_2", "MAPFILE_VAR_SIZE_1", "MAPFILE_VAR_SIZE_2", "PARSE_WITH_COMMAND", "PARSE_COMMAND", "COMMAND_VAR_NAME_ADDRESS", "COMMAND_DATA_START", "COMMAND_DATA_END", "COMMAND_BSS_START", "COMMAND_BSS_END", }; private static final int FRAME_NEW_OFFSET = 30; private static final int FRAME_STANDARD_WIDTH = 150; private static final int FRAME_STANDARD_HEIGHT = 300; private GUI myGUI; private Simulation mySimulation; protected GUIEventHandler guiEventHandler = new GUIEventHandler(); private JMenu menuPlugins, menuMoteTypeClasses, menuMoteTypes; private JMenu menuOpenSimulation, menuConfOpenSimulation; private Vector<Class<? extends Plugin>> menuMotePluginClasses; private JDesktopPane myDesktopPane; private Vector<Plugin> startedPlugins = new Vector<Plugin>(); // Platform configuration variables // Maintained via method reparseProjectConfig() private ProjectConfig projectConfig; private Vector<File> currentProjectDirs = new Vector<File>(); private ClassLoader projectDirClassLoader; private Vector<Class<? extends MoteType>> moteTypeClasses = new Vector<Class<? extends MoteType>>(); private Vector<Class<? extends Plugin>> pluginClasses = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends Plugin>> pluginClassesTemporary = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends RadioMedium>> radioMediumClasses = new Vector<Class<? extends RadioMedium>>(); private Vector<Class<? extends IPDistributor>> ipDistributorClasses = new Vector<Class<? extends IPDistributor>>(); private Vector<Class<? extends Positioner>> positionerClasses = new Vector<Class<? extends Positioner>>(); // Mote highlight observable private class HighlightObservable extends Observable { private void highlightMote(Mote mote) { setChanged(); notifyObservers(mote); } } private HighlightObservable moteHighlightObservable = new HighlightObservable(); /** * Creates a new COOJA Simulator GUI. * * @param desktop Desktop pane */ public GUI(JDesktopPane desktop) { myGUI = this; mySimulation = null; myDesktopPane = desktop; if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); } if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); if (specifiedContikiPath != null) { setExternalToolsSetting("PATH_CONTIKI", specifiedContikiPath); } // Register default project directories String defaultProjectDirs = getExternalToolsSetting( "DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null) { String[] defaultProjectDirsArr = defaultProjectDirs.split(";"); if (defaultProjectDirsArr.length > 0) { for (String defaultProjectDir : defaultProjectDirsArr) { File projectDir = new File(defaultProjectDir); if (projectDir.exists() && projectDir.isDirectory()) { currentProjectDirs.add(projectDir); } } } } // Load extendable parts (using current project config) try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading project directories: " + e.getMessage()); e.printStackTrace(); if (myDesktopPane != null) { JOptionPane.showMessageDialog(frame, "Loading project directories failed.\nStack trace printed to console.", "Error", JOptionPane.ERROR_MESSAGE); } } // Start all standard GUI plugins for (Class<? extends Plugin> visPluginClass : pluginClasses) { int pluginType = visPluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { startPlugin(visPluginClass, this, null, null); } } } /** * Add mote highlight observer. * * @see #deleteTickObserver(Observer) * @param newObserver * New observer */ public void addMoteHighligtObserver(Observer newObserver) { moteHighlightObservable.addObserver(newObserver); } /** * Delete an mote highlight observer. * * @see #addTickObserver(Observer) * @param observer * Observer to delete */ public void deleteMoteHighligtObserver(Observer observer) { moteHighlightObservable.deleteObserver(observer); } /** * @return True if simulator is visualized */ public boolean isVisualized() { return frame != null; } /** * EXPERIMENTAL! * Tries to create/remove simulator visualizer. * * @param visualized Visualized */ public void setVisualized(boolean visualized) { if (!isVisualized() && visualized) { configureFrame(myGUI, false); } else { frame.setVisible(false); frame.dispose(); frame = null; } } private Vector<File> getFileHistory() { Vector<File> history = new Vector<File>(); // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); for (String file: historyArray) { history.add(new File(file)); } return history; } private void addToFileHistory(File file) { // Fetch current history String[] history = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); // Create new history String[] newHistory = null; if (history == null || history.length <= 1 && history[0].equals("")) { newHistory = new String[1]; } else { newHistory = new String[Math.min(5, history.length+1)]; System.arraycopy(history, 0, newHistory, 1, newHistory.length-1); } newHistory[0] = file.getAbsolutePath(); // Abort if file added is equal to last file if (history.length >= 1 && file.getAbsolutePath().equals(new File(history[0]).getAbsolutePath())) { return; } String newHistoryConfig = null; for (String path: newHistory) { if (newHistoryConfig == null) { newHistoryConfig = path; } else { newHistoryConfig += ";" + path; } } setExternalToolsSetting("SIMCFG_HISTORY", newHistoryConfig); saveExternalToolsUserSettings(); } private void updateOpenHistoryMenuItems() { menuConfOpenSimulation.removeAll(); JMenuItem browseItem = new JMenuItem("Browse..."); browseItem.setActionCommand("confopen sim"); browseItem.addActionListener(guiEventHandler); menuConfOpenSimulation.add(browseItem); menuConfOpenSimulation.add(new JSeparator()); Vector<File> openFilesHistory = getFileHistory(); for (File file: openFilesHistory) { JMenuItem lastItem = new JMenuItem(file.getName()); lastItem.setActionCommand("confopen last sim"); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); lastItem.addActionListener(guiEventHandler); menuConfOpenSimulation.add(lastItem); } menuOpenSimulation.removeAll(); browseItem = new JMenuItem("Browse..."); browseItem.setActionCommand("open sim"); browseItem.addActionListener(guiEventHandler); menuOpenSimulation.add(browseItem); menuOpenSimulation.add(new JSeparator()); for (File file: openFilesHistory) { JMenuItem lastItem = new JMenuItem(file.getName()); lastItem.setActionCommand("open last sim"); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); lastItem.addActionListener(guiEventHandler); menuOpenSimulation.add(lastItem); } } private JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu; JMenuItem menuItem; // File menu menu = new JMenu("File"); menu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateOpenHistoryMenuItems(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); menuItem = new JMenuItem("New simulation"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("new sim"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuItem = new JMenuItem("Reload simulation"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { reloadCurrentSimulation(); } }); menu.add(menuItem); menuItem = new JMenuItem("Close simulation"); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.setActionCommand("close sim"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuOpenSimulation = new JMenu("Open simulation"); menuOpenSimulation.setMnemonic(KeyEvent.VK_O); menu.add(menuOpenSimulation); menuConfOpenSimulation = new JMenu("Open & Reconfigure simulation"); menuConfOpenSimulation.setMnemonic(KeyEvent.VK_R); menu.add(menuConfOpenSimulation); menuItem = new JMenuItem("Save simulation"); menuItem.setMnemonic(KeyEvent.VK_S); menuItem.setActionCommand("save sim"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Close all plugins"); menuItem.setActionCommand("close plugins"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Exit"); menuItem.setMnemonic(KeyEvent.VK_X); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("quit"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Simulation menu menu = new JMenu("Simulation"); menu.setMnemonic(KeyEvent.VK_S); menuBar.add(menu); menuItem = new JMenuItem("Open Control"); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", SimControl.class); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuItem = new JMenuItem("Information"); menuItem.setMnemonic(KeyEvent.VK_I); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", SimInformation.class); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Mote type menu menu = new JMenu("Mote Types"); menu.setMnemonic(KeyEvent.VK_T); menuBar.add(menu); // Mote type classes sub menu menuMoteTypeClasses = new JMenu("Create mote type"); menuMoteTypeClasses.setMnemonic(KeyEvent.VK_C); menuMoteTypeClasses.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypeClasses.removeAll(); // Recreate menu items JMenuItem menuItem; for (Class<? extends MoteType> moteTypeClass : moteTypeClasses) { /* Sort mote types according to abstraction level */ String abstractionLevelDescription = GUI.getAbstractionLevelDescriptionOf(moteTypeClass); if(abstractionLevelDescription == null) { abstractionLevelDescription = "[unknown cross-level]"; } /* Check if abstraction description already exists */ JSeparator abstractionLevelSeparator = null; for (Component component: menuMoteTypeClasses.getMenuComponents()) { if (component == null || !(component instanceof JSeparator)) { continue; } JSeparator existing = (JSeparator) component; if (abstractionLevelDescription.equals(existing.getToolTipText())) { abstractionLevelSeparator = existing; break; } } if (abstractionLevelSeparator == null) { abstractionLevelSeparator = new JSeparator(); abstractionLevelSeparator.setToolTipText(abstractionLevelDescription); menuMoteTypeClasses.add(abstractionLevelSeparator); } String description = GUI.getDescriptionOf(moteTypeClass); menuItem = new JMenuItem(description); menuItem.setActionCommand("create mote type"); menuItem.putClientProperty("class", moteTypeClass); menuItem.setToolTipText(abstractionLevelDescription); menuItem.addActionListener(guiEventHandler); /* Add new item directly after cross level separator */ for (int i=0; i < menuMoteTypeClasses.getMenuComponentCount(); i++) { if (menuMoteTypeClasses.getMenuComponent(i) == abstractionLevelSeparator) { menuMoteTypeClasses.add(menuItem, i+1); break; } } } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypeClasses); menuItem = new JMenuItem("Information"); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", MoteTypeInformation.class); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Mote menu menu = new JMenu("Motes"); menu.setMnemonic(KeyEvent.VK_M); menuBar.add(menu); // Mote types sub menu menuMoteTypes = new JMenu("Add motes of type"); menuMoteTypes.setMnemonic(KeyEvent.VK_A); menuMoteTypes.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypes.removeAll(); if (mySimulation == null) { return; } // Recreate menu items JMenuItem menuItem; for (MoteType moteType : mySimulation.getMoteTypes()) { menuItem = new JMenuItem(moteType.getDescription()); menuItem.setActionCommand("add motes"); menuItem.setToolTipText(getDescriptionOf(moteType.getClass())); menuItem.putClientProperty("motetype", moteType); menuItem.addActionListener(guiEventHandler); menuMoteTypes.add(menuItem); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menu.add(menuMoteTypes); menuItem = new JMenuItem("Remove all motes"); menuItem.setActionCommand("remove all motes"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); // Plugins menu if (menuPlugins == null) { menuPlugins = new JMenu("Plugins"); } else { menuPlugins.setText("Plugins"); } menuPlugins.setMnemonic(KeyEvent.VK_P); menuBar.add(menuPlugins); // Settings menu menu = new JMenu("Settings"); menuBar.add(menu); menuItem = new JMenuItem("External tools paths"); menuItem.setActionCommand("edit paths"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menuItem = new JMenuItem("Manage project directories"); menuItem.setActionCommand("manage projects"); menuItem.addActionListener(guiEventHandler); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Java version: " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); menuItem.setEnabled(false); menu.add(menuItem); // Mote plugins popup menu (not available via menu bar) if (menuMotePluginClasses == null) { menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); } return menuBar; } private static void configureFrame(final GUI gui, boolean createSimDialog) { // Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); // Create and set up the window. frame = new JFrame("COOJA Simulator"); if (maxSize != null) { frame.setMaximizedBounds(maxSize); } frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Add menu bar frame.setJMenuBar(gui.createMenuBar()); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.setSize(700, 700); frame.setLocationRelativeTo(null); frame.addWindowListener(gui.guiEventHandler); // Restore last frame size and position if (frame != null) { int framePosX = Integer.parseInt(getExternalToolsSetting("FRAME_POS_X", "-1")); int framePosY = Integer.parseInt(getExternalToolsSetting("FRAME_POS_Y", "-1")); int frameWidth = Integer.parseInt(getExternalToolsSetting("FRAME_WIDTH", "-1")); int frameHeight = Integer.parseInt(getExternalToolsSetting("FRAME_HEIGHT", "-1")); if (framePosX >= 0 && framePosY >= 0 && frameWidth > 0 && frameHeight > 0) { frame.setLocation(framePosX, framePosY); frame.setSize(frameWidth, frameHeight); // Assume window was maximized if loaded size matches maximum bounds if (maxSize != null && framePosX == 0 && framePosY == 0 && frameWidth == maxSize.width && frameHeight == maxSize.height) { frame.setExtendedState(JFrame.MAXIMIZED_BOTH); } } } // Display the window. frame.setVisible(true); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } /** * @return Current desktop pane (simulator visualizer) */ public JDesktopPane getDesktopPane() { return myDesktopPane; } /** * Quick-starts a simulation using given parameters. TODO Experimental code * * @param moteTypeID * Mote type ID (if null "mtype1" will be used) * @param projectDirs * GUI project directories * @param sensors * Contiki sensors (if null sensors will be scanned for) * @param coreInterfaces * COOJA core interfaces (if null interfaces will be scanned for) * @param userProcesses * Contiki user processes (if null processes all in given main file * will be added) * @param addAutostartProcesses * Should autostart processes automatically be added? * @param numberOfNodes * Number of nodes to add * @param areaSideLength * Side of node positioning square * @param delayTime * Initial delay time * @param simulationStartinge * Simulation automatically started? * @param filename * Main Contiki process file * @param contikiPath * Contiki path * @return True if simulation was quickstarted correctly */ private static boolean quickStartSimulation(String moteTypeID, Vector<String> projectDirs, Vector<String> sensors, Vector<String> coreInterfaces, Vector<String> userProcesses, boolean addAutostartProcesses, int numberOfNodes, double areaSideLength, int delayTime, boolean simulationStarting, String filename, String contikiPath) { // Create GUI and GUI frame (not visible yet) JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); logger.info("> Creating GUI and main frame (invisible)"); frame = new JFrame("COOJA Simulator"); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Create and set up the content pane. JDesktopPane desktop = new JDesktopPane(); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); GUI gui = new GUI(desktop); // loads external settings and creates initial project config // Add menu bar frame.setSize(700, 700); frame.addWindowListener(gui.guiEventHandler); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.setLocationRelativeTo(null); // Set manual Contiki path if specified if (contikiPath != null) { setExternalToolsSetting("PATH_CONTIKI", contikiPath); } // Parse project directories and create config if (projectDirs == null) { projectDirs = new Vector<String>(); projectDirs.add("."); } // TODO Should add user prop projects as well here... logger.info("> Reparsing project directories and creating config"); for (String projectDir : projectDirs) { logger.info(">> Adding: " + projectDir); // Check if config file exists File configFile = new File(projectDir + File.separatorChar + PROJECT_CONFIG_FILENAME); if (!configFile.exists()) { logger.debug(">>> Creating empty cooja.config file"); try { configFile.createNewFile(); } catch (IOException e) { logger.fatal(">> Error when creating cooja.config file, aborting"); return false; } } gui.currentProjectDirs.add(new File(projectDir)); } try { gui.reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal(">> Error when parsing project directories: " + e.getMessage()); return false; } // Check file permissions and paths logger.info("> Checking paths and file permissions"); if (moteTypeID == null) { moteTypeID = "mtype1"; } File contikiBaseDir = new File(getExternalToolsSetting("PATH_CONTIKI")); File contikiCoreDir = new File(contikiBaseDir, getExternalToolsSetting("PATH_COOJA_CORE_RELATIVE")); File libFile = new File(ContikiMoteType.tempOutputDirectory, moteTypeID + ContikiMoteType.librarySuffix); File mapFile = new File(ContikiMoteType.tempOutputDirectory, moteTypeID + ContikiMoteType.mapSuffix); File depFile = new File(ContikiMoteType.tempOutputDirectory, moteTypeID + ContikiMoteType.dependSuffix); if (libFile.exists()) { libFile.delete(); } if (depFile.exists()) { depFile.delete(); } if (mapFile.exists()) { mapFile.delete(); } if (libFile.exists()) { logger.fatal(">> Can't delete output file, aborting: " + libFile); return false; } if (depFile.exists()) { logger.fatal(">> Can't delete output file, aborting: " + depFile); return false; } if (mapFile.exists()) { logger.fatal(">> Can't delete output file, aborting: " + mapFile); return false; } // Search for main file in current directory (or arg) File mainProcessFile = new File(filename); logger.info(">> Searching main process file: " + mainProcessFile.getAbsolutePath()); if (!mainProcessFile.exists()) { logger.info(">> Searching main process file: " + mainProcessFile.getAbsolutePath()); boolean foundFile = false; for (String projectDir : projectDirs) { mainProcessFile = new File(projectDir, filename); logger.info(">> Searching main process file: " + mainProcessFile.getAbsolutePath()); if (mainProcessFile.exists()) { foundFile = true; break; } } if (!foundFile) { logger.fatal(">> Could not locate main process file, aborting"); return false; } } // Setup compilation arguments logger.info("> Setting up compilation arguments"); Vector<File> filesToCompile = new Vector<File>(); filesToCompile.add(mainProcessFile); // main process file for (String projectDir : projectDirs) { // project directories filesToCompile.add(new File(projectDir)); } String[] projectSources = // project config sources gui.getProjectConfig().getStringArrayValue(ContikiMoteType.class, "C_SOURCES"); for (String projectSource : projectSources) { if (!projectSource.equals("")) { File file = new File(projectSource); if (file.getParent() != null) { // Find which project directory added this file File projectDir = gui.getProjectConfig().getUserProjectDefining( ContikiMoteType.class, "C_SOURCES", projectSource); if (projectDir != null) { // We found a project directory - Add it filesToCompile.add(new File(projectDir.getPath(), file .getParent())); } } filesToCompile.add(new File(file.getName())); } } // Scan for sensors if (sensors == null) { logger.info("> Scanning for sensors"); sensors = new Vector<String>(); Vector<String[]> scannedSensorInfo = ContikiMoteTypeDialog .scanForSensors(contikiCoreDir); for (String projectDir : projectDirs) { // project directories scannedSensorInfo.addAll(ContikiMoteTypeDialog.scanForSensors(new File( projectDir))); } for (String[] sensorInfo : scannedSensorInfo) { // logger.info(">> Found and added: " + sensorInfo[1] + " (" + // sensorInfo[0] + ")"); sensors.add(sensorInfo[1]); } } // Scan for core interfaces if (coreInterfaces == null) { logger.info("> Scanning for core interfaces"); coreInterfaces = new Vector<String>(); Vector<String[]> scannedCoreInterfaceInfo = ContikiMoteTypeDialog .scanForInterfaces(contikiCoreDir); for (String projectDir : projectDirs) { // project directories scannedCoreInterfaceInfo.addAll(ContikiMoteTypeDialog .scanForInterfaces(new File(projectDir))); } for (String[] coreInterfaceInfo : scannedCoreInterfaceInfo) { // logger.info(">> Found and added: " + coreInterfaceInfo[1] + " (" + // coreInterfaceInfo[0] + ")"); coreInterfaces.add(coreInterfaceInfo[1]); } } // Scan for mote interfaces logger.info("> Loading mote interfaces"); String[] moteInterfaces = gui.getProjectConfig().getStringArrayValue( ContikiMoteType.class, "MOTE_INTERFACES"); Vector<Class<? extends MoteInterface>> moteIntfClasses = new Vector<Class<? extends MoteInterface>>(); for (String moteInterface : moteInterfaces) { try { Class<? extends MoteInterface> newMoteInterfaceClass = gui .tryLoadClass(gui, MoteInterface.class, moteInterface); moteIntfClasses.add(newMoteInterfaceClass); // logger.info(">> Loaded mote interface: " + newMoteInterfaceClass); } catch (Exception e) { logger.fatal(">> Failed to load mote interface, aborting: " + moteInterface + ", " + e.getMessage()); return false; } } // Scan for processes if (userProcesses == null) { logger.info("> Scanning for user processes"); userProcesses = new Vector<String>(); Vector<String> autostartProcesses = new Vector<String>(); Vector<String[]> scannedProcessInfo = ContikiMoteTypeDialog .scanForProcesses(contikiCoreDir); for (String projectDir : projectDirs) { // project directories scannedProcessInfo.addAll(ContikiMoteTypeDialog .scanForProcesses(new File(projectDir))); } for (String[] processInfo : scannedProcessInfo) { if (processInfo[0].equals(mainProcessFile.getName())) { logger.info(">> Found and added: " + processInfo[1] + " (" + processInfo[0] + ")"); userProcesses.add(processInfo[1]); if (addAutostartProcesses) { // Parse any autostart processes try { // logger.info(">>> Parsing " + processInfo[0] + " for autostart // processes"); Vector<String> autostarters = ContikiMoteTypeDialog .parseAutostartProcesses(mainProcessFile); if (autostarters != null) { autostartProcesses.addAll(autostarters); } } catch (Exception e) { logger .fatal(">>> Error when parsing autostart processes, aborting: " + e); return false; } } } else { // logger.info(">> Found and ignored: " + processInfo[1] + " (" + // processInfo[0] + ")"); } } if (addAutostartProcesses) { // Add autostart process sources if found logger.info("> Adding autostart processes"); for (String autostartProcess : autostartProcesses) { boolean alreadyExists = false; for (String existingProcess : userProcesses) { if (existingProcess.equals(autostartProcess)) { alreadyExists = true; break; } } if (!alreadyExists) { userProcesses.add(autostartProcess); logger.info(">> Added autostart process: " + autostartProcess); } } } } // Generate Contiki main source file logger.info("> Generating Contiki main source file"); if (!ContikiMoteType.tempOutputDirectory.exists()) { ContikiMoteType.tempOutputDirectory.mkdir(); } if (!ContikiMoteType.tempOutputDirectory.exists()) { logger.fatal(">> Could not create output directory: " + ContikiMoteType.tempOutputDirectory); return false; } try { String generatedFilename = ContikiMoteTypeDialog.generateSourceFile( moteTypeID, sensors, coreInterfaces, userProcesses); // logger.info(">> Generated source file: " + generatedFilename); } catch (Exception e) { logger.fatal(">> Error during file generation, aborting: " + e.getMessage()); return false; } // Compile library logger.info("> Compiling library (Rime comm stack)"); // TODO Warning, assuming Rime communication stack boolean compilationSucceded = ContikiMoteTypeDialog.compileLibrary( moteTypeID, contikiBaseDir, filesToCompile, false, ContikiMoteType.CommunicationStack.RIME, null, System.err); if (!libFile.exists() || !depFile.exists() || !mapFile.exists()) { compilationSucceded = false; } if (compilationSucceded) { // logger.info(">> Compilation complete"); } else { logger.fatal(">> Error during compilation, aborting"); return false; } // Create mote type logger.info("> Creating mote type"); ContikiMoteType moteType; try { moteType = new ContikiMoteType(moteTypeID); } catch (MoteTypeCreationException e) { logger.fatal("Exception when creating mote type: " + e); return false; } moteType.setDescription("Mote type: " + filename); moteType.setContikiBaseDir(contikiBaseDir.getPath()); moteType.setContikiCoreDir(contikiCoreDir.getPath()); moteType.setProjectDirs(new Vector<File>()); moteType.setCompilationFiles(filesToCompile); moteType.setConfig(gui.getProjectConfig()); moteType.setProcesses(userProcesses); moteType.setSensors(sensors); moteType.setCoreInterfaces(coreInterfaces); moteType.setMoteInterfaces(moteIntfClasses); // Create simulation logger.info("> Creating simulation"); Simulation simulation = new Simulation(gui); simulation.setTitle("Quickstarted: " + filename); simulation.setDelayTime(delayTime); simulation.setSimulationTime(0); simulation.setTickTime(1); String radioMediumClassName = null; try { radioMediumClassName = gui.getProjectConfig().getStringArrayValue( GUI.class, "RADIOMEDIUMS")[0]; Class<? extends RadioMedium> radioMediumClass = gui.tryLoadClass(gui, RadioMedium.class, radioMediumClassName); RadioMedium radioMedium = RadioMedium.generateRadioMedium( radioMediumClass, simulation); simulation.setRadioMedium(radioMedium); } catch (Exception e) { logger.fatal(">> Failed to load radio medium, aborting: " + radioMediumClassName + ", " + e); return false; } // Create nodes logger.info("> Creating motes"); Vector<ContikiMote> motes = new Vector<ContikiMote>(); Random random = new Random(); int nextMoteID = 1; int nextIP = 0; for (int i = 0; i < numberOfNodes; i++) { ContikiMote mote = (ContikiMote) moteType.generateMote(simulation); // Set random position if (mote.getInterfaces().getPosition() != null) { mote.getInterfaces().getPosition().setCoordinates( random.nextDouble() * areaSideLength, random.nextDouble() * areaSideLength, 0); } // Set unique mote ID's if (mote.getInterfaces().getMoteID() != null) { mote.getInterfaces().getMoteID().setMoteID(nextMoteID++); } // Set unique IP address if (mote.getInterfaces().getIPAddress() != null) { mote.getInterfaces().getIPAddress().setIPNumber((char) 10, (char) ((nextIP / (254 * 255)) % 255), (char) ((nextIP / 254) % 255), (char) (nextIP % 254 + 1)); nextIP++; } motes.add(mote); } // Add mote type and motes to simulation logger.info("> Adding motes and mote type to simulation"); simulation.addMoteType(moteType); for (Mote mote : motes) { simulation.addMote(mote); } // Add simulation to GUI logger.info("> Adding simulation to GUI"); gui.setSimulation(simulation); // Start plugins and try to place them wisely logger.info("> Starting plugin and showing GUI"); VisPlugin plugin = (VisPlugin) gui.startPlugin(VisState.class, gui, simulation, null); plugin.setLocation(350, 20); plugin = (VisPlugin) gui.startPlugin(VisTraffic.class, gui, simulation, null); plugin.setLocation(350, 340); plugin = (VisPlugin) gui.startPlugin(LogListener.class, gui, simulation, null); plugin.setLocation(20, 420); frame.setJMenuBar(gui.createMenuBar()); // Finally show GUI frame.setVisible(true); if (simulationStarting) { simulation.startSimulation(); } return true; } //// PROJECT CONFIG AND EXTENDABLE PARTS METHODS //// /** * Register new mote type class. * * @param moteTypeClass * Class to register */ public void registerMoteType(Class<? extends MoteType> moteTypeClass) { moteTypeClasses.add(moteTypeClass); } /** * Unregister all mote type classes. */ public void unregisterMoteTypes() { moteTypeClasses.clear(); } /** * @return All registered mote type classes */ public Vector<Class<? extends MoteType>> getRegisteredMoteTypes() { return moteTypeClasses; } /** * Register new IP distributor class * * @param ipDistributorClass * Class to register * @return True if class was registered */ public boolean registerIPDistributor( Class<? extends IPDistributor> ipDistributorClass) { // Check that vector constructor exists try { ipDistributorClass.getConstructor(new Class[] { Vector.class }); } catch (Exception e) { logger.fatal("No vector constructor found of IP distributor: " + ipDistributorClass); return false; } ipDistributorClasses.add(ipDistributorClass); return true; } /** * Unregister all IP distributors. */ public void unregisterIPDistributors() { ipDistributorClasses.clear(); } /** * @return All registered IP distributors */ public Vector<Class<? extends IPDistributor>> getRegisteredIPDistributors() { return ipDistributorClasses; } /** * Register new positioner class. * * @param positionerClass * Class to register * @return True if class was registered */ public boolean registerPositioner(Class<? extends Positioner> positionerClass) { // Check that interval constructor exists try { positionerClass .getConstructor(new Class[] { int.class, double.class, double.class, double.class, double.class, double.class, double.class }); } catch (Exception e) { logger.fatal("No interval constructor found of positioner: " + positionerClass); return false; } positionerClasses.add(positionerClass); return true; } /** * Unregister all positioner classes. */ public void unregisterPositioners() { positionerClasses.clear(); } /** * @return All registered positioner classes */ public Vector<Class<? extends Positioner>> getRegisteredPositioners() { return positionerClasses; } /** * Register new radio medium class. * * @param radioMediumClass * Class to register * @return True if class was registered */ public boolean registerRadioMedium( Class<? extends RadioMedium> radioMediumClass) { // Check that simulation constructor exists try { radioMediumClass.getConstructor(new Class[] { Simulation.class }); } catch (Exception e) { logger.fatal("No simulation constructor found of radio medium: " + radioMediumClass); return false; } radioMediumClasses.add(radioMediumClass); return true; } /** * Unregister all radio medium classes. */ public void unregisterRadioMediums() { radioMediumClasses.clear(); } /** * @return All registered radio medium classes */ public Vector<Class<? extends RadioMedium>> getRegisteredRadioMediums() { return radioMediumClasses; } /** * Builds new project configuration using current project directories settings. * Reregisters mote types, plugins, IP distributors, positioners and radio * mediums. This method may still return true even if all classes could not be * registered, but always returns false if all project directory configuration * files were not parsed correctly. * * Any registered temporary plugins will be saved and reregistered. * * @return True if external configuration files were found and parsed OK */ public void reparseProjectConfig() throws ParseProjectsException { // Backup temporary plugins Vector<Class<? extends Plugin>> oldTempPlugins = (Vector<Class<? extends Plugin>>) pluginClassesTemporary .clone(); // Reset current configuration unregisterMoteTypes(); unregisterPlugins(); unregisterIPDistributors(); unregisterPositioners(); unregisterRadioMediums(); try { // Read default configuration projectConfig = new ProjectConfig(true); } catch (FileNotFoundException e) { logger.fatal("Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Could not find default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } catch (IOException e) { logger.fatal("Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Error when reading default project config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } // Append project directory configurations for (File projectDir : currentProjectDirs) { try { // Append config to general config projectConfig.appendProjectDir(projectDir); } catch (FileNotFoundException e) { logger.fatal("Could not find project config file: " + projectDir); throw (ParseProjectsException) new ParseProjectsException( "Could not find project config file: " + projectDir).initCause(e); } catch (IOException e) { logger.fatal("Error when reading project config file: " + projectDir); throw (ParseProjectsException) new ParseProjectsException( "Error when reading project config file: " + projectDir).initCause(e); } } // Create class loader try { projectDirClassLoader = createClassLoader(currentProjectDirs); } catch (ClassLoaderCreationException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when creating class loader").initCause(e); } // Register mote types String[] moteTypeClassNames = projectConfig.getStringArrayValue(GUI.class, "MOTETYPES"); if (moteTypeClassNames != null) { for (String moteTypeClassName : moteTypeClassNames) { Class<? extends MoteType> moteTypeClass = tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass != null) { registerMoteType(moteTypeClass); // logger.info("Loaded mote type class: " + moteTypeClassName); } else { logger.warn("Could not load mote type class: " + moteTypeClassName); } } } // Register plugins registerPlugin(SimControl.class, false); // Not in menu registerPlugin(SimInformation.class, false); // Not in menu registerPlugin(MoteTypeInformation.class, false); // Not in menu String[] pluginClassNames = projectConfig.getStringArrayValue(GUI.class, "PLUGINS"); if (pluginClassNames != null) { for (String pluginClassName : pluginClassNames) { Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass != null) { registerPlugin(pluginClass); // logger.info("Loaded plugin class: " + pluginClassName); } else { logger.warn("Could not load plugin class: " + pluginClassName); } } } // Reregister temporary plugins again if (oldTempPlugins != null) { for (Class<? extends Plugin> pluginClass : oldTempPlugins) { if (registerTemporaryPlugin(pluginClass)) { // logger.info("Reregistered temporary plugin class: " + // getDescriptionOf(pluginClass)); } else { logger.warn("Could not reregister temporary plugin class: " + getDescriptionOf(pluginClass)); } } } // Register IP distributors String[] ipDistClassNames = projectConfig.getStringArrayValue(GUI.class, "IP_DISTRIBUTORS"); if (ipDistClassNames != null) { for (String ipDistClassName : ipDistClassNames) { Class<? extends IPDistributor> ipDistClass = tryLoadClass(this, IPDistributor.class, ipDistClassName); if (ipDistClass != null) { registerIPDistributor(ipDistClass); // logger.info("Loaded IP distributor class: " + ipDistClassName); } else { logger .warn("Could not load IP distributor class: " + ipDistClassName); } } } // Register positioners String[] positionerClassNames = projectConfig.getStringArrayValue( GUI.class, "POSITIONERS"); if (positionerClassNames != null) { for (String positionerClassName : positionerClassNames) { Class<? extends Positioner> positionerClass = tryLoadClass(this, Positioner.class, positionerClassName); if (positionerClass != null) { registerPositioner(positionerClass); // logger.info("Loaded positioner class: " + positionerClassName); } else { logger .warn("Could not load positioner class: " + positionerClassName); } } } // Register radio mediums String[] radioMediumsClassNames = projectConfig.getStringArrayValue( GUI.class, "RADIOMEDIUMS"); if (radioMediumsClassNames != null) { for (String radioMediumClassName : radioMediumsClassNames) { Class<? extends RadioMedium> radioMediumClass = tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { registerRadioMedium(radioMediumClass); // logger.info("Loaded radio medium class: " + radioMediumClassName); } else { logger.warn("Could not load radio medium class: " + radioMediumClassName); } } } } /** * Returns the current project configuration common to the entire simulator. * * @return Current project configuration */ public ProjectConfig getProjectConfig() { return projectConfig; } /** * Returns the current project directories common to the entire simulator. * * @return Current project directories. */ public Vector<File> getProjectDirs() { return currentProjectDirs; } // // PLUGIN METHODS //// /** * Show a started plugin in working area. * * @param plugin * Internal frame to add */ public void showPlugin(VisPlugin plugin) { int nrFrames = myDesktopPane.getAllFrames().length; myDesktopPane.add(plugin); // Set standard size if not specified by plugin itself if (plugin.getWidth() <= 0 || plugin.getHeight() <= 0) { plugin.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); } // Set location if not already visible if (!plugin.isVisible()) { plugin.setLocation((nrFrames + 1) * FRAME_NEW_OFFSET, (nrFrames + 1) * FRAME_NEW_OFFSET); plugin.setVisible(true); } // Deselect all other plugins before selecting the new one try { for (JInternalFrame existingPlugin : myDesktopPane.getAllFrames()) { existingPlugin.setSelected(false); } plugin.setSelected(true); } catch (Exception e) { // Ignore } // Mote plugin to front myDesktopPane.moveToFront(plugin); } /** * Remove a plugin from working area. * * @param plugin * Plugin to remove * @param askUser * If plugin is the last one, ask user if we should remove current * simulation also? */ public void removePlugin(Plugin plugin, boolean askUser) { // Clear any allocated resources and remove plugin plugin.closePlugin(); startedPlugins.remove(plugin); // Dispose plugin if it has visualizer if (plugin instanceof VisPlugin) { ((VisPlugin) plugin).dispose(); } if (getSimulation() != null && askUser && startedPlugins.isEmpty()) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } doRemoveSimulation(false); } } /** * Starts a plugin of given plugin class with given arguments. * * @param pluginClass * Plugin class * @param gui * GUI passed as argument to all plugins * @param simulation * Simulation passed as argument to mote and simulation plugins * @param mote * Mote passed as argument to mote plugins * @return Start plugin if any */ public Plugin startPlugin(Class<? extends Plugin> pluginClass, GUI gui, Simulation simulation, Mote mote) { // Check that plugin class is registered if (!pluginClasses.contains(pluginClass)) { logger.fatal("Plugin class not registered: " + pluginClass); return null; } // Check that visualizer plugin is not started without GUI if (!isVisualized()) { try { pluginClass.asSubclass(VisPlugin.class); // Cast succeded, plugin is visualizer plugin! logger.fatal("Can't start visualizer plugin (no GUI): " + pluginClass); return null; } catch (ClassCastException e) { } } // Construct plugin depending on plugin type Plugin newPlugin = null; int pluginType = pluginClass.getAnnotation(PluginType.class).value(); try { if (pluginType == PluginType.MOTE_PLUGIN) { if (mote == null) { logger.fatal("Can't start mote plugin (no mote selected)"); return null; } newPlugin = pluginClass.getConstructor( new Class[] { Mote.class, Simulation.class, GUI.class }) .newInstance(mote, simulation, gui); // Tag plugin with mote newPlugin.tagWithObject(mote); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { if (simulation == null) { logger.fatal("Can't start simulation plugin (no simulation)"); return null; } newPlugin = pluginClass.getConstructor( new Class[] { Simulation.class, GUI.class }).newInstance( simulation, gui); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { if (gui == null) { logger.fatal("Can't start COOJA plugin (no GUI)"); return null; } newPlugin = pluginClass.getConstructor(new Class[] { GUI.class }) .newInstance(gui); } } catch (Exception e) { logger.fatal("Exception thrown when starting plugin: " + e); e.printStackTrace(); return null; } if (newPlugin == null) { return null; } // Add to active plugins list startedPlugins.add(newPlugin); // Show plugin if visualizer type if (newPlugin instanceof VisPlugin) { myGUI.showPlugin((VisPlugin) newPlugin); } return newPlugin; } /** * Register a plugin to be included in the GUI. The plugin will be visible in * the menubar. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerPlugin(Class<? extends Plugin> newPluginClass) { return registerPlugin(newPluginClass, true); } /** * Register a temporary plugin to be included in the GUI. The plugin will be * visible in the menubar. This plugin will automatically be unregistered if * the current simulation is removed. * * @param newPluginClass * New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerTemporaryPlugin(Class<? extends Plugin> newPluginClass) { if (pluginClasses.contains(newPluginClass)) { return false; } boolean returnVal = registerPlugin(newPluginClass, true); if (!returnVal) { return false; } pluginClassesTemporary.add(newPluginClass); return true; } /** * Unregister a plugin class. Removes any plugin menu items links as well. * * @param pluginClass * Plugin class to unregister */ public void unregisterPlugin(Class<? extends Plugin> pluginClass) { // Remove (if existing) plugin class menu items for (Component menuComponent : menuPlugins.getMenuComponents()) { if (menuComponent.getClass().isAssignableFrom(JMenuItem.class)) { JMenuItem menuItem = (JMenuItem) menuComponent; if (menuItem.getClientProperty("class").equals(pluginClass)) { menuPlugins.remove(menuItem); } } } if (menuMotePluginClasses.contains(pluginClass)) { menuMotePluginClasses.remove(pluginClass); } // Remove from plugin vectors (including temporary) if (pluginClasses.contains(pluginClass)) { pluginClasses.remove(pluginClass); } if (pluginClassesTemporary.contains(pluginClass)) { pluginClassesTemporary.remove(pluginClass); } } /** * Register a plugin to be included in the GUI. * * @param newPluginClass * New plugin to register * @param addToMenu * Should this plugin be added to the dedicated plugins menubar? * @return True if this plugin was registered ok, false otherwise */ private boolean registerPlugin(Class<? extends Plugin> newPluginClass, boolean addToMenu) { // Get description annotation (if any) String description = getDescriptionOf(newPluginClass); // Get plugin type annotation (required) int pluginType; if (newPluginClass.isAnnotationPresent(PluginType.class)) { pluginType = newPluginClass.getAnnotation(PluginType.class).value(); } else { pluginType = PluginType.UNDEFINED_PLUGIN; } // Check that plugin type is valid and constructor exists try { if (pluginType == PluginType.MOTE_PLUGIN) { newPluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, GUI.class }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { newPluginClass .getConstructor(new Class[] { Simulation.class, GUI.class }); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { newPluginClass.getConstructor(new Class[] { GUI.class }); } else { logger.fatal("Could not find valid plugin type annotation in class " + newPluginClass); return false; } } catch (NoSuchMethodException e) { logger.fatal("Could not find valid constructor in class " + newPluginClass + ": " + e); return false; } if (addToMenu && menuPlugins != null) { // Create 'start plugin'-menu item JMenuItem menuItem = new JMenuItem(description); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", newPluginClass); menuItem.addActionListener(guiEventHandler); menuPlugins.add(menuItem); if (pluginType == PluginType.MOTE_PLUGIN) { // Disable previous menu item and add new item to mote plugins menu menuItem.setEnabled(false); menuItem.setToolTipText("Mote plugin"); menuMotePluginClasses.add(newPluginClass); } } pluginClasses.add(newPluginClass); return true; } /** * Unregister all plugin classes, including temporary plugins. */ public void unregisterPlugins() { if (menuPlugins != null) { menuPlugins.removeAll(); } if (menuMotePluginClasses != null) { menuMotePluginClasses.clear(); } pluginClasses.clear(); pluginClassesTemporary.clear(); } /** * Return a mote plugins submenu for given mote. * * @param mote Mote * @return Mote plugins menu */ public JMenu createMotePluginsSubmenu(Mote mote) { JMenu menuMotePlugins = new JMenu("Open mote plugin for " + mote); for (Class<? extends Plugin> motePluginClass: menuMotePluginClasses) { JMenuItem menuItem = new JMenuItem(getDescriptionOf(motePluginClass)); menuItem.setActionCommand("start plugin"); menuItem.putClientProperty("class", motePluginClass); menuItem.putClientProperty("mote", mote); menuItem.addActionListener(guiEventHandler); menuMotePlugins.add(menuItem); } return menuMotePlugins; } // // GUI CONTROL METHODS //// /** * @return Current simulation */ public Simulation getSimulation() { return mySimulation; } public void setSimulation(Simulation sim) { if (sim != null) { doRemoveSimulation(false); } mySimulation = sim; // Set frame title if (frame != null) { frame.setTitle("COOJA Simulator" + " - " + sim.getTitle()); } // Open standard plugins (if none opened already) if (startedPlugins.size() == 0) { for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.SIM_STANDARD_PLUGIN) { startPlugin(pluginClass, this, sim, null); } } } } /** * Creates a new mote type of the given mote type class. * * @param moteTypeClass * Mote type class */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass) { if (mySimulation == null) { logger.fatal("Can't create mote type (no simulation)"); return; } // Stop simulation (if running) mySimulation.stopSimulation(); // Create mote type MoteType newMoteType = null; boolean moteTypeOK = false; try { newMoteType = moteTypeClass.newInstance(); moteTypeOK = newMoteType.configureAndInit(frame, mySimulation, isVisualized()); } catch (InstantiationException e) { logger.fatal("Exception when creating mote type: " + e); return; } catch (IllegalAccessException e) { logger.fatal("Exception when creating mote type: " + e); return; } catch (MoteTypeCreationException e) { logger.fatal("Exception when creating mote type: " + e); return; } // Add mote type to simulation if (newMoteType != null && moteTypeOK) { mySimulation.addMoteType(newMoteType); } } /** * Remove current simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doRemoveSimulation(boolean askForConfirmation) { if (mySimulation != null) { if (askForConfirmation) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Close all started non-GUI plugins for (Object startedPlugin : startedPlugins.toArray()) { int pluginType = startedPlugin.getClass().getAnnotation( PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { removePlugin((Plugin) startedPlugin, false); } } // Delete simulation mySimulation.deleteObservers(); mySimulation.stopSimulation(); mySimulation = null; // Unregister temporary plugin classes Enumeration<Class<? extends Plugin>> pluginClasses = pluginClassesTemporary .elements(); while (pluginClasses.hasMoreElements()) { unregisterPlugin(pluginClasses.nextElement()); } // Reset frame title frame.setTitle("COOJA Simulator"); } } /** * Load a simulation configuration file from disk * * @param askForConfirmation Ask for confirmation before removing any current simulation * @param quick Quick-load simulation * @param configFile Configuration file to load, if null a dialog will appear */ public void doLoadConfig(boolean askForConfirmation, final boolean quick, File configFile) { if (CoreComm.hasLibraryBeenLoaded()) { JOptionPane .showMessageDialog( frame, "Shared libraries has already been loaded.\nYou need to restart the simulator!", "Can't load simulation", JOptionPane.ERROR_MESSAGE); return; } if (askForConfirmation && mySimulation != null) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } doRemoveSimulation(false); // Check already selected file, or select file using filechooser if (configFile != null) { if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file"); return; } } else { JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); // Suggest file using history Vector<File> history = getFileHistory(); if (history != null && history.size() > 0) { File suggestedFile = getFileHistory().firstElement(); fc.setSelectedFile(suggestedFile); } int returnVal = fc.showOpenDialog(frame); if (returnVal == JFileChooser.APPROVE_OPTION) { configFile = fc.getSelectedFile(); // Try adding extension if not founds if (!configFile.exists()) { configFile = new File(configFile.getParent(), configFile.getName() + SAVED_SIMULATIONS_FILES); } if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file"); return; } } else { logger.info("Load command cancelled by user..."); return; } } // Load simulation in separate thread, while showing progress monitor final JDialog progressDialog = new JDialog(frame, "Loading", true); final File fileToLoad = configFile; final Thread loadThread = new Thread(new Runnable() { public void run() { Simulation newSim = null; try { newSim = loadSimulationConfig(fileToLoad, quick); addToFileHistory(fileToLoad); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } catch (UnsatisfiedLinkError e) { showErrorDialog(frame, "Simulation load error", e, false); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } newSim = null; } catch (SimulationCreationException e) { showErrorDialog(frame, "Simulation load error", e, false); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } newSim = null; } if (newSim != null) { myGUI.setSimulation(newSim); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); JProgressBar progressBar; JButton button; progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread != null && loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.pack(); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); if (quick) { SwingUtilities.invokeLater(new Runnable() { public void run() { progressDialog.setVisible(true); } }); } } /** * Reloads current simulation. * This may include recompiling libraries and renaming mote type identifiers. */ private void reloadCurrentSimulation() { if (getSimulation() == null) { logger.fatal("No simulation to reload"); return; } final JDialog progressDialog = new JDialog(frame, "Reloading", true); final Thread loadThread = new Thread(new Runnable() { public void run() { // Create mappings to new mote type identifiers Properties moteTypeNames = new Properties(); for (MoteType moteType: getSimulation().getMoteTypes()) { if (moteType.getClass().equals(ContikiMoteType.class)) { // Suggest new identifier int counter = 0; String testIdentifier = ""; boolean identifierOK = false; while (!identifierOK) { counter++; testIdentifier = ContikiMoteTypeDialog.ID_PREFIX + counter; identifierOK = true; // Check if identifier already reserved for some other type if (moteTypeNames.containsValue(testIdentifier)) { identifierOK = false; } // Check if identifier is already used by some other type for (MoteType existingMoteType : getSimulation().getMoteTypes()) { if (existingMoteType != moteType && existingMoteType.getIdentifier().equals(testIdentifier)) { identifierOK = false; break; } } // Check if library file with given identifier has already been loaded if (identifierOK && CoreComm.hasLibraryFileBeenLoaded(new File( ContikiMoteType.tempOutputDirectory, testIdentifier + ContikiMoteType.librarySuffix))) { identifierOK = false; } } moteTypeNames.setProperty(moteType.getIdentifier(), testIdentifier); } } // Get current simulation configuration Element simulationElement = new Element("simulation"); simulationElement.addContent(getSimulation().getConfigXML()); Collection<Element> pluginsConfig = getPluginsConfigXML(); // Scan and replace old configuration mote type names Element root = new Element("simconf"); root.addContent(simulationElement); if (pluginsConfig != null) { root.addContent(pluginsConfig); } Document doc = new Document(root); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); String configXML = outputter.outputString(doc); Enumeration oldNames = moteTypeNames.keys(); while (oldNames.hasMoreElements()) { String oldName = (String) oldNames.nextElement(); configXML = configXML.replaceAll(">" + oldName + "<", ">" + moteTypeNames.get(oldName) + "<"); } // Reload altered simulation config boolean shouldRetry = false; do { try { shouldRetry = false; myGUI.doRemoveSimulation(false); Simulation newSim = loadSimulationConfig(new StringReader(configXML), true); myGUI.setSimulation(newSim); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); myGUI.doRemoveSimulation(false); } } while (shouldRetry); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); // Display progress dialog while reloading JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); JButton button = new JButton("Cancel"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread != null && loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.pack(); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); progressDialog.setVisible(true); } /** * Save current simulation configuration to disk * * @param askForConfirmation * Ask for confirmation before overwriting file */ public void doSaveConfig(boolean askForConfirmation) { if (mySimulation != null) { mySimulation.stopSimulation(); JFileChooser fc = new JFileChooser(); fc.setFileFilter(GUI.SAVED_SIMULATIONS_FILES); // Suggest file using history Vector<File> history = getFileHistory(); if (history != null && history.size() > 0) { File suggestedFile = getFileHistory().firstElement(); fc.setSelectedFile(suggestedFile); } int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = fc.getSelectedFile(); if (!fc.accept(saveFile)) { saveFile = new File(saveFile.getParent(), saveFile.getName() + SAVED_SIMULATIONS_FILES); } if (saveFile.exists()) { if (askForConfirmation) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane .showOptionDialog( frame, "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } } if (!saveFile.exists() || saveFile.canWrite()) { saveSimulationConfig(saveFile); addToFileHistory(saveFile); } else { logger.fatal("No write access to file"); } } else { logger.info("Save command cancelled by user..."); } } } /** * Add new mote to current simulation */ public void doAddMotes(MoteType moteType) { if (mySimulation != null) { mySimulation.stopSimulation(); Vector<Mote> newMotes = AddMoteDialog.showDialog(frame, mySimulation, moteType); if (newMotes != null) { for (Mote newMote : newMotes) { mySimulation.addMote(newMote); } } } else { logger.warn("No simulation active"); } } /** * Create a new simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doCreateSimulation(boolean askForConfirmation) { if (askForConfirmation && mySimulation != null) { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Create new simulation doRemoveSimulation(false); Simulation newSim = new Simulation(this); boolean createdOK = CreateSimDialog.showDialog(frame, newSim); if (createdOK) { myGUI.setSimulation(newSim); } } /** * Quit program * * @param askForConfirmation * Should we ask for confirmation before quitting? */ public void doQuit(boolean askForConfirmation) { if (askForConfirmation) { String s1 = "Quit"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(frame, "Sure you want to quit?", "Close COOJA Simulator", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return; } } // Clean up resources Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } // Restore last frame size and position if (frame != null) { setExternalToolsSetting("FRAME_POS_X", "" + frame.getLocationOnScreen().x); setExternalToolsSetting("FRAME_POS_Y", "" + frame.getLocationOnScreen().y); setExternalToolsSetting("FRAME_WIDTH", "" + frame.getWidth()); setExternalToolsSetting("FRAME_HEIGHT", "" + frame.getHeight()); saveExternalToolsUserSettings(); } System.exit(0); } // // EXTERNAL TOOLS SETTINGS METHODS //// /** * @return Number of external tools settings */ public static int getExternalToolsSettingsCount() { return externalToolsSettingNames.length; } /** * Get name of external tools setting at given index. * * @param index * Setting index * @return Name */ public static String getExternalToolsSettingName(int index) { return externalToolsSettingNames[index]; } /** * @param name * Name of setting * @return Value */ public static String getExternalToolsSetting(String name) { return currentExternalToolsSettings.getProperty(name); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsSetting(String name, String defaultValue) { return currentExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsDefaultSetting(String name, String defaultValue) { return defaultExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param newVal * New value */ public static void setExternalToolsSetting(String name, String newVal) { currentExternalToolsSettings.setProperty(name, newVal); } /** * Load external tools settings from default file. */ public static void loadExternalToolsDefaultSettings() { String osName = System.getProperty("os.name").toLowerCase(); String filename = GUI.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; if (osName.startsWith("win")) { filename = GUI.EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME; } else if (osName.startsWith("mac os x")) { filename = GUI.EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME; } logger.info("Loading external tools user settings from: " + filename); try { InputStream in = GUI.class.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " not found"); } Properties settings = new Properties(); settings.load(in); in.close(); currentExternalToolsSettings = settings; defaultExternalToolsSettings = (Properties) currentExternalToolsSettings.clone(); } catch (IOException e) { // Error while importing default properties logger.warn( "Error when reading external tools settings from " + filename, e); } finally { if (currentExternalToolsSettings == null) { defaultExternalToolsSettings = new Properties(); currentExternalToolsSettings = new Properties(); } } } /** * Load user values from external properties file */ public static void loadExternalToolsUserSettings() { try { FileInputStream in = new FileInputStream(externalToolsUserSettingsFile); Properties settings = new Properties(); settings.load(in); in.close(); Enumeration en = settings.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); setExternalToolsSetting(key, settings.getProperty(key)); } } catch (FileNotFoundException e) { // No default configuration file found, using default } catch (IOException e) { // Error while importing saved properties, using default logger.warn("Error when reading default settings from " + externalToolsUserSettingsFile); } } /** * Save external tools user settings to file. */ public static void saveExternalToolsUserSettings() { if (externalToolsUserSettingsFileReadOnly) { return; } try { FileOutputStream out = new FileOutputStream(externalToolsUserSettingsFile); Properties differingSettings = new Properties(); Enumeration keyEnum = currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = getExternalToolsDefaultSetting(key, ""); String currentSetting = getExternalToolsSetting(key, ""); if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "COOJA External Tools (User specific)"); out.close(); } catch (FileNotFoundException ex) { // Could not open settings file for writing, aborting logger.warn("Could not save external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } catch (IOException ex) { // Could not open settings file for writing, aborting logger.warn("Error while saving external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } } // // GUI EVENT HANDLER //// private class GUIEventHandler implements ActionListener, WindowListener { public void windowDeactivated(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { myGUI.doQuit(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("new sim")) { myGUI.doCreateSimulation(true); } else if (e.getActionCommand().equals("close sim")) { myGUI.doRemoveSimulation(true); } else if (e.getActionCommand().equals("confopen sim")) { myGUI.doLoadConfig(true, false, null); } else if (e.getActionCommand().equals("confopen last sim")) { File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); myGUI.doLoadConfig(true, false, file); } else if (e.getActionCommand().equals("open sim")) { myGUI.doLoadConfig(true, true, null); } else if (e.getActionCommand().equals("open last sim")) { File file = (File) ((JMenuItem) e.getSource()).getClientProperty("file"); myGUI.doLoadConfig(true, true, file); } else if (e.getActionCommand().equals("save sim")) { myGUI.doSaveConfig(true); } else if (e.getActionCommand().equals("quit")) { myGUI.doQuit(true); } else if (e.getActionCommand().equals("create mote type")) { myGUI.doCreateMoteType((Class<? extends MoteType>) ((JMenuItem) e .getSource()).getClientProperty("class")); } else if (e.getActionCommand().equals("add motes")) { myGUI.doAddMotes((MoteType) ((JMenuItem) e.getSource()) .getClientProperty("motetype")); } else if (e.getActionCommand().equals("edit paths")) { ExternalToolsDialog.showDialog(frame); } else if (e.getActionCommand().equals("close plugins")) { Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } } else if (e.getActionCommand().equals("remove all motes")) { if (getSimulation() != null) { if (getSimulation().isRunning()) { getSimulation().stopSimulation(); } while (getSimulation().getMotesCount() > 0) { getSimulation().removeMote(getSimulation().getMote(0)); } } } else if (e.getActionCommand().equals("manage projects")) { Vector<File> newProjects = ProjectDirectoriesDialog.showDialog(frame, currentProjectDirs, null); if (newProjects != null) { currentProjectDirs = newProjects; try { reparseProjectConfig(); } catch (ParseProjectsException e2) { logger.fatal("Error when loading projects: " + e2.getMessage()); e2.printStackTrace(); if (myGUI.isVisualized()) { JOptionPane.showMessageDialog(frame, "Error when loading projects.\nStack trace printed to console.", "Error", JOptionPane.ERROR_MESSAGE); } return; } } } else if (e.getActionCommand().equals("start plugin")) { Class<? extends VisPlugin> pluginClass = (Class<? extends VisPlugin>) ((JMenuItem) e .getSource()).getClientProperty("class"); Mote mote = (Mote) ((JMenuItem) e.getSource()).getClientProperty("mote"); startPlugin(pluginClass, myGUI, mySimulation, mote); } else { logger.warn("Unhandled action: " + e.getActionCommand()); } } } // // VARIOUS HELP METHODS //// /** * Help method that tries to load and initialize a class with given name. * * @param <N> * Class extending given class type * @param classType * Class type * @param className * Class name * @return Class extending given class type or null if not found */ public <N extends Object> Class<? extends N> tryLoadClass( Object callingObject, Class<N> classType, String className) { if (callingObject != null) { try { return callingObject.getClass().getClassLoader().loadClass(className) .asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } try { return Class.forName(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } try { if (projectDirClassLoader != null) { return projectDirClassLoader.loadClass(className).asSubclass( classType); } } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } return null; } public ClassLoader createProjectDirClassLoader(Vector<File> projectsDirs) throws ParseProjectsException, ClassLoaderCreationException { if (projectDirClassLoader == null) { reparseProjectConfig(); } return createClassLoader(projectDirClassLoader, projectsDirs); } private ClassLoader createClassLoader(Vector<File> currentProjectDirs) throws ClassLoaderCreationException { return createClassLoader(ClassLoader.getSystemClassLoader(), currentProjectDirs); } private File findJarFile(File projectDir, String jarfile) { File fp = new File(jarfile); if (!fp.exists()) { fp = new File(projectDir, jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/lib/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "lib/" + jarfile); } return fp.exists() ? fp : null; } private ClassLoader createClassLoader(ClassLoader parent, Vector<File> projectDirs) throws ClassLoaderCreationException { if (projectDirs == null || projectDirs.isEmpty()) { return parent; } // Combine class loader from all project directories (including any // specified JAR files) ArrayList<URL> urls = new ArrayList<URL>(); for (int j = projectDirs.size() - 1; j >= 0; j--) { File projectDir = projectDirs.get(j); try { urls.add((new File(projectDir, "java")).toURL()); // Read configuration to check if any JAR files should be loaded ProjectConfig projectConfig = new ProjectConfig(false); projectConfig.appendProjectDir(projectDir); String[] projectJarFiles = projectConfig.getStringArrayValue( GUI.class, "JARFILES"); if (projectJarFiles != null && projectJarFiles.length > 0) { for (String jarfile : projectJarFiles) { File jarpath = findJarFile(projectDir, jarfile); if (jarpath == null) { throw new FileNotFoundException(jarfile); } urls.add(jarpath.toURL()); } } } catch (Exception e) { logger.fatal("Error when trying to read JAR-file in " + projectDir + ": " + e); throw (ClassLoaderCreationException) new ClassLoaderCreationException( "Error when trying to read JAR-file in " + projectDir).initCause(e); } } return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent); } /** * Help method that returns the description for given object. This method * reads from the object's class annotations if existing. Otherwise it returns * the simple class name of object's class. * * @param object * Object * @return Description */ public static String getDescriptionOf(Object object) { return getDescriptionOf(object.getClass()); } /** * Help method that returns the description for given class. This method reads * from class annotations if existing. Otherwise it returns the simple class * name. * * @param clazz * Class * @return Description */ public static String getDescriptionOf(Class<? extends Object> clazz) { if (clazz.isAnnotationPresent(ClassDescription.class)) { return clazz.getAnnotation(ClassDescription.class).value(); } return clazz.getSimpleName(); } /** * Help method that returns the abstraction level description for given mote type class. * * @param clazz * Class * @return Description */ public static String getAbstractionLevelDescriptionOf(Class<? extends MoteType> clazz) { if (clazz.isAnnotationPresent(AbstractionLevelDescription.class)) { return clazz.getAnnotation(AbstractionLevelDescription.class).value(); } return null; } /** * Load configurations and create a GUI. * * @param args * null */ public static void main(String[] args) { // Configure logger if ((new File(LOG_CONFIG_FILE)).exists()) { DOMConfigurator.configure(LOG_CONFIG_FILE); } else { // Used when starting from jar DOMConfigurator.configure(GUI.class.getResource("/" + LOG_CONFIG_FILE)); } // Parse general command arguments for (String element : args) { if (element.startsWith("-contiki=")) { String arg = element.substring("-contiki=".length()); GUI.specifiedContikiPath = arg; } if (element.startsWith("-external_tools_config=")) { String arg = element.substring("-external_tools_config=".length()); File specifiedExternalToolsConfigFile = new File(arg); if (!specifiedExternalToolsConfigFile.exists()) { logger.fatal("Specified external tools configuration not found: " + specifiedExternalToolsConfigFile); specifiedExternalToolsConfigFile = null; System.exit(1); } else { GUI.externalToolsUserSettingsFile = specifiedExternalToolsConfigFile; GUI.externalToolsUserSettingsFileReadOnly = true; } } } // Check if simulator should be quick-started if (args.length > 0 && args[0].startsWith("-quickstart=")) { String filename = args[0].substring("-quickstart=".length()); String moteTypeID = "mtype1"; Vector<String> projectDirs = null; Vector<String> sensors = null; Vector<String> coreInterfaces = null; Vector<String> userProcesses = null; boolean addAutostartProcesses = true; int numberOfNodes = 100; double areaSideLength = 100; int delayTime = 5; boolean startSimulation = true; String contikiPath = null; // Parse arguments for (int i = 1; i < args.length; i++) { if (args[i].startsWith("-id=")) { moteTypeID = args[i].substring("-id=".length()); } else if (args[i].startsWith("-projects=")) { String arg = args[i].substring("-projects=".length()); String[] argArray = arg.split(","); projectDirs = new Vector<String>(); for (String argValue : argArray) { projectDirs.add(argValue); } } else if (args[i].startsWith("-sensors=")) { String arg = args[i].substring("-sensors=".length()); String[] argArray = arg.split(","); sensors = new Vector<String>(); for (String argValue : argArray) { sensors.add(argValue); } } else if (args[i].startsWith("-interfaces=")) { String arg = args[i].substring("-interfaces=".length()); String[] argArray = arg.split(","); coreInterfaces = new Vector<String>(); for (String argValue : argArray) { coreInterfaces.add(argValue); } } else if (args[i].startsWith("-processes=")) { String arg = args[i].substring("-processes=".length()); String[] argArray = arg.split(","); userProcesses = new Vector<String>(); for (String argValue : argArray) { userProcesses.add(argValue); } } else if (args[i].equals("-noautostartscan")) { addAutostartProcesses = false; } else if (args[i].equals("-paused")) { startSimulation = false; } else if (args[i].startsWith("-nodes=")) { String arg = args[i].substring("-nodes=".length()); numberOfNodes = Integer.parseInt(arg); } else if (args[i].startsWith("-contiki=")) { String arg = args[i].substring("-contiki=".length()); contikiPath = arg; } else if (args[i].startsWith("-delay=")) { String arg = args[i].substring("-delay=".length()); delayTime = Integer.parseInt(arg); } else if (args[i].startsWith("-side=")) { String arg = args[i].substring("-side=".length()); areaSideLength = Double.parseDouble(arg); } else { logger.fatal("Unknown argument, aborting: " + args[i]); System.exit(1); } } boolean ok = quickStartSimulation(moteTypeID, projectDirs, sensors, coreInterfaces, userProcesses, addAutostartProcesses, numberOfNodes, areaSideLength, delayTime, startSimulation, filename, contikiPath); if (!ok) { System.exit(1); } } else if (args.length > 0 && args[0].startsWith("-nogui")) { // No GUI start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = new JDesktopPane(); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); new GUI(desktop); } }); } else { // Regular start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = new JDesktopPane(); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); GUI gui = new GUI(desktop); configureFrame(gui, false); } }); } } /** * Loads a simulation configuration from given file. * * When loading Contiki mote types, the libraries must be recompiled. User may * change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public Simulation loadSimulationConfig(File file, boolean quick) throws UnsatisfiedLinkError, SimulationCreationException { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(file); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick); } catch (JDOMException e) { logger.fatal("Config not wellformed: " + e.getMessage()); return null; } catch (IOException e) { logger.fatal("IOException: " + e.getMessage()); return null; } } private Simulation loadSimulationConfig(StringReader stringReader, boolean quick) throws SimulationCreationException { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(stringReader); Element root = doc.getRootElement(); return loadSimulationConfig(root, quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "IO Exception: " + e.getMessage()).initCause(e); } } private Simulation loadSimulationConfig(Element root, boolean quick) throws SimulationCreationException { Simulation newSim = null; try { // Check that config file version is correct if (!root.getName().equals("simconf")) { logger.fatal("Not a valid COOJA simulation config!"); return null; } // Create new simulation from config for (Object element : root.getChildren()) { if (((Element) element).getName().equals("simulation")) { Collection<Element> config = ((Element) element).getChildren(); newSim = new Simulation(this); boolean createdOK = newSim.setConfigXML(config, !quick); if (!createdOK) { logger.info("Simulation not loaded"); return null; } } } // Restart plugins from config setPluginsConfigXML(root.getChildren(), newSim, !quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "No access to configuration file: " + e.getMessage()).initCause(e); } catch (MoteTypeCreationException e) { throw (SimulationCreationException) new SimulationCreationException( "Mote type creation error: " + e.getMessage()).initCause(e); } catch (Exception e) { throw (SimulationCreationException) new SimulationCreationException( "Unknown error: " + e.getMessage()).initCause(e); } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File, boolean) * @param file * File to write */ public void saveSimulationConfig(File file) { try { // Create simulation configL Element root = new Element("simconf"); Element simulationElement = new Element("simulation"); simulationElement.addContent(mySimulation.getConfigXML()); root.addContent(simulationElement); // Create started plugins config Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } // Create and write to document Document doc = new Document(root); FileOutputStream out = new FileOutputStream(file); XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); e.printStackTrace(); } } /** * Returns started plugins config. * * @return Config or null */ public Collection<Element> getPluginsConfigXML() { Vector<Element> config = new Vector<Element>(); // Loop through all started plugins // (Only return config of non-GUI plugins) Element pluginElement, pluginSubElement; for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class) .value(); // Ignore GUI plugins if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { continue; } pluginElement = new Element("plugin"); pluginElement.setText(startedPlugin.getClass().getName()); // Create mote argument config (if mote plugin) if (pluginType == PluginType.MOTE_PLUGIN && startedPlugin.getTag() != null) { pluginSubElement = new Element("mote_arg"); Mote taggedMote = (Mote) startedPlugin.getTag(); for (int moteNr = 0; moteNr < mySimulation.getMotesCount(); moteNr++) { if (mySimulation.getMote(moteNr) == taggedMote) { pluginSubElement.setText(Integer.toString(moteNr)); pluginElement.addContent(pluginSubElement); break; } } } // Create plugin specific configuration Collection pluginXML = startedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("plugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } // If plugin is visualizer plugin, create visualization arguments if (startedPlugin instanceof VisPlugin) { VisPlugin startedVisPlugin = (VisPlugin) startedPlugin; pluginSubElement = new Element("width"); pluginSubElement.setText("" + startedVisPlugin.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + getDesktopPane().getComponentZOrder(startedVisPlugin)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + startedVisPlugin.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + startedVisPlugin.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + startedVisPlugin.getLocation().y); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("minimized"); pluginSubElement.setText(new Boolean(startedVisPlugin.isIcon()) .toString()); pluginElement.addContent(pluginSubElement); } config.add(pluginElement); } return config; } /** * Starts plugins with arguments in given config. * * @param configXML * Config XML elements * @param simulation * Simulation on which to start plugins * @return True if all plugins started, false otherwise */ public boolean setPluginsConfigXML(Collection<Element> configXML, Simulation simulation, boolean visAvailable) { for (Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("plugin")) { // Read plugin class String pluginClassName = pluginElement.getText().trim(); Class<? extends Plugin> visPluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (visPluginClass == null) { logger.fatal("Could not load plugin class: " + pluginClassName); return false; } // Parse plugin mote argument (if any) Mote mote = null; for (Element pluginSubElement : (List<Element>) pluginElement .getChildren()) { if (pluginSubElement.getName().equals("mote_arg")) { int moteNr = Integer.parseInt(pluginSubElement.getText()); if (moteNr >= 0 && moteNr < simulation.getMotesCount()) { mote = simulation.getMote(moteNr); } } } // Start plugin (before applying rest of config) Plugin startedPlugin = startPlugin(visPluginClass, this, simulation, mote); // Apply plugin specific configuration for (Element pluginSubElement : (List<Element>) pluginElement .getChildren()) { if (pluginSubElement.getName().equals("plugin_config")) { startedPlugin.setConfigXML(pluginSubElement.getChildren(), visAvailable); } } // If plugin is visualizer plugin, parse visualization arguments if (startedPlugin instanceof VisPlugin) { Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); VisPlugin startedVisPlugin = (VisPlugin) startedPlugin; for (Element pluginSubElement : (List<Element>) pluginElement .getChildren()) { if (pluginSubElement.getName().equals("width") && size != null) { size.width = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); // Save z order as temporary client property startedVisPlugin.putClientProperty("zorder", zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); startedVisPlugin.setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { try { startedVisPlugin.setIcon(Boolean.parseBoolean(pluginSubElement .getText())); } catch (PropertyVetoException e) { // Ignoring } } } } } } // For all started visplugins, check if they have a zorder property try { for (JInternalFrame plugin : getDesktopPane().getAllFrames()) { if (plugin.getClientProperty("zorder") != null) { getDesktopPane().setComponentZOrder(plugin, ((Integer) plugin.getClientProperty("zorder")).intValue()); plugin.putClientProperty("zorder", null); } } } catch (Exception e) { // Ignore errors } return true; } public class ParseProjectsException extends Exception { public ParseProjectsException(String message) { super(message); } } public class ClassLoaderCreationException extends Exception { public ClassLoaderCreationException(String message) { super(message); } } public class SimulationCreationException extends Exception { public SimulationCreationException(String message) { super(message); } } /** * Shows a simple dialog with information about the thrown exception. A user * may watch the stack trace and, if the exception is a * MoteTypeCreationException, watch compilation output. * * @param parentComponent * Parent component * @param title * Title of error window * @param exception * Exception causing window to be shown * @param retryAvailable * If true, a retry option is available */ public static boolean showErrorDialog(Component parentComponent, final String title, Throwable exception, boolean retryAvailable) { MessageList compilationOutput = null; MessageList stackTrace = null; String message = title; // Create message if (exception != null) { message = exception.getMessage(); } // Create stack trace message list if (exception != null) { stackTrace = new MessageList(); PrintStream printStream = stackTrace.getInputStream(MessageList.NORMAL); exception.printStackTrace(printStream); } // Create compilation out message list (if available) if (exception != null && exception instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception) .getCompilationOutput(); } else if (exception != null && exception.getCause() != null && exception.getCause() instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception.getCause()) .hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception.getCause()) .getCompilationOutput(); } // Create error dialog final JDialog errorDialog; if (parentComponent instanceof Dialog) { errorDialog = new JDialog((Dialog) parentComponent, title, true); } else if (parentComponent instanceof Frame) { errorDialog = new JDialog((Frame) parentComponent, title, true); } else { logger.fatal("Bad parent for error dialog"); errorDialog = new JDialog((Frame) null, title + " (Java stack trace)"); } final JPanel errorPanel = new JPanel(); errorPanel.setLayout(new BoxLayout(errorPanel, BoxLayout.Y_AXIS)); errorPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Box messageBox = Box.createHorizontalBox(); // Icon myIcon = (Icon)DefaultLookup.get(errorPanel, null, // "OptionPane.errorIcon"); // messageBox.add(new JLabel(myIcon)); messageBox.add(Box.createHorizontalGlue()); messageBox.add(new JLabel(message)); messageBox.add(Box.createHorizontalGlue()); Box buttonBox = Box.createHorizontalBox(); if (compilationOutput != null) { final MessageList listToDisplay = compilationOutput; final String titleToDisplay = title + " (Compilation output)"; JButton showCompilationButton = new JButton("Show compilation output"); showCompilationButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JDialog messageListDialog = new JDialog(errorDialog, titleToDisplay); JPanel messageListPanel = new JPanel(new BorderLayout()); messageListPanel.add(BorderLayout.CENTER, new JScrollPane( listToDisplay)); messageListPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); messageListPanel.setVisible(true); messageListDialog.getContentPane().add(messageListPanel); messageListDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); messageListDialog.pack(); messageListDialog.setLocationRelativeTo(errorDialog); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); if (maxSize != null && (messageListDialog.getSize().getWidth() > maxSize.getWidth() || messageListDialog .getSize().getHeight() > maxSize.getHeight())) { Dimension newSize = new Dimension(); newSize.height = Math.min((int) maxSize.getHeight(), (int) messageListDialog.getSize().getHeight()); newSize.width = Math.min((int) maxSize.getWidth(), (int) messageListDialog.getSize().getWidth()); messageListDialog.setSize(newSize); } messageListDialog.setVisible(true); } }); buttonBox.add(showCompilationButton); } if (stackTrace != null) { final MessageList listToDisplay = stackTrace; final String titleToDisplay = title + " (Java stack trace)"; JButton showTraceButton = new JButton("Show Java stack trace"); showTraceButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JDialog messageListDialog = new JDialog(errorDialog, titleToDisplay); JPanel messageListPanel = new JPanel(new BorderLayout()); messageListPanel.add(BorderLayout.CENTER, new JScrollPane( listToDisplay)); messageListPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); messageListPanel.setVisible(true); messageListDialog.getContentPane().add(messageListPanel); messageListDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); messageListDialog.pack(); messageListDialog.setLocationRelativeTo(errorDialog); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds(); if (maxSize != null && (messageListDialog.getSize().getWidth() > maxSize.getWidth() || messageListDialog .getSize().getHeight() > maxSize.getHeight())) { Dimension newSize = new Dimension(); newSize.height = Math.min((int) maxSize.getHeight(), (int) messageListDialog.getSize().getHeight()); newSize.width = Math.min((int) maxSize.getWidth(), (int) messageListDialog.getSize().getWidth()); messageListDialog.setSize(newSize); } messageListDialog.setVisible(true); } }); buttonBox.add(showTraceButton); } if (retryAvailable) { JButton retryButton = new JButton("Retry"); retryButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { errorDialog.dispose(); errorDialog.setTitle("-RETRY-"); } }); buttonBox.add(retryButton); } final JButton closeButton = new JButton("Close"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { errorDialog.dispose(); } }); buttonBox.add(closeButton); // Dispose on escape key InputMap inputMap = errorDialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "dispose"); AbstractAction cancelAction = new AbstractAction(){ public void actionPerformed(ActionEvent e) { closeButton.doClick(); } }; errorDialog.getRootPane().getActionMap().put("dispose", cancelAction); errorPanel.add(messageBox); errorPanel.add(Box.createVerticalStrut(20)); errorPanel.add(buttonBox); errorDialog.getContentPane().add(errorPanel); errorDialog.pack(); errorDialog.setLocationRelativeTo(parentComponent); errorDialog.setVisible(true); if (errorDialog.getTitle().equals("-RETRY-")) { return true; } return false; } /** * This method can be used by various different modules in the simulator to * indicate for example that a mote has been selected. All mote highlight * listeners will be notified. An example application of mote highlightinh is * a simulator visualizer that highlights the mote. * * @see #addMoteHighligtObserver(Observer) * @param m * Mote to highlight */ public void signalMoteHighlight(Mote m) { moteHighlightObservable.highlightMote(m); } }
updated deprecated code
tools/cooja/java/se/sics/cooja/GUI.java
updated deprecated code
<ide><path>ools/cooja/java/se/sics/cooja/GUI.java <ide> * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS <ide> * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <ide> * <del> * $Id: GUI.java,v 1.66 2008/02/07 10:30:19 fros4943 Exp $ <add> * $Id: GUI.java,v 1.67 2008/02/07 22:25:26 fros4943 Exp $ <ide> */ <ide> <ide> package se.sics.cooja; <ide> for (int j = projectDirs.size() - 1; j >= 0; j--) { <ide> File projectDir = projectDirs.get(j); <ide> try { <del> urls.add((new File(projectDir, "java")).toURL()); <add> urls.add((new File(projectDir, "java")).toURI().toURL()); <ide> <ide> // Read configuration to check if any JAR files should be loaded <ide> ProjectConfig projectConfig = new ProjectConfig(false); <ide> if (jarpath == null) { <ide> throw new FileNotFoundException(jarfile); <ide> } <del> urls.add(jarpath.toURL()); <add> urls.add(jarpath.toURI().toURL()); <ide> } <ide> } <ide> <ide> } <ide> } <ide> <del> return new URLClassLoader(urls.toArray(new URL[urls.size()]), <del> parent); <add> URL[] urlsArray = urls.toArray(new URL[urls.size()]); <add> return new URLClassLoader(urlsArray, parent); <ide> } <ide> <ide> /**
Java
bsd-3-clause
0572c3b037a48474d4699ef506ad75b31cf66e7f
0
jdgarrett/geogig,mtCarto/geogig,jodygarnett/GeoGig,mtCarto/geogig,jdgarrett/geogig,jodygarnett/GeoGig,jdgarrett/geogig,mtCarto/geogig,jodygarnett/GeoGig
/* Copyright (c) 2016 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Gabriel Roldan (Boundless) - initial implementation */ package org.locationtech.geogig.rocksdb; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.jdt.annotation.Nullable; import org.locationtech.geogig.model.ObjectId; import org.locationtech.geogig.model.RevObject; import org.locationtech.geogig.plumbing.ResolveGeogigURI; import org.locationtech.geogig.repository.Hints; import org.locationtech.geogig.repository.Platform; import org.locationtech.geogig.storage.AbstractObjectStore; import org.locationtech.geogig.storage.BulkOpListener; import org.locationtech.geogig.storage.ObjectStore; import org.locationtech.geogig.storage.datastream.DataStreamSerializationFactoryV2; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.inject.Inject; public class RocksdbObjectStore extends AbstractObjectStore implements ObjectStore { private volatile boolean open; protected final String path; protected final boolean readOnly; private DBHandle dbhandle; private RocksDB db; @Inject public RocksdbObjectStore(Platform platform, @Nullable Hints hints) { super(DataStreamSerializationFactoryV2.INSTANCE); Optional<URI> repoUriOpt = new ResolveGeogigURI(platform, hints).call(); checkArgument(repoUriOpt.isPresent(), "couldn't resolve geogig directory"); URI uri = repoUriOpt.get(); checkArgument("file".equals(uri.getScheme())); this.path = new File(new File(uri), "objects.rocksdb").getAbsolutePath(); this.readOnly = hints == null ? false : hints.getBoolean(Hints.OBJECTS_READ_ONLY); } @Override public synchronized void open() { if (isOpen()) { return; } DBOptions address = new DBOptions(path, readOnly); this.dbhandle = RocksConnectionManager.INSTANCE.acquire(address); this.db = dbhandle.db; open = true; } @Override public synchronized void close() { if (!open) { return; } open = false; final DBHandle dbhandle = this.dbhandle; this.db = null; this.dbhandle = null; RocksConnectionManager.INSTANCE.release(dbhandle); } @Override public boolean isOpen() { return open; } private void checkOpen() { Preconditions.checkState(isOpen(), "Database is closed"); } public void checkWritable() { checkOpen(); if (readOnly) { throw new IllegalStateException("db is read only."); } } @Override protected boolean putInternal(ObjectId id, byte[] rawData) { checkWritable(); byte[] key = id.getRawValue(); boolean exists; try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false); ro.setVerifyChecksums(false); exists = exists(ro, key); } if (!exists) { try { db.put(key, rawData); } catch (RocksDBException e) { throw Throwables.propagate(e); } } return !exists; } @Override protected InputStream getRawInternal(ObjectId id, boolean failIfNotFound) throws IllegalArgumentException { byte[] bytes = getRawInternal(id.getRawValue(), null, null); if (bytes != null) { return new ByteArrayInputStream(bytes); } if (failIfNotFound) { throw new IllegalArgumentException("object does not exist: " + id); } return null; } @Nullable private byte[] getRawInternal(byte[] key, @Nullable byte[] outBuff, @Nullable AtomicInteger outSize) throws IllegalArgumentException { try { if (outBuff == null) { outBuff = db.get(key); } else { final int size = db.get(key, outBuff); if (size == RocksDB.NOT_FOUND) { outBuff = null; } else if (size > outBuff.length) { int newBuffSize = 1024 * (1 + (size / 1024)); outBuff = new byte[newBuffSize]; db.get(key, outBuff); } if (outSize != null) { outSize.set(size); } } } catch (RocksDBException e) { throw Throwables.propagate(e); } return outBuff; } @Override public boolean exists(ObjectId id) { checkOpen(); checkNotNull(id, "argument id is null"); try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false).setVerifyChecksums(false); return exists(ro, id.getRawValue()); } } private static final byte[] NO_DATA = new byte[0]; private boolean exists(ReadOptions readOptions, byte[] key) { int size = RocksDB.NOT_FOUND; if (db.keyMayExist(key, new StringBuffer())) { try { size = db.get(key, NO_DATA); } catch (RocksDBException e) { throw Throwables.propagate(e); } } return size != RocksDB.NOT_FOUND; } @Override public void delete(ObjectId objectId) { checkNotNull(objectId, "argument objectId is null"); checkWritable(); byte[] key = objectId.getRawValue(); try { db.remove(key); } catch (RocksDBException e) { throw Throwables.propagate(e); } } @Override public Iterator<RevObject> getAll(final Iterable<ObjectId> ids, final BulkOpListener listener) { return getAll(ids, listener, RevObject.class); } private static class BatchGet implements Function<List<ObjectId>, Iterator<RevObject>> { private final RocksdbObjectStore store; private final BulkOpListener listener; private final Predicate<Object> filter; public BatchGet(RocksdbObjectStore store, BulkOpListener listener, final Class<?> filter) { this.store = store; this.listener = listener; this.filter = RevObject.class.equals(filter) ? Predicates.alwaysTrue() : Predicates.instanceOf(filter); } @Override public Iterator<RevObject> apply(List<ObjectId> input) { store.checkOpen(); SortedSet<ObjectId> sortedIds = new TreeSet<>(input); List<RevObject> objects = new ArrayList<>(input.size()); try (ReadOptions ops = new ReadOptions()) { ops.setFillCache(false);// better for bulk ops ops.setVerifyChecksums(false); byte[] keybuff = new byte[ObjectId.NUM_BYTES]; try (RocksIterator rocksit = store.db.newIterator(ops)) { for (ObjectId id : sortedIds) { RevObject object = null; id.getRawValue(keybuff); rocksit.seek(keybuff); if (rocksit.isValid()) { byte[] currentKey = rocksit.key(); if (Arrays.equals(keybuff, currentKey)) { byte[] value = rocksit.value(); try { object = store.serializer.read(id, new ByteArrayInputStream(value)); if (filter.apply(object)) { objects.add(object); listener.found(id, Integer.valueOf(value.length)); continue; } } catch (IOException e) { throw Throwables.propagate(e); } } } listener.notFound(id); } } } return objects.iterator(); } } @SuppressWarnings("unchecked") @Override public <T extends RevObject> Iterator<T> getAll(final Iterable<ObjectId> ids, final BulkOpListener listener, final Class<T> type) { checkNotNull(ids, "ids is null"); checkNotNull(listener, "listener is null"); checkNotNull(type, "type is null"); checkOpen(); final int partitionSize = 500; Iterator<List<ObjectId>> partitions = Iterables.partition(ids, partitionSize).iterator(); Iterator<Iterator<RevObject>> objects = Iterators.transform(partitions, new BatchGet(this, listener, type)); Iterator<RevObject> iterator = Iterators.concat(objects); return (Iterator<T>) iterator; } @Override public void deleteAll(Iterator<ObjectId> ids, BulkOpListener listener) { checkNotNull(ids, "argument objectId is null"); checkNotNull(listener, "argument listener is null"); checkWritable(); final boolean checkExists = !BulkOpListener.NOOP_LISTENER.equals(listener); byte[] keybuff = new byte[ObjectId.NUM_BYTES]; try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false); ro.setVerifyChecksums(false); try (WriteOptions writeOps = new WriteOptions()) { writeOps.setSync(false); while (ids.hasNext()) { ObjectId id = ids.next(); id.getRawValue(keybuff); if (!checkExists || exists(ro, keybuff)) { try { db.remove(writeOps, keybuff); } catch (RocksDBException e) { throw Throwables.propagate(e); } listener.deleted(id); } else { listener.notFound(id); } } writeOps.sync(); } } } @Override protected List<ObjectId> lookUpInternal(byte[] idprefix) { List<ObjectId> matches = new ArrayList<>(2); try (RocksIterator it = db.newIterator()) { it.seek(idprefix); while (it.isValid()) { byte[] key = it.key(); for (int i = 0; i < idprefix.length; i++) { if (idprefix[i] != key[i]) { break; } } ObjectId id = ObjectId.createNoClone(key); matches.add(id); it.next(); } } return matches; } @Override public void putAll(Iterator<? extends RevObject> objects, final BulkOpListener listener) { checkNotNull(objects, "objects is null"); checkNotNull(listener, "listener is null"); checkWritable(); final boolean checkExists = !BulkOpListener.NOOP_LISTENER.equals(listener); ByteArrayOutputStream rawOut = new ByteArrayOutputStream(4096); byte[] keybuff = new byte[ObjectId.NUM_BYTES]; try (WriteOptions wo = new WriteOptions()) { wo.setDisableWAL(true); wo.setSync(false); try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false); ro.setVerifyChecksums(false); while (objects.hasNext()) { Iterator<? extends RevObject> partition = Iterators.limit(objects, 10_000); try (WriteBatch batch = new WriteBatch()) { while (partition.hasNext()) { RevObject object = partition.next(); rawOut.reset(); writeObject(object, rawOut); object.getId().getRawValue(keybuff); final byte[] value = rawOut.toByteArray(); boolean exists = checkExists ? exists(ro, keybuff) : false; if (exists) { listener.found(object.getId(), null); } else { batch.put(keybuff, value); listener.inserted(object.getId(), Integer.valueOf(value.length)); } } // Stopwatch sw = Stopwatch.createStarted(); db.write(wo, batch); // System.err.printf("--- synced writes in %s\n", sw.stop()); } } } wo.sync(); } catch (RocksDBException e) { throw Throwables.propagate(e); } } }
src/storage/rocksdb/src/main/java/org/locationtech/geogig/rocksdb/RocksdbObjectStore.java
/* Copyright (c) 2016 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Gabriel Roldan (Boundless) - initial implementation */ package org.locationtech.geogig.rocksdb; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import org.eclipse.jdt.annotation.Nullable; import org.locationtech.geogig.model.ObjectId; import org.locationtech.geogig.model.RevObject; import org.locationtech.geogig.plumbing.ResolveGeogigURI; import org.locationtech.geogig.repository.Hints; import org.locationtech.geogig.repository.Platform; import org.locationtech.geogig.storage.AbstractObjectStore; import org.locationtech.geogig.storage.BulkOpListener; import org.locationtech.geogig.storage.ObjectStore; import org.locationtech.geogig.storage.datastream.DataStreamSerializationFactoryV2; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.inject.Inject; public class RocksdbObjectStore extends AbstractObjectStore implements ObjectStore { private volatile boolean open; protected final String path; protected final boolean readOnly; private DBHandle dbhandle; private RocksDB db; @Inject public RocksdbObjectStore(Platform platform, @Nullable Hints hints) { super(DataStreamSerializationFactoryV2.INSTANCE); Optional<URI> repoUriOpt = new ResolveGeogigURI(platform, hints).call(); checkArgument(repoUriOpt.isPresent(), "couldn't resolve geogig directory"); URI uri = repoUriOpt.get(); checkArgument("file".equals(uri.getScheme())); this.path = new File(new File(uri), "objects.rocksdb").getAbsolutePath(); this.readOnly = hints == null ? false : hints.getBoolean(Hints.OBJECTS_READ_ONLY); } @Override public synchronized void open() { if (isOpen()) { return; } DBOptions address = new DBOptions(path, readOnly); this.dbhandle = RocksConnectionManager.INSTANCE.acquire(address); this.db = dbhandle.db; open = true; } @Override public synchronized void close() { if (!open) { return; } open = false; final DBHandle dbhandle = this.dbhandle; this.db = null; this.dbhandle = null; RocksConnectionManager.INSTANCE.release(dbhandle); } @Override public boolean isOpen() { return open; } private void checkOpen() { Preconditions.checkState(isOpen(), "Database is closed"); } public void checkWritable() { checkOpen(); if (readOnly) { throw new IllegalStateException("db is read only."); } } @Override protected boolean putInternal(ObjectId id, byte[] rawData) { checkWritable(); byte[] key = id.getRawValue(); boolean exists; try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false); ro.setVerifyChecksums(false); exists = exists(ro, key); } if (!exists) { try { db.put(key, rawData); } catch (RocksDBException e) { throw Throwables.propagate(e); } } return !exists; } @Override protected InputStream getRawInternal(ObjectId id, boolean failIfNotFound) throws IllegalArgumentException { byte[] bytes = getRawInternal(id.getRawValue(), null, null); if (bytes != null) { return new ByteArrayInputStream(bytes); } if (failIfNotFound) { throw new IllegalArgumentException("object does not exist: " + id); } return null; } @Nullable private byte[] getRawInternal(byte[] key, @Nullable byte[] outBuff, @Nullable AtomicInteger outSize) throws IllegalArgumentException { try { if (outBuff == null) { outBuff = db.get(key); } else { final int size = db.get(key, outBuff); if (size == RocksDB.NOT_FOUND) { outBuff = null; } else if (size > outBuff.length) { int newBuffSize = 1024 * (1 + (size / 1024)); outBuff = new byte[newBuffSize]; db.get(key, outBuff); } if (outSize != null) { outSize.set(size); } } } catch (RocksDBException e) { throw Throwables.propagate(e); } return outBuff; } @Override public boolean exists(ObjectId id) { checkOpen(); checkNotNull(id, "argument id is null"); try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false).setVerifyChecksums(false); return exists(ro, id.getRawValue()); } } private static final byte[] NO_DATA = new byte[0]; private static final StringBuffer existsBuff = new StringBuffer(); private boolean exists(ReadOptions readOptions, byte[] key) { int size = RocksDB.NOT_FOUND; existsBuff.setLength(0); if (db.keyMayExist(key, existsBuff)) { try { size = db.get(key, NO_DATA); } catch (RocksDBException e) { throw Throwables.propagate(e); } } return size != RocksDB.NOT_FOUND; } @Override public void delete(ObjectId objectId) { checkNotNull(objectId, "argument objectId is null"); checkWritable(); byte[] key = objectId.getRawValue(); try { db.remove(key); } catch (RocksDBException e) { throw Throwables.propagate(e); } } @Override public Iterator<RevObject> getAll(final Iterable<ObjectId> ids, final BulkOpListener listener) { return getAll(ids, listener, RevObject.class); } private static class BatchGet implements Function<List<ObjectId>, Iterator<RevObject>> { private final RocksdbObjectStore store; private final BulkOpListener listener; private final Predicate<Object> filter; public BatchGet(RocksdbObjectStore store, BulkOpListener listener, final Class<?> filter) { this.store = store; this.listener = listener; this.filter = RevObject.class.equals(filter) ? Predicates.alwaysTrue() : Predicates.instanceOf(filter); } @Override public Iterator<RevObject> apply(List<ObjectId> input) { store.checkOpen(); SortedSet<ObjectId> sortedIds = new TreeSet<>(input); List<RevObject> objects = new ArrayList<>(input.size()); try (ReadOptions ops = new ReadOptions()) { ops.setFillCache(false);// better for bulk ops ops.setVerifyChecksums(false); byte[] keybuff = new byte[ObjectId.NUM_BYTES]; try (RocksIterator rocksit = store.db.newIterator(ops)) { for (ObjectId id : sortedIds) { RevObject object = null; id.getRawValue(keybuff); rocksit.seek(keybuff); if (rocksit.isValid()) { byte[] currentKey = rocksit.key(); if (Arrays.equals(keybuff, currentKey)) { byte[] value = rocksit.value(); try { object = store.serializer.read(id, new ByteArrayInputStream(value)); if (filter.apply(object)) { objects.add(object); listener.found(id, Integer.valueOf(value.length)); continue; } } catch (IOException e) { throw Throwables.propagate(e); } } } listener.notFound(id); } } } return objects.iterator(); } } @SuppressWarnings("unchecked") @Override public <T extends RevObject> Iterator<T> getAll(final Iterable<ObjectId> ids, final BulkOpListener listener, final Class<T> type) { checkNotNull(ids, "ids is null"); checkNotNull(listener, "listener is null"); checkNotNull(type, "type is null"); checkOpen(); final int partitionSize = 500; Iterator<List<ObjectId>> partitions = Iterables.partition(ids, partitionSize).iterator(); Iterator<Iterator<RevObject>> objects = Iterators.transform(partitions, new BatchGet(this, listener, type)); Iterator<RevObject> iterator = Iterators.concat(objects); return (Iterator<T>) iterator; } @Override public void deleteAll(Iterator<ObjectId> ids, BulkOpListener listener) { checkNotNull(ids, "argument objectId is null"); checkNotNull(listener, "argument listener is null"); checkWritable(); final boolean checkExists = !BulkOpListener.NOOP_LISTENER.equals(listener); byte[] keybuff = new byte[ObjectId.NUM_BYTES]; try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false); ro.setVerifyChecksums(false); try (WriteOptions writeOps = new WriteOptions()) { writeOps.setSync(false); while (ids.hasNext()) { ObjectId id = ids.next(); id.getRawValue(keybuff); if (!checkExists || exists(ro, keybuff)) { try { db.remove(writeOps, keybuff); } catch (RocksDBException e) { throw Throwables.propagate(e); } listener.deleted(id); } else { listener.notFound(id); } } writeOps.sync(); } } } @Override protected List<ObjectId> lookUpInternal(byte[] idprefix) { List<ObjectId> matches = new ArrayList<>(2); try (RocksIterator it = db.newIterator()) { it.seek(idprefix); while (it.isValid()) { byte[] key = it.key(); for (int i = 0; i < idprefix.length; i++) { if (idprefix[i] != key[i]) { break; } } ObjectId id = ObjectId.createNoClone(key); matches.add(id); it.next(); } } return matches; } @Override public void putAll(Iterator<? extends RevObject> objects, final BulkOpListener listener) { checkNotNull(objects, "objects is null"); checkNotNull(listener, "listener is null"); checkWritable(); final boolean checkExists = !BulkOpListener.NOOP_LISTENER.equals(listener); ByteArrayOutputStream rawOut = new ByteArrayOutputStream(4096); byte[] keybuff = new byte[ObjectId.NUM_BYTES]; try (WriteOptions wo = new WriteOptions()) { wo.setDisableWAL(true); wo.setSync(false); try (ReadOptions ro = new ReadOptions()) { ro.setFillCache(false); ro.setVerifyChecksums(false); while (objects.hasNext()) { Iterator<? extends RevObject> partition = Iterators.limit(objects, 10_000); try (WriteBatch batch = new WriteBatch()) { while (partition.hasNext()) { RevObject object = partition.next(); rawOut.reset(); writeObject(object, rawOut); object.getId().getRawValue(keybuff); final byte[] value = rawOut.toByteArray(); boolean exists = checkExists ? exists(ro, keybuff) : false; if (exists) { listener.found(object.getId(), null); } else { batch.put(keybuff, value); listener.inserted(object.getId(), Integer.valueOf(value.length)); } } // Stopwatch sw = Stopwatch.createStarted(); db.write(wo, batch); // System.err.printf("--- synced writes in %s\n", sw.stop()); } } } wo.sync(); } catch (RocksDBException e) { throw Throwables.propagate(e); } } }
Avoid thread contention in RocksdbObjectStore.exists() Signed-off-by: Gabriel Roldan <[email protected]>
src/storage/rocksdb/src/main/java/org/locationtech/geogig/rocksdb/RocksdbObjectStore.java
Avoid thread contention in RocksdbObjectStore.exists()
<ide><path>rc/storage/rocksdb/src/main/java/org/locationtech/geogig/rocksdb/RocksdbObjectStore.java <ide> <ide> private static final byte[] NO_DATA = new byte[0]; <ide> <del> private static final StringBuffer existsBuff = new StringBuffer(); <del> <ide> private boolean exists(ReadOptions readOptions, byte[] key) { <ide> int size = RocksDB.NOT_FOUND; <del> existsBuff.setLength(0); <del> if (db.keyMayExist(key, existsBuff)) { <add> if (db.keyMayExist(key, new StringBuffer())) { <ide> try { <ide> size = db.get(key, NO_DATA); <ide> } catch (RocksDBException e) {
Java
mit
77b1da44f31a52c7d827c71130f0535f49a54f1e
0
ghiringh/Wegas,ghiringh/Wegas,ghiringh/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas,Heigvd/Wegas
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013, 2014, 2015 School of Business and Engineering Vaud, Comem * Licensed under the MIT License */ package com.wegas.core.ejb; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.pusher.rest.Pusher; import com.pusher.rest.data.PresenceUser; import com.pusher.rest.data.Result; import com.wegas.core.Helper; import com.wegas.core.event.client.*; import com.wegas.core.exception.client.WegasErrorMessage; import com.wegas.core.persistence.AbstractEntity; import com.wegas.core.persistence.game.Game; import com.wegas.core.persistence.game.GameModel; import com.wegas.core.persistence.game.Player; import com.wegas.core.persistence.game.Team; import com.wegas.core.rest.util.JacksonMapperProvider; import com.wegas.core.rest.util.PusherChannelExistenceWebhook; import com.wegas.core.security.ejb.UserFacade; import com.wegas.core.security.persistence.User; import com.wegas.core.security.util.OnlineUser; import com.wegas.core.security.util.SecurityHelper; import org.apache.shiro.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.InvocationTargetException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; /** * @author Yannick Lagger (lagger.yannick.com) */ @Stateless @LocalBean public class WebsocketFacade { private static final Logger logger = LoggerFactory.getLogger(WebsocketFacade.class); private final Pusher pusher; private final Boolean maintainLocalListUpToDate; public final static String GLOBAL_CHANNEL = "global-channel"; public final static String ADMIN_CHANNEL = "private-Admin"; public static final Pattern USER_CHANNEL_PATTERN = Pattern.compile(Helper.USER_CHANNEL_PREFIX + "(\\d+)"); public static final Pattern PRIVATE_CHANNEL_PATTERN = Pattern.compile("private-(User|Player|Team|Game|GameModel)-(\\d+)"); private static boolean onlineUsersUptodate = false; private static final Map<Long, OnlineUser> onlineUsers = new HashMap<>(); public enum WegasStatus { DOWN, READY, OUTDATED } @EJB GameFacade gameFacade; @EJB TeamFacade teamFacade; /** * */ @EJB private UserFacade userFacade; @EJB private PlayerFacade playerFacade; @Inject private RequestFacade requestFacade; /** * Initialize Pusher Connection */ public WebsocketFacade() { Pusher tmp; String appId = getProperty("pusher.appId"); String key = getProperty("pusher.key"); String secret = getProperty("pusher.secret"); maintainLocalListUpToDate = "true".equalsIgnoreCase(getProperty("pusher.onlineusers_hook")); if (!Helper.isNullOrEmpty(appId) && !Helper.isNullOrEmpty(key) && !Helper.isNullOrEmpty(secret)) { tmp = new Pusher(getProperty("pusher.appId"), getProperty("pusher.key"), getProperty("pusher.secret")); tmp.setCluster(getProperty("pusher.cluster")); pusher = tmp; } else { pusher = null; } } /** * Get all channels based on entites * * @param entities * @return according to entities, all concerned channels */ public List<String> getChannels(List<AbstractEntity> entities) { List<String> channels = new ArrayList<>(); String channel = null; for (AbstractEntity entity : entities) { if (entity instanceof GameModel) { if (SecurityUtils.getSubject().isPermitted("GameModel:View:gm" + entity.getId())) { channel = ((GameModel) entity).getChannel(); } } else if (entity instanceof Game) { if (SecurityHelper.isPermitted((Game) entity, "View")) { channel = ((Game) entity).getChannel(); } } else if (entity instanceof Team) { Team team = (Team) entity; User user = userFacade.getCurrentUser(); if (SecurityHelper.isPermitted(team.getGame(), "Edit") // Trainer and scenarist || playerFacade.checkExistingPlayerInTeam(team.getId(), user.getId()) != null) { // or member of team channel = ((Team) entity).getChannel(); } } else if (entity instanceof Player) { Player player = (Player) entity; User user = userFacade.getCurrentUser(); if (SecurityHelper.isPermitted(player.getGame(), "Edit") // Trainer and scenarist || player.getUser() == user) { // is the player channel = ((Player) entity).getChannel(); } } if (channel != null) { channels.add(channel); } } return channels; } public void sendLock(String channel, String token) { if (this.pusher != null) { logger.error("send lock " + token + " to " + channel); pusher.trigger(channel, "LockEvent", "{\"@class\": \"LockEvent\", \"token\": \"" + token + "\", \"status\": \"lock\"}", null); } } public void sendUnLock(String channel, String token) { if (this.pusher != null) { logger.error("send lock " + token + " to " + channel); pusher.trigger(channel, "LockEvent", "{\"@class\": \"LockEvent\", \"token\": \"" + token + "\", \"status\": \"unlock\"}", null); } } /** * @param channel * @param status * @param socketId */ public void sendLifeCycleEvent(String channel, WegasStatus status, final String socketId) { if (this.pusher != null) { pusher.trigger(channel, "LifeCycleEvent", "{\"@class\": \"LifeCycleEvent\", \"status\": \"" + status.toString() + "\"}", socketId); } } /** * Send LifeCycle event to every connected user * * @param status * @param socketId */ public void sendLifeCycleEvent(WegasStatus status, final String socketId) { sendLifeCycleEvent(GLOBAL_CHANNEL, status, socketId); } /** * @param channel * @param message * @param socketId */ public void sendPopup(String channel, String message, final String socketId) { if (this.pusher != null) { pusher.trigger(channel, "CustomEvent", "{\"@class\": \"CustomEvent\", \"type\": \"popupEvent\", \"payload\": {\"content\": \"<p>" + message + "</p>\"}}", socketId); } } /** * @param property * @return the property value */ private String getProperty(String property) { try { return Helper.getWegasProperty(property); } catch (MissingResourceException ex) { logger.warn("Pusher init failed: missing " + property + " property"); return null; } } /** * @param filter * @param entityType * @param entityId * @param data * @return Status * @throws IOException */ public Integer send(String filter, String entityType, String entityId, Object data) throws IOException { if (this.pusher == null) { return 400; } return pusher.trigger(entityType + "-" + entityId, filter, data).getHttpStatus(); } /** * fire and forget pusher events * * @param dispatchedEntities * @param destroyedEntities * @param outdatedEntities */ public void onRequestCommit(final Map<String, List<AbstractEntity>> dispatchedEntities, final Map<String, List<AbstractEntity>> destroyedEntities, final Map<String, List<AbstractEntity>> outdatedEntities) { this.onRequestCommit(dispatchedEntities, destroyedEntities, outdatedEntities, null); } /** * fire and forget pusher events * * @param dispatchedEntities * @param destroyedEntities * @param outdatedEntities * @param socketId Client's socket id. Prevent that specific * client to receive this particular message */ public void onRequestCommit(final Map<String, List<AbstractEntity>> dispatchedEntities, final Map<String, List<AbstractEntity>> destroyedEntities, final Map<String, List<AbstractEntity>> outdatedEntities, final String socketId) { if (this.pusher == null) { return; } propagate(destroyedEntities, socketId, EntityDestroyedEvent.class); propagate(dispatchedEntities, socketId, EntityUpdatedEvent.class); propagate(outdatedEntities, socketId, OutdatedEntitiesEvent.class); } /** * @param <T> * @param container * @param socketId * @param eventClass */ private <T extends ClientEvent> void propagate(Map<String, List<AbstractEntity>> container, String socketId, Class<T> eventClass) { try { for (Map.Entry<String, List<AbstractEntity>> entry : container.entrySet()) { String audience = entry.getKey(); List<AbstractEntity> toPropagate = entry.getValue(); ClientEvent event; if (eventClass == EntityDestroyedEvent.class) { List<AbstractEntity> refreshed = new ArrayList<>(); /* * Not possible to find an already destroyed entity, so, in * this case (and since those informations are sufficient), * only id and class name are propagated */ for (AbstractEntity ae : toPropagate) { refreshed.add(new DestroyedEntity(ae.getId(), ae.getJSONClassName())); } event = eventClass.getDeclaredConstructor(List.class).newInstance(refreshed); } else { event = eventClass.getDeclaredConstructor(List.class).newInstance(toPropagate); } propagate(event, audience, socketId); } } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { logger.error("EVENT INSTANTIATION FAILS"); } } /** * Gzip some string * * @param data * @return gzipped data * @throws IOException */ private GzContent gzip(String channel, String name, String data, String socketId) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); OutputStreamWriter osw = new OutputStreamWriter(gzos, "UTF-8"); osw.append(data); osw.flush(); osw.close(); byte[] ba = baos.toByteArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ba.length; i++) { // @hack convert to uint array /* * Sending a byte[] through pusher result takes lot of place cause * json is like "data: [31, 8, -127, ...]", full text */ sb.append(Character.toString((char) Byte.toUnsignedInt(ba[i]))); } return new GzContent(channel, name, sb.toString(), socketId); } private static class GzContent { private final String name; private final String[] channels = {""}; private final String data; private final String socketId; public GzContent(String channel, String name, String data, String socketId) { this.data = data; this.socketId = socketId; this.channels[0] = channel; this.name = name; } public String getName() { return name; } public String[] getChannels() { return channels; } public String getData() { return data; } public String getSocketId() { return socketId; } }; private int computeLength(GzContent gzip) { try { ObjectMapper mapper = JacksonMapperProvider.getMapper(); String writeValueAsString = mapper.writeValueAsString(gzip); logger.error(writeValueAsString); logger.error("LENGTH SHOULD BE: " + writeValueAsString.length()); return writeValueAsString.length(); } catch (JsonProcessingException ex) { logger.error("FAILS TO COMPUTE LENGTH"); return 0; } } /** * Send data through pusher * * @param clientEvent * @param audience * @param socketId */ private void propagate(ClientEvent clientEvent, String audience, final String socketId) { try { String eventName = clientEvent.getClass().getSimpleName() + ".gz"; //if (eventName.matches(".*\\.gz$")) { GzContent gzip = gzip(audience, eventName, clientEvent.toJson(), socketId); String content = gzip.getData(); //int computedLength = computeLength(gzip); //if (computedLength > 10240) { // logger.error("413 MESSAGE TOO BIG"); // wooops pusher error (too big) // this.fallback(clientEvent, audience, socketId); //} else { Result result = pusher.trigger(audience, eventName, content, socketId); if (result.getHttpStatus() == 403) { logger.error("403 QUOTA REACHED"); } else if (result.getHttpStatus() == 413) { logger.error("413 MESSAGE TOO BIG"); this.fallback(clientEvent, audience, socketId); } //} } catch (IOException ex) { logger.error(" IOEX <----------------------", ex); } } private void fallback(ClientEvent clientEvent, String audience, final String socketId) { if (clientEvent instanceof EntityUpdatedEvent) { this.propagate(new OutdatedEntitiesEvent(((EntityUpdatedEvent) clientEvent).getUpdatedEntities()), audience, socketId); //this.outdateEntities(audience, ((EntityUpdatedEvent) clientEvent), socketId); } else { logger.error(" -> OUTDATE"); this.sendLifeCycleEvent(audience, WegasStatus.OUTDATED, socketId); } } /** * Pusher authentication * * @param socketId * @param channel * @return complete body to return to the client requesting authentication */ public String pusherAuth(final String socketId, final String channel) { if (channel.startsWith("presence")) { final Map<String, String> userInfo = new HashMap<>(); User user = userFacade.getCurrentUser(); userInfo.put("name", user.getName()); return pusher.authenticate(socketId, channel, new PresenceUser(user.getId(), userInfo)); } if (channel.startsWith("private")) { boolean hasPermission = userFacade.hasPermission(channel); if (hasPermission) { return pusher.authenticate(socketId, channel); } } return null; } private User getUserFromChannel(String channelName) { Matcher matcher = USER_CHANNEL_PATTERN.matcher(channelName); if (matcher.matches()) { if (matcher.groupCount() == 1) { Long userId = Long.parseLong(matcher.group(1)); return userFacade.find(userId); } } return null; } /** * * @param hook */ public void pusherChannelExistenceWebhook(PusherChannelExistenceWebhook hook) { synchronized (onlineUsers) { if (!WebsocketFacade.onlineUsersUptodate) { initOnlineUsers(); } User user = this.getUserFromChannel(hook.getChannel()); if (user != null) { if (hook.getName().equals("channel_occupied")) { this.registerUser(user); } else if (hook.getName().equals("channel_vacated")) { onlineUsers.remove(user.getId()); } this.propagateOnlineUsers(); } } } /** * Return online users * * @return list a users who are online */ public Collection<OnlineUser> getOnlineUsers() { synchronized (onlineUsers) { if (!WebsocketFacade.onlineUsersUptodate) { initOnlineUsers(); } } return onlineUsers.values(); } /** * Register user within internal onlineUser list * * @param user */ private void registerUser(User user) { if (user != null && !onlineUsers.containsKey(user.getId())) { onlineUsers.put(user.getId(), new OnlineUser(user)); } } /** * Build initial onlineUser list from pusher channels list */ private void initOnlineUsers() { try { this.clearOnlineUsers(); Result get = pusher.get("/channels"); String message = get.getMessage(); ObjectMapper mapper = JacksonMapperProvider.getMapper(); HashMap<String, HashMap<String, Object>> readValue = mapper.readValue(message, HashMap.class); HashMap<String, Object> channels = readValue.get("channels"); for (String channel : channels.keySet()) { this.registerUser(this.getUserFromChannel(channel)); } if (maintainLocalListUpToDate) { WebsocketFacade.onlineUsersUptodate = true; } } catch (IOException ex) { java.util.logging.Logger.getLogger(WebsocketFacade.class.getName()).log(Level.SEVERE, null, ex); } } /** * Say to admin's who are currently logged in that some users connect or * disconnect */ private void propagateOnlineUsers() { try { ObjectMapper mapper = JacksonMapperProvider.getMapper(); String users = mapper.writeValueAsString(onlineUsers.values()); pusher.trigger("private-Admin", "online-users", users); } catch (JsonProcessingException ex) { java.util.logging.Logger.getLogger(WebsocketFacade.class.getName()).log(Level.SEVERE, null, ex); } } public void clearOnlineUsers() { synchronized (onlineUsers) { onlineUsers.clear(); onlineUsersUptodate = false; } } /** * Assert HmacSHA256 BODY signature match * * @param request * @param raw */ public void authenticateHookSource(HttpServletRequest request, byte[] raw) { try { String pusherKey = request.getHeader("X-Pusher-Key"); if (pusherKey == null || !pusherKey.equals(Helper.getWegasProperty("pusher.key"))) { throw WegasErrorMessage.error("Invalid app key"); } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(Helper.getWegasProperty("pusher.secret").getBytes("UTF-8"), "HmacSHA256")); String hex = Helper.hex(mac.doFinal(raw)); if (hex == null || !hex.equals(request.getHeader("X-Pusher-Signature"))) { throw WegasErrorMessage.error("Authentication Failed"); } } catch (IOException ex) { throw WegasErrorMessage.error("Unable to read request body"); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw WegasErrorMessage.error(ex.getMessage()); } } }
wegas-core/src/main/java/com/wegas/core/ejb/WebsocketFacade.java
/* * Wegas * http://wegas.albasim.ch * * Copyright (c) 2013, 2014, 2015 School of Business and Engineering Vaud, Comem * Licensed under the MIT License */ package com.wegas.core.ejb; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.pusher.rest.Pusher; import com.pusher.rest.data.PresenceUser; import com.pusher.rest.data.Result; import com.wegas.core.Helper; import com.wegas.core.event.client.*; import com.wegas.core.exception.client.WegasErrorMessage; import com.wegas.core.persistence.AbstractEntity; import com.wegas.core.persistence.game.Game; import com.wegas.core.persistence.game.GameModel; import com.wegas.core.persistence.game.Player; import com.wegas.core.persistence.game.Team; import com.wegas.core.rest.util.JacksonMapperProvider; import com.wegas.core.rest.util.PusherChannelExistenceWebhook; import com.wegas.core.security.ejb.UserFacade; import com.wegas.core.security.persistence.User; import com.wegas.core.security.util.OnlineUser; import com.wegas.core.security.util.SecurityHelper; import org.apache.shiro.SecurityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.InvocationTargetException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; /** * @author Yannick Lagger (lagger.yannick.com) */ @Stateless @LocalBean public class WebsocketFacade { private static final Logger logger = LoggerFactory.getLogger(WebsocketFacade.class); private final Pusher pusher; private final Boolean maintainLocalListUpToDate; public final static String GLOBAL_CHANNEL = "global-channel"; public final static String ADMIN_CHANNEL = "private-Admin"; public static final Pattern USER_CHANNEL_PATTERN = Pattern.compile(Helper.USER_CHANNEL_PREFIX + "(\\d+)"); public static final Pattern PRIVATE_CHANNEL_PATTERN = Pattern.compile("private-(User|Player|Team|Game|GameModel)-(\\d+)"); private static boolean onlineUsersUptodate = false; private static final Map<Long, OnlineUser> onlineUsers = new HashMap<>(); public enum WegasStatus { DOWN, READY, OUTDATED } @EJB GameFacade gameFacade; @EJB TeamFacade teamFacade; /** * */ @EJB private UserFacade userFacade; @EJB private PlayerFacade playerFacade; @Inject private RequestFacade requestFacade; /** * Initialize Pusher Connection */ public WebsocketFacade() { Pusher tmp; String appId = getProperty("pusher.appId"); String key = getProperty("pusher.key"); String secret = getProperty("pusher.secret"); maintainLocalListUpToDate = "true".equalsIgnoreCase(getProperty("pusher.onlineusers_hook")); if (!Helper.isNullOrEmpty(appId) && !Helper.isNullOrEmpty(key) && !Helper.isNullOrEmpty(secret)) { tmp = new Pusher(getProperty("pusher.appId"), getProperty("pusher.key"), getProperty("pusher.secret")); tmp.setCluster(getProperty("pusher.cluster")); pusher = tmp; } else { pusher = null; } } /** * Get all channels based on entites * * @param entities * @return according to entities, all concerned channels */ public List<String> getChannels(List<AbstractEntity> entities) { List<String> channels = new ArrayList<>(); String channel = null; for (AbstractEntity entity : entities) { if (entity instanceof GameModel) { if (SecurityUtils.getSubject().isPermitted("GameModel:View:gm" + entity.getId())) { channel = "GameModel"; } } else if (entity instanceof Game) { if (SecurityHelper.isPermitted((Game) entity, "View")) { channel = "Game"; } } else if (entity instanceof Team) { Team team = (Team) entity; User user = userFacade.getCurrentUser(); if (SecurityHelper.isPermitted(team.getGame(), "Edit") // Trainer and scenarist || playerFacade.checkExistingPlayerInTeam(team.getId(), user.getId()) != null) { // or member of team channel = "Team"; } } else if (entity instanceof Player) { Player player = (Player) entity; User user = userFacade.getCurrentUser(); if (SecurityHelper.isPermitted(player.getGame(), "Edit") // Trainer and scenarist || player.getUser() == user) { // is the player channel = "Player"; } } if (channel != null) { channels.add(channel + "-" + entity.getId()); } } return channels; } public void sendLock(String channel, String token) { if (this.pusher != null) { logger.error("send lock " + token + " to " + channel); pusher.trigger(channel, "LockEvent", "{\"@class\": \"LockEvent\", \"token\": \"" + token + "\", \"status\": \"lock\"}", null); } } public void sendUnLock(String channel, String token) { if (this.pusher != null) { logger.error("send lock " + token + " to " + channel); pusher.trigger(channel, "LockEvent", "{\"@class\": \"LockEvent\", \"token\": \"" + token + "\", \"status\": \"unlock\"}", null); } } /** * @param channel * @param status * @param socketId */ public void sendLifeCycleEvent(String channel, WegasStatus status, final String socketId) { if (this.pusher != null) { pusher.trigger(channel, "LifeCycleEvent", "{\"@class\": \"LifeCycleEvent\", \"status\": \"" + status.toString() + "\"}", socketId); } } /** * Send LifeCycle event to every connected user * * @param status * @param socketId */ public void sendLifeCycleEvent(WegasStatus status, final String socketId) { sendLifeCycleEvent(GLOBAL_CHANNEL, status, socketId); } /** * @param channel * @param message * @param socketId */ public void sendPopup(String channel, String message, final String socketId) { if (this.pusher != null) { pusher.trigger(channel, "CustomEvent", "{\"@class\": \"CustomEvent\", \"type\": \"popupEvent\", \"payload\": {\"content\": \"<p>" + message + "</p>\"}}", socketId); } } /** * @param property * @return the property value */ private String getProperty(String property) { try { return Helper.getWegasProperty(property); } catch (MissingResourceException ex) { logger.warn("Pusher init failed: missing " + property + " property"); return null; } } /** * @param filter * @param entityType * @param entityId * @param data * @return Status * @throws IOException */ public Integer send(String filter, String entityType, String entityId, Object data) throws IOException { if (this.pusher == null) { return 400; } return pusher.trigger(entityType + "-" + entityId, filter, data).getHttpStatus(); } /** * fire and forget pusher events * * @param dispatchedEntities * @param destroyedEntities * @param outdatedEntities */ public void onRequestCommit(final Map<String, List<AbstractEntity>> dispatchedEntities, final Map<String, List<AbstractEntity>> destroyedEntities, final Map<String, List<AbstractEntity>> outdatedEntities) { this.onRequestCommit(dispatchedEntities, destroyedEntities, outdatedEntities, null); } /** * fire and forget pusher events * * @param dispatchedEntities * @param destroyedEntities * @param outdatedEntities * @param socketId Client's socket id. Prevent that specific * client to receive this particular message */ public void onRequestCommit(final Map<String, List<AbstractEntity>> dispatchedEntities, final Map<String, List<AbstractEntity>> destroyedEntities, final Map<String, List<AbstractEntity>> outdatedEntities, final String socketId) { if (this.pusher == null) { return; } propagate(destroyedEntities, socketId, EntityDestroyedEvent.class); propagate(dispatchedEntities, socketId, EntityUpdatedEvent.class); propagate(outdatedEntities, socketId, OutdatedEntitiesEvent.class); } /** * @param <T> * @param container * @param socketId * @param eventClass */ private <T extends ClientEvent> void propagate(Map<String, List<AbstractEntity>> container, String socketId, Class<T> eventClass) { try { for (Map.Entry<String, List<AbstractEntity>> entry : container.entrySet()) { String audience = entry.getKey(); List<AbstractEntity> toPropagate = entry.getValue(); ClientEvent event; if (eventClass == EntityDestroyedEvent.class) { List<AbstractEntity> refreshed = new ArrayList<>(); /* * Not possible to find an already destroyed entity, so, in * this case (and since those informations are sufficient), * only id and class name are propagated */ for (AbstractEntity ae : toPropagate) { refreshed.add(new DestroyedEntity(ae.getId(), ae.getJSONClassName())); } event = eventClass.getDeclaredConstructor(List.class).newInstance(refreshed); } else { event = eventClass.getDeclaredConstructor(List.class).newInstance(toPropagate); } propagate(event, audience, socketId); } } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { logger.error("EVENT INSTANTIATION FAILS"); } } /** * Gzip some string * * @param data * @return gzipped data * @throws IOException */ private GzContent gzip(String channel, String name, String data, String socketId) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); OutputStreamWriter osw = new OutputStreamWriter(gzos, "UTF-8"); osw.append(data); osw.flush(); osw.close(); byte[] ba = baos.toByteArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ba.length; i++) { // @hack convert to uint array /* * Sending a byte[] through pusher result takes lot of place cause * json is like "data: [31, 8, -127, ...]", full text */ sb.append(Character.toString((char) Byte.toUnsignedInt(ba[i]))); } return new GzContent(channel, name, sb.toString(), socketId); } private static class GzContent { private final String name; private final String[] channels = {""}; private final String data; private final String socketId; public GzContent(String channel, String name, String data, String socketId) { this.data = data; this.socketId = socketId; this.channels[0] = channel; this.name = name; } public String getName() { return name; } public String[] getChannels() { return channels; } public String getData() { return data; } public String getSocketId() { return socketId; } }; private int computeLength(GzContent gzip) { try { ObjectMapper mapper = JacksonMapperProvider.getMapper(); String writeValueAsString = mapper.writeValueAsString(gzip); logger.error(writeValueAsString); logger.error("LENGTH SHOULD BE: " + writeValueAsString.length()); return writeValueAsString.length(); } catch (JsonProcessingException ex) { logger.error("FAILS TO COMPUTE LENGTH"); return 0; } } /** * Send data through pusher * * @param clientEvent * @param audience * @param socketId */ private void propagate(ClientEvent clientEvent, String audience, final String socketId) { try { String eventName = clientEvent.getClass().getSimpleName() + ".gz"; //if (eventName.matches(".*\\.gz$")) { GzContent gzip = gzip(audience, eventName, clientEvent.toJson(), socketId); String content = gzip.getData(); //int computedLength = computeLength(gzip); //if (computedLength > 10240) { // logger.error("413 MESSAGE TOO BIG"); // wooops pusher error (too big) // this.fallback(clientEvent, audience, socketId); //} else { Result result = pusher.trigger(audience, eventName, content, socketId); if (result.getHttpStatus() == 403) { logger.error("403 QUOTA REACHED"); } else if (result.getHttpStatus() == 413) { logger.error("413 MESSAGE TOO BIG"); this.fallback(clientEvent, audience, socketId); } //} } catch (IOException ex) { logger.error(" IOEX <----------------------", ex); } } private void fallback(ClientEvent clientEvent, String audience, final String socketId) { if (clientEvent instanceof EntityUpdatedEvent) { this.propagate(new OutdatedEntitiesEvent(((EntityUpdatedEvent) clientEvent).getUpdatedEntities()), audience, socketId); //this.outdateEntities(audience, ((EntityUpdatedEvent) clientEvent), socketId); } else { logger.error(" -> OUTDATE"); this.sendLifeCycleEvent(audience, WegasStatus.OUTDATED, socketId); } } /** * Pusher authentication * * @param socketId * @param channel * @return complete body to return to the client requesting authentication */ public String pusherAuth(final String socketId, final String channel) { if (channel.startsWith("presence")) { final Map<String, String> userInfo = new HashMap<>(); User user = userFacade.getCurrentUser(); userInfo.put("name", user.getName()); return pusher.authenticate(socketId, channel, new PresenceUser(user.getId(), userInfo)); } if (channel.startsWith("private")) { boolean hasPermission = userFacade.hasPermission(channel); if (hasPermission) { return pusher.authenticate(socketId, channel); } } return null; } private User getUserFromChannel(String channelName) { Matcher matcher = USER_CHANNEL_PATTERN.matcher(channelName); if (matcher.matches()) { if (matcher.groupCount() == 1) { Long userId = Long.parseLong(matcher.group(1)); return userFacade.find(userId); } } return null; } /** * * @param hook */ public void pusherChannelExistenceWebhook(PusherChannelExistenceWebhook hook) { synchronized (onlineUsers) { if (!WebsocketFacade.onlineUsersUptodate) { initOnlineUsers(); } User user = this.getUserFromChannel(hook.getChannel()); if (user != null) { if (hook.getName().equals("channel_occupied")) { this.registerUser(user); } else if (hook.getName().equals("channel_vacated")) { onlineUsers.remove(user.getId()); } this.propagateOnlineUsers(); } } } /** * Return online users * * @return list a users who are online */ public Collection<OnlineUser> getOnlineUsers() { synchronized (onlineUsers) { if (!WebsocketFacade.onlineUsersUptodate) { initOnlineUsers(); } } return onlineUsers.values(); } /** * Register user within internal onlineUser list * * @param user */ private void registerUser(User user) { if (user != null && !onlineUsers.containsKey(user.getId())) { onlineUsers.put(user.getId(), new OnlineUser(user)); } } /** * Build initial onlineUser list from pusher channels list */ private void initOnlineUsers() { try { this.clearOnlineUsers(); Result get = pusher.get("/channels"); String message = get.getMessage(); ObjectMapper mapper = JacksonMapperProvider.getMapper(); HashMap<String, HashMap<String, Object>> readValue = mapper.readValue(message, HashMap.class); HashMap<String, Object> channels = readValue.get("channels"); for (String channel : channels.keySet()) { this.registerUser(this.getUserFromChannel(channel)); } if (maintainLocalListUpToDate) { WebsocketFacade.onlineUsersUptodate = true; } } catch (IOException ex) { java.util.logging.Logger.getLogger(WebsocketFacade.class.getName()).log(Level.SEVERE, null, ex); } } /** * Say to admin's who are currently logged in that some users connect or * disconnect */ private void propagateOnlineUsers() { try { ObjectMapper mapper = JacksonMapperProvider.getMapper(); String users = mapper.writeValueAsString(onlineUsers.values()); pusher.trigger("private-Admin", "online-users", users); } catch (JsonProcessingException ex) { java.util.logging.Logger.getLogger(WebsocketFacade.class.getName()).log(Level.SEVERE, null, ex); } } public void clearOnlineUsers() { synchronized (onlineUsers) { onlineUsers.clear(); onlineUsersUptodate = false; } } /** * Assert HmacSHA256 BODY signature match * * @param request * @param raw */ public void authenticateHookSource(HttpServletRequest request, byte[] raw) { try { String pusherKey = request.getHeader("X-Pusher-Key"); if (pusherKey == null || !pusherKey.equals(Helper.getWegasProperty("pusher.key"))) { throw WegasErrorMessage.error("Invalid app key"); } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(Helper.getWegasProperty("pusher.secret").getBytes("UTF-8"), "HmacSHA256")); String hex = Helper.hex(mac.doFinal(raw)); if (hex == null || !hex.equals(request.getHeader("X-Pusher-Signature"))) { throw WegasErrorMessage.error("Authentication Failed"); } } catch (IOException ex) { throw WegasErrorMessage.error("Unable to read request body"); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw WegasErrorMessage.error(ex.getMessage()); } } }
Get Channels based on entity * fix channels name
wegas-core/src/main/java/com/wegas/core/ejb/WebsocketFacade.java
Get Channels based on entity
<ide><path>egas-core/src/main/java/com/wegas/core/ejb/WebsocketFacade.java <ide> } <ide> } <ide> <add> <ide> /** <ide> * Get all channels based on entites <ide> * <ide> for (AbstractEntity entity : entities) { <ide> if (entity instanceof GameModel) { <ide> if (SecurityUtils.getSubject().isPermitted("GameModel:View:gm" + entity.getId())) { <del> channel = "GameModel"; <add> channel = ((GameModel) entity).getChannel(); <ide> } <ide> } else if (entity instanceof Game) { <ide> if (SecurityHelper.isPermitted((Game) entity, "View")) { <del> channel = "Game"; <add> channel = ((Game) entity).getChannel(); <ide> } <ide> } else if (entity instanceof Team) { <ide> Team team = (Team) entity; <ide> User user = userFacade.getCurrentUser(); <ide> if (SecurityHelper.isPermitted(team.getGame(), "Edit") // Trainer and scenarist <ide> || playerFacade.checkExistingPlayerInTeam(team.getId(), user.getId()) != null) { // or member of team <del> channel = "Team"; <add> channel = ((Team) entity).getChannel(); <ide> } <ide> } else if (entity instanceof Player) { <ide> Player player = (Player) entity; <ide> User user = userFacade.getCurrentUser(); <ide> if (SecurityHelper.isPermitted(player.getGame(), "Edit") // Trainer and scenarist <ide> || player.getUser() == user) { // is the player <del> channel = "Player"; <add> channel = ((Player) entity).getChannel(); <ide> } <ide> } <ide> <ide> if (channel != null) { <del> channels.add(channel + "-" + entity.getId()); <add> channels.add(channel); <ide> } <ide> } <ide> return channels;
Java
apache-2.0
8e7f34713c360309b26ae0be933ccd3ce145b0d2
0
dhutchis/accumulo,milleruntime/accumulo,phrocker/accumulo,phrocker/accumulo,mjwall/accumulo,adamjshook/accumulo,lstav/accumulo,joshelser/accumulo,phrocker/accumulo,mikewalch/accumulo,apache/accumulo,keith-turner/accumulo,dhutchis/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,ivakegg/accumulo,milleruntime/accumulo,apache/accumulo,ivakegg/accumulo,adamjshook/accumulo,mikewalch/accumulo,mjwall/accumulo,milleruntime/accumulo,ctubbsii/accumulo,joshelser/accumulo,dhutchis/accumulo,ctubbsii/accumulo,mikewalch/accumulo,dhutchis/accumulo,ctubbsii/accumulo,apache/accumulo,lstav/accumulo,ctubbsii/accumulo,milleruntime/accumulo,phrocker/accumulo-1,keith-turner/accumulo,keith-turner/accumulo,phrocker/accumulo,adamjshook/accumulo,ctubbsii/accumulo,adamjshook/accumulo,apache/accumulo,joshelser/accumulo,phrocker/accumulo,phrocker/accumulo,ivakegg/accumulo,milleruntime/accumulo,dhutchis/accumulo,phrocker/accumulo,ivakegg/accumulo,ivakegg/accumulo,joshelser/accumulo,lstav/accumulo,apache/accumulo,joshelser/accumulo,mjwall/accumulo,mikewalch/accumulo,adamjshook/accumulo,adamjshook/accumulo,apache/accumulo,phrocker/accumulo-1,dhutchis/accumulo,phrocker/accumulo-1,dhutchis/accumulo,dhutchis/accumulo,ivakegg/accumulo,phrocker/accumulo-1,joshelser/accumulo,mjwall/accumulo,joshelser/accumulo,phrocker/accumulo,adamjshook/accumulo,ctubbsii/accumulo,apache/accumulo,phrocker/accumulo-1,keith-turner/accumulo,keith-turner/accumulo,dhutchis/accumulo,phrocker/accumulo-1,lstav/accumulo,adamjshook/accumulo,mjwall/accumulo,keith-turner/accumulo,milleruntime/accumulo,mjwall/accumulo,milleruntime/accumulo,mikewalch/accumulo,mjwall/accumulo,lstav/accumulo,lstav/accumulo,ivakegg/accumulo,adamjshook/accumulo,phrocker/accumulo,lstav/accumulo,mikewalch/accumulo,keith-turner/accumulo,joshelser/accumulo,mikewalch/accumulo,mikewalch/accumulo
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.server.security; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.core.security.SystemPermission; import org.apache.accumulo.core.security.TablePermission; import org.apache.accumulo.core.security.thrift.AuthInfo; import org.apache.accumulo.core.security.thrift.SecurityErrorCode; import org.apache.accumulo.core.util.ByteBufferUtil; import org.apache.accumulo.core.zookeeper.ZooUtil.NodeExistsPolicy; import org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.accumulo.server.zookeeper.IZooReaderWriter; import org.apache.accumulo.server.zookeeper.ZooCache; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.log4j.Logger; import org.apache.zookeeper.KeeperException; // Utility class for adding all security info into ZK public final class ZKAuthenticator implements Authenticator { private static final Logger log = Logger.getLogger(ZKAuthenticator.class); private static Authenticator zkAuthenticatorInstance = null; private static String rootUserName = null; private final String ZKUserAuths = "/Authorizations"; private final String ZKUserSysPerms = "/System"; private final String ZKUserTablePerms = "/Tables"; private final String ZKUserPath; private final ZooCache zooCache; public static synchronized Authenticator getInstance() { if (zkAuthenticatorInstance == null) zkAuthenticatorInstance = new Auditor(new ZKAuthenticator()); return zkAuthenticatorInstance; } private ZKAuthenticator() { this(HdfsZooInstance.getInstance().getInstanceID()); } public ZKAuthenticator(String instanceId) { ZKUserPath = Constants.ZROOT + "/" + instanceId + "/users"; zooCache = new ZooCache(); } /** * Authenticate a user's credentials * * @return true if username/password combination match existing user; false otherwise * @throws AccumuloSecurityException */ private boolean authenticate(AuthInfo credentials) throws AccumuloSecurityException { if (!credentials.instanceId.equals(HdfsZooInstance.getInstance().getInstanceID())) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.INVALID_INSTANCEID); if (credentials.user.equals(SecurityConstants.SYSTEM_USERNAME)) return credentials.equals(SecurityConstants.getSystemCredentials()); byte[] pass; String zpath = ZKUserPath + "/" + credentials.user; pass = zooCache.get(zpath); boolean result = Tool.checkPass(ByteBufferUtil.toBytes(credentials.password), pass); if (!result) { zooCache.clear(zpath); pass = zooCache.get(zpath); result = Tool.checkPass(ByteBufferUtil.toBytes(credentials.password), pass); } return result; } /** * Only SYSTEM user can call this method */ public void initializeSecurity(AuthInfo credentials, String rootuser, byte[] rootpass) throws AccumuloSecurityException { if (!credentials.user.equals(SecurityConstants.SYSTEM_USERNAME) || !authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); try { // remove old settings from zookeeper first, if any IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); synchronized (zooCache) { zooCache.clear(); if (zoo.exists(ZKUserPath)) { zoo.recursiveDelete(ZKUserPath, NodeMissingPolicy.SKIP); log.info("Removed " + ZKUserPath + "/" + " from zookeeper"); } // prep parent node of users with root username zoo.putPersistentData(ZKUserPath, rootuser.getBytes(), NodeExistsPolicy.FAIL); // create the root user with all system privileges, no table privileges, and no record-level authorizations Set<SystemPermission> rootPerms = new TreeSet<SystemPermission>(); for (SystemPermission p : SystemPermission.values()) rootPerms.add(p); Map<String,Set<TablePermission>> tablePerms = new HashMap<String,Set<TablePermission>>(); // Allow the root user to flush the !METADATA table tablePerms.put(Constants.METADATA_TABLE_ID, Collections.singleton(TablePermission.ALTER_TABLE)); constructUser(rootuser, Tool.createPass(rootpass), rootPerms, tablePerms, Constants.NO_AUTHS); } log.info("Initialized root user with username: " + rootuser + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new RuntimeException(e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (AccumuloException e) { log.error(e, e); throw new RuntimeException(e); } } /** * Sets up the user in ZK for the provided user. No checking for existence is done here, it should be done before calling. */ private void constructUser(String user, byte[] pass, Set<SystemPermission> sysPerms, Map<String,Set<TablePermission>> tablePerms, Authorizations auths) throws KeeperException, InterruptedException { synchronized (zooCache) { zooCache.clear(); IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); zoo.putPrivatePersistentData(ZKUserPath + "/" + user, pass, NodeExistsPolicy.FAIL); zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserAuths, Tool.convertAuthorizations(auths), NodeExistsPolicy.FAIL); zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserSysPerms, Tool.convertSystemPermissions(sysPerms), NodeExistsPolicy.FAIL); zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms, new byte[0], NodeExistsPolicy.FAIL); for (Entry<String,Set<TablePermission>> entry : tablePerms.entrySet()) createTablePerm(user, entry.getKey(), entry.getValue()); } } /** * Sets up a new table configuration for the provided user/table. No checking for existance is done here, it should be done before calling. */ private void createTablePerm(String user, String table, Set<TablePermission> perms) throws KeeperException, InterruptedException { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, Tool.convertTablePermissions(perms), NodeExistsPolicy.FAIL); } } public synchronized String getRootUsername() { if (rootUserName == null) rootUserName = new String(zooCache.get(ZKUserPath)); return rootUserName; } public boolean authenticateUser(AuthInfo credentials, String user, ByteBuffer pass) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); if (!credentials.user.equals(user) && !hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); return authenticate(new AuthInfo(user, pass, credentials.instanceId)); } public boolean authenticateUser(AuthInfo credentials, String user, byte[] pass) throws AccumuloSecurityException { return authenticateUser(credentials, user, ByteBuffer.wrap(pass)); } @Override public Set<String> listUsers(AuthInfo credentials) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); return new TreeSet<String>(zooCache.getChildren(ZKUserPath)); } /** * Creates a user with no permissions whatsoever */ public void createUser(AuthInfo credentials, String user, byte[] pass, Authorizations authorizations) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER)) { Authorizations creatorAuths = getUserAuthorizations(credentials, credentials.user); for (byte[] auth : authorizations.getAuthorizations()) if (!creatorAuths.contains(auth)) { log.info("User " + credentials.user + " attempted to create a user " + user + " with authorization " + new String(auth) + " they did not have"); throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS); } } // don't allow creating a user with the same name as system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED); try { constructUser(user, Tool.createPass(pass), new TreeSet<SystemPermission>(), new HashMap<String,Set<TablePermission>>(), authorizations); log.info("Created user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); if (e.code().equals(KeeperException.Code.NODEEXISTS)) throw new AccumuloSecurityException(user, SecurityErrorCode.USER_EXISTS, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (AccumuloException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e); } } public void dropUser(AuthInfo credentials, String user) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't delete root or system users if (user.equals(getRootUsername()) || user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED); try { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().recursiveDelete(ZKUserPath + "/" + user, NodeMissingPolicy.FAIL); } log.info("Deleted user " + user + " at the request of user " + credentials.user); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (KeeperException e) { log.error(e, e); if (e.code().equals(KeeperException.Code.NONODE)) throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } } public void changePassword(AuthInfo credentials, String user, byte[] pass) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !credentials.user.equals(user)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { try { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPrivatePersistentData(ZKUserPath + "/" + user, Tool.createPass(pass), NodeExistsPolicy.OVERWRITE); } log.info("Changed password for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (AccumuloException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e); } } else throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } /** * Checks if a user exists */ private boolean userExists(String user) { if (zooCache.get(ZKUserPath + "/" + user) != null) return true; zooCache.clear(ZKUserPath + "/" + user); return zooCache.get(ZKUserPath + "/" + user) != null; } public void changeAuthorizations(AuthInfo credentials, String user, Authorizations authorizations) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { try { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserAuths, Tool.convertAuthorizations(authorizations), NodeExistsPolicy.OVERWRITE); } log.info("Changed authorizations for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } public Authorizations getUserAuthorizations(AuthInfo credentials, String user) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM) && !credentials.user.equals(user)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // system user doesn't need record-level authorizations for the tables it reads (for now) if (user.equals(SecurityConstants.SYSTEM_USERNAME)) return Constants.NO_AUTHS; if (userExists(user)) { byte[] authsBytes = zooCache.get(ZKUserPath + "/" + user + ZKUserAuths); if (authsBytes != null) return Tool.convertAuthorizations(authsBytes); } throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } /** * Checks if a user has a system permission * * @return true if a user exists and has permission; false otherwise */ @Override public boolean hasSystemPermission(AuthInfo credentials, String user, SystemPermission permission) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); // some people just aren't allowed to ask about other users; here are those who can ask if (!credentials.user.equals(user) && !hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM) && !hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (user.equals(getRootUsername()) || user.equals(SecurityConstants.SYSTEM_USERNAME)) return true; byte[] perms = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (perms != null) { if (Tool.convertSystemPermissions(perms).contains(permission)) return true; zooCache.clear(ZKUserPath + "/" + user + ZKUserSysPerms); perms = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (perms == null) return false; return Tool.convertSystemPermissions(zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms)).contains(permission); } throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } @Override public boolean hasTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!_hasTablePermission(credentials, user, table, permission)) { zooCache.clear(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); return _hasTablePermission(credentials, user, table, permission); } return true; } private boolean _hasTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); // some people just aren't allowed to ask about other users; here are those who can ask if (!credentials.user.equals(user) && !hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM) && !hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // always allow system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) return true; // Don't let nonexistant users scan if (!userExists(user)) throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist // allow anybody to read the METADATA table if (table.equals(Constants.METADATA_TABLE_ID) && permission.equals(TablePermission.READ)) return true; byte[] serializedPerms = zooCache.get(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); if (serializedPerms != null) { return Tool.convertTablePermissions(serializedPerms).contains(permission); } return false; } @Override public void grantSystemPermission(AuthInfo credentials, String user, SystemPermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (permission.equals(SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.GRANT_INVALID); if (userExists(user)) { try { byte[] permBytes = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (permBytes == null) { throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } Set<SystemPermission> perms = Tool.convertSystemPermissions(permBytes); if (perms.add(permission)) { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserSysPerms, Tool.convertSystemPermissions(perms), NodeExistsPolicy.OVERWRITE); } } log.info("Granted system permission " + permission + " for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } @Override public void grantTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasTablePermission(credentials, credentials.user, table, TablePermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { Set<TablePermission> tablePerms; byte[] serializedPerms = zooCache.get(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); if (serializedPerms != null) tablePerms = Tool.convertTablePermissions(serializedPerms); else tablePerms = new TreeSet<TablePermission>(); try { if (tablePerms.add(permission)) { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, Tool.convertTablePermissions(tablePerms), NodeExistsPolicy.OVERWRITE); } } log.info("Granted table permission " + permission + " for user " + user + " on the table " + table + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } @Override public void revokeSystemPermission(AuthInfo credentials, String user, SystemPermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user or revoke permissions from root user if (user.equals(SecurityConstants.SYSTEM_USERNAME) || user.equals(getRootUsername())) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (permission.equals(SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.GRANT_INVALID); if (userExists(user)) { byte[] sysPermBytes = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (sysPermBytes == null) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); Set<SystemPermission> sysPerms = Tool.convertSystemPermissions(sysPermBytes); try { if (sysPerms.remove(permission)) { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserSysPerms, Tool.convertSystemPermissions(sysPerms), NodeExistsPolicy.OVERWRITE); } } log.info("Revoked system permission " + permission + " for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); } @Override public void revokeTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasTablePermission(credentials, credentials.user, table, TablePermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { byte[] serializedPerms = zooCache.get(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); if (serializedPerms == null) return; Set<TablePermission> tablePerms = Tool.convertTablePermissions(serializedPerms); try { if (tablePerms.remove(permission)) { zooCache.clear(); IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); if (tablePerms.size() == 0) zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, NodeMissingPolicy.SKIP); else zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, Tool.convertTablePermissions(tablePerms), NodeExistsPolicy.OVERWRITE); } } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } log.info("Revoked table permission " + permission + " for user " + user + " on the table " + table + " at the request of user " + credentials.user); } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); } @Override public void deleteTable(AuthInfo credentials, String table) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_TABLE) && !hasTablePermission(credentials, credentials.user, table, TablePermission.DROP_TABLE)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); try { synchronized (zooCache) { zooCache.clear(); IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); for (String user : zooCache.getChildren(ZKUserPath)) zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, NodeMissingPolicy.SKIP); } } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } /** * All the static too methods used for this class, so that we can separate out stuff that isn't using ZooKeeper. That way, we can check the synchronization * model more easily, as we only need to check to make sure zooCache is cleared when things are written to ZooKeeper in methods that might use it. These * won't, and so don't need to be checked. */ static class Tool { private static final int SALT_LENGTH = 8; // Generates a byte array salt of length SALT_LENGTH private static byte[] generateSalt() { final SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); return salt; } private static byte[] hash(byte[] raw) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(Constants.PW_HASH_ALGORITHM); md.update(raw); return md.digest(); } public static boolean checkPass(byte[] password, byte[] zkData) { if (zkData == null) return false; byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(zkData, 0, salt, 0, SALT_LENGTH); byte[] passwordToCheck; try { passwordToCheck = convertPass(password, salt); } catch (NoSuchAlgorithmException e) { log.error("Count not create hashed password", e); return false; } return java.util.Arrays.equals(passwordToCheck, zkData); } public static byte[] createPass(byte[] password) throws AccumuloException { byte[] salt = generateSalt(); try { return convertPass(password, salt); } catch (NoSuchAlgorithmException e) { log.error("Count not create hashed password", e); throw new AccumuloException("Count not create hashed password", e); } } private static byte[] convertPass(byte[] password, byte[] salt) throws NoSuchAlgorithmException { byte[] plainSalt = new byte[password.length + SALT_LENGTH]; System.arraycopy(password, 0, plainSalt, 0, password.length); System.arraycopy(salt, 0, plainSalt, password.length, SALT_LENGTH); byte[] hashed = hash(plainSalt); byte[] saltedHash = new byte[SALT_LENGTH + hashed.length]; System.arraycopy(salt, 0, saltedHash, 0, SALT_LENGTH); System.arraycopy(hashed, 0, saltedHash, SALT_LENGTH, hashed.length); return saltedHash; // contains salt+hash(password+salt) } public static Authorizations convertAuthorizations(byte[] authorizations) { return new Authorizations(authorizations); } public static byte[] convertAuthorizations(Authorizations authorizations) { return authorizations.getAuthorizationsArray(); } public static byte[] convertSystemPermissions(Set<SystemPermission> systempermissions) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(systempermissions.size()); DataOutputStream out = new DataOutputStream(bytes); try { for (SystemPermission sp : systempermissions) out.writeByte(sp.getId()); } catch (IOException e) { log.error(e, e); throw new RuntimeException(e); // this is impossible with ByteArrayOutputStream; crash hard if this happens } return bytes.toByteArray(); } public static Set<SystemPermission> convertSystemPermissions(byte[] systempermissions) { ByteArrayInputStream bytes = new ByteArrayInputStream(systempermissions); DataInputStream in = new DataInputStream(bytes); Set<SystemPermission> toReturn = new HashSet<SystemPermission>(); try { while (in.available() > 0) toReturn.add(SystemPermission.getPermissionById(in.readByte())); } catch (IOException e) { log.error("User database is corrupt; error converting system permissions", e); toReturn.clear(); } return toReturn; } public static byte[] convertTablePermissions(Set<TablePermission> tablepermissions) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(tablepermissions.size()); DataOutputStream out = new DataOutputStream(bytes); try { for (TablePermission tp : tablepermissions) out.writeByte(tp.getId()); } catch (IOException e) { log.error(e, e); throw new RuntimeException(e); // this is impossible with ByteArrayOutputStream; crash hard if this happens } return bytes.toByteArray(); } public static Set<TablePermission> convertTablePermissions(byte[] tablepermissions) { Set<TablePermission> toReturn = new HashSet<TablePermission>(); for (byte b : tablepermissions) toReturn.add(TablePermission.getPermissionById(b)); return toReturn; } } @Override public void clearCache(String user) { zooCache.clear(ZKUserPath + "/" + user); } @Override public void clearCache(String user, String tableId) { zooCache.clear(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + tableId); } }
src/server/src/main/java/org/apache/accumulo/server/security/ZKAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.server.security; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.AccumuloException; import org.apache.accumulo.core.client.AccumuloSecurityException; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.core.security.SystemPermission; import org.apache.accumulo.core.security.TablePermission; import org.apache.accumulo.core.security.thrift.AuthInfo; import org.apache.accumulo.core.security.thrift.SecurityErrorCode; import org.apache.accumulo.core.util.ByteBufferUtil; import org.apache.accumulo.core.zookeeper.ZooUtil.NodeExistsPolicy; import org.apache.accumulo.core.zookeeper.ZooUtil.NodeMissingPolicy; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.accumulo.server.zookeeper.IZooReaderWriter; import org.apache.accumulo.server.zookeeper.ZooCache; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.log4j.Logger; import org.apache.zookeeper.KeeperException; // Utility class for adding all security info into ZK public final class ZKAuthenticator implements Authenticator { private static final Logger log = Logger.getLogger(ZKAuthenticator.class); private static Authenticator zkAuthenticatorInstance = null; private static String rootUserName = null; private final String ZKUserAuths = "/Authorizations"; private final String ZKUserSysPerms = "/System"; private final String ZKUserTablePerms = "/Tables"; private final String ZKUserPath; private final ZooCache zooCache; public static synchronized Authenticator getInstance() { if (zkAuthenticatorInstance == null) zkAuthenticatorInstance = new Auditor(new ZKAuthenticator()); return zkAuthenticatorInstance; } private ZKAuthenticator() { this(HdfsZooInstance.getInstance().getInstanceID()); } public ZKAuthenticator(String instanceId) { ZKUserPath = Constants.ZROOT + "/" + instanceId + "/users"; zooCache = new ZooCache(); } /** * Authenticate a user's credentials * * @return true if username/password combination match existing user; false otherwise * @throws AccumuloSecurityException */ private boolean authenticate(AuthInfo credentials) throws AccumuloSecurityException { if (!credentials.instanceId.equals(HdfsZooInstance.getInstance().getInstanceID())) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.INVALID_INSTANCEID); if (credentials.user.equals(SecurityConstants.SYSTEM_USERNAME)) return credentials.equals(SecurityConstants.getSystemCredentials()); byte[] pass; String zpath = ZKUserPath + "/" + credentials.user; pass = zooCache.get(zpath); boolean result = Tool.checkPass(ByteBufferUtil.toBytes(credentials.password), pass); if (!result) { zooCache.clear(zpath); pass = zooCache.get(zpath); result = Tool.checkPass(ByteBufferUtil.toBytes(credentials.password), pass); } return result; } /** * Only SYSTEM user can call this method */ public void initializeSecurity(AuthInfo credentials, String rootuser, byte[] rootpass) throws AccumuloSecurityException { if (!credentials.user.equals(SecurityConstants.SYSTEM_USERNAME) || !authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); try { // remove old settings from zookeeper first, if any IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); synchronized (zooCache) { zooCache.clear(); if (zoo.exists(ZKUserPath)) { zoo.recursiveDelete(ZKUserPath, NodeMissingPolicy.SKIP); log.info("Removed " + ZKUserPath + "/" + " from zookeeper"); } // prep parent node of users with root username zoo.putPersistentData(ZKUserPath, rootuser.getBytes(), NodeExistsPolicy.FAIL); // create the root user with all system privileges, no table privileges, and no record-level authorizations Set<SystemPermission> rootPerms = new TreeSet<SystemPermission>(); for (SystemPermission p : SystemPermission.values()) rootPerms.add(p); Map<String,Set<TablePermission>> tablePerms = new HashMap<String,Set<TablePermission>>(); // Allow the root user to flush the !METADATA table tablePerms.put(Constants.METADATA_TABLE_ID, Collections.singleton(TablePermission.ALTER_TABLE)); constructUser(rootuser, Tool.createPass(rootpass), rootPerms, tablePerms, Constants.NO_AUTHS); } log.info("Initialized root user with username: " + rootuser + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new RuntimeException(e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (AccumuloException e) { log.error(e, e); throw new RuntimeException(e); } } /** * Sets up the user in ZK for the provided user. No checking for existence is done here, it should be done before calling. */ private void constructUser(String user, byte[] pass, Set<SystemPermission> sysPerms, Map<String,Set<TablePermission>> tablePerms, Authorizations auths) throws KeeperException, InterruptedException { synchronized (zooCache) { zooCache.clear(); IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); zoo.putPrivatePersistentData(ZKUserPath + "/" + user, pass, NodeExistsPolicy.FAIL); zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserAuths, Tool.convertAuthorizations(auths), NodeExistsPolicy.FAIL); zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserSysPerms, Tool.convertSystemPermissions(sysPerms), NodeExistsPolicy.FAIL); zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms, new byte[0], NodeExistsPolicy.FAIL); for (Entry<String,Set<TablePermission>> entry : tablePerms.entrySet()) createTablePerm(user, entry.getKey(), entry.getValue()); } } /** * Sets up a new table configuration for the provided user/table. No checking for existance is done here, it should be done before calling. */ private void createTablePerm(String user, String table, Set<TablePermission> perms) throws KeeperException, InterruptedException { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, Tool.convertTablePermissions(perms), NodeExistsPolicy.FAIL); } } public synchronized String getRootUsername() { if (rootUserName == null) rootUserName = new String(zooCache.get(ZKUserPath)); return rootUserName; } public boolean authenticateUser(AuthInfo credentials, String user, ByteBuffer pass) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); if (!credentials.user.equals(user) && !hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); return authenticate(new AuthInfo(user, pass, credentials.instanceId)); } public boolean authenticateUser(AuthInfo credentials, String user, byte[] pass) throws AccumuloSecurityException { return authenticateUser(credentials, user, ByteBuffer.wrap(pass)); } @Override public Set<String> listUsers(AuthInfo credentials) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); return new TreeSet<String>(zooCache.getChildren(ZKUserPath)); } /** * Creates a user with no permissions whatsoever */ public void createUser(AuthInfo credentials, String user, byte[] pass, Authorizations authorizations) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER)) { Authorizations creatorAuths = getUserAuthorizations(credentials, credentials.user); for (byte[] auth : authorizations.getAuthorizations()) if (!creatorAuths.contains(auth)) { log.info("User " + credentials.user + " attempted to create a user " + user + " with authorization " + new String(auth) + " they did not have"); throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_AUTHORIZATIONS); } } // don't allow creating a user with the same name as system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED); try { constructUser(user, Tool.createPass(pass), new TreeSet<SystemPermission>(), new HashMap<String,Set<TablePermission>>(), authorizations); log.info("Created user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); if (e.code().equals(KeeperException.Code.NODEEXISTS)) throw new AccumuloSecurityException(user, SecurityErrorCode.USER_EXISTS, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (AccumuloException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e); } } public void dropUser(AuthInfo credentials, String user) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't delete root or system users if (user.equals(getRootUsername()) || user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED); try { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().recursiveDelete(ZKUserPath + "/" + user, NodeMissingPolicy.FAIL); } log.info("Deleted user " + user + " at the request of user " + credentials.user); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (KeeperException e) { log.error(e, e); if (e.code().equals(KeeperException.Code.NONODE)) throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } } public void changePassword(AuthInfo credentials, String user, byte[] pass) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !credentials.user.equals(user)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { try { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPrivatePersistentData(ZKUserPath + "/" + user, Tool.createPass(pass), NodeExistsPolicy.OVERWRITE); } log.info("Changed password for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } catch (AccumuloException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.DEFAULT_SECURITY_ERROR, e); } } else throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } /** * Checks if a user exists */ private boolean userExists(String user) { if (zooCache.get(ZKUserPath + "/" + user) != null) return true; zooCache.clear(ZKUserPath + "/" + user); return zooCache.get(ZKUserPath + "/" + user) != null; } public void changeAuthorizations(AuthInfo credentials, String user, Authorizations authorizations) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { try { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserAuths, Tool.convertAuthorizations(authorizations), NodeExistsPolicy.OVERWRITE); } log.info("Changed authorizations for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } public Authorizations getUserAuthorizations(AuthInfo credentials, String user) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM) && !credentials.user.equals(user)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // system user doesn't need record-level authorizations for the tables it reads (for now) if (user.equals(SecurityConstants.SYSTEM_USERNAME)) return Constants.NO_AUTHS; if (userExists(user)) { byte[] authsBytes = zooCache.get(ZKUserPath + "/" + user + ZKUserAuths); if (authsBytes != null) return Tool.convertAuthorizations(authsBytes); } throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } /** * Checks if a user has a system permission * * @return true if a user exists and has permission; false otherwise */ @Override public boolean hasSystemPermission(AuthInfo credentials, String user, SystemPermission permission) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); // some people just aren't allowed to ask about other users; here are those who can ask if (!credentials.user.equals(user) && !hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM) && !hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (user.equals(getRootUsername()) || user.equals(SecurityConstants.SYSTEM_USERNAME)) return true; byte[] perms = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (perms != null) { if (Tool.convertSystemPermissions(perms).contains(permission)) return true; zooCache.clear(ZKUserPath + "/" + user + ZKUserSysPerms); return Tool.convertSystemPermissions(zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms)).contains(permission); } throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } @Override public boolean hasTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!_hasTablePermission(credentials, user, table, permission)) { zooCache.clear(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); return _hasTablePermission(credentials, user, table, permission); } return true; } private boolean _hasTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!authenticate(credentials)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.BAD_CREDENTIALS); // some people just aren't allowed to ask about other users; here are those who can ask if (!credentials.user.equals(user) && !hasSystemPermission(credentials, credentials.user, SystemPermission.SYSTEM) && !hasSystemPermission(credentials, credentials.user, SystemPermission.CREATE_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_USER)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // always allow system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) return true; // Don't let nonexistant users scan if (!userExists(user)) throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist // allow anybody to read the METADATA table if (table.equals(Constants.METADATA_TABLE_ID) && permission.equals(TablePermission.READ)) return true; byte[] serializedPerms = zooCache.get(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); if (serializedPerms != null) { return Tool.convertTablePermissions(serializedPerms).contains(permission); } return false; } @Override public void grantSystemPermission(AuthInfo credentials, String user, SystemPermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (permission.equals(SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.GRANT_INVALID); if (userExists(user)) { try { byte[] permBytes = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (permBytes == null) { throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } Set<SystemPermission> perms = Tool.convertSystemPermissions(permBytes); if (perms.add(permission)) { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserSysPerms, Tool.convertSystemPermissions(perms), NodeExistsPolicy.OVERWRITE); } } log.info("Granted system permission " + permission + " for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } @Override public void grantTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasTablePermission(credentials, credentials.user, table, TablePermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { Set<TablePermission> tablePerms; byte[] serializedPerms = zooCache.get(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); if (serializedPerms != null) tablePerms = Tool.convertTablePermissions(serializedPerms); else tablePerms = new TreeSet<TablePermission>(); try { if (tablePerms.add(permission)) { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, Tool.convertTablePermissions(tablePerms), NodeExistsPolicy.OVERWRITE); } } log.info("Granted table permission " + permission + " for user " + user + " on the table " + table + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist } @Override public void revokeSystemPermission(AuthInfo credentials, String user, SystemPermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user or revoke permissions from root user if (user.equals(SecurityConstants.SYSTEM_USERNAME) || user.equals(getRootUsername())) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (permission.equals(SystemPermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.GRANT_INVALID); if (userExists(user)) { byte[] sysPermBytes = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); if (sysPermBytes == null) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); Set<SystemPermission> sysPerms = Tool.convertSystemPermissions(sysPermBytes); try { if (sysPerms.remove(permission)) { synchronized (zooCache) { zooCache.clear(); ZooReaderWriter.getRetryingInstance().putPersistentData(ZKUserPath + "/" + user + ZKUserSysPerms, Tool.convertSystemPermissions(sysPerms), NodeExistsPolicy.OVERWRITE); } } log.info("Revoked system permission " + permission + " for user " + user + " at the request of user " + credentials.user); } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); } @Override public void revokeTablePermission(AuthInfo credentials, String user, String table, TablePermission permission) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.ALTER_USER) && !hasTablePermission(credentials, credentials.user, table, TablePermission.GRANT)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); // can't modify system user if (user.equals(SecurityConstants.SYSTEM_USERNAME)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); if (userExists(user)) { byte[] serializedPerms = zooCache.get(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table); if (serializedPerms == null) return; Set<TablePermission> tablePerms = Tool.convertTablePermissions(serializedPerms); try { if (tablePerms.remove(permission)) { zooCache.clear(); IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); if (tablePerms.size() == 0) zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, NodeMissingPolicy.SKIP); else zoo.putPersistentData(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, Tool.convertTablePermissions(tablePerms), NodeExistsPolicy.OVERWRITE); } } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } log.info("Revoked table permission " + permission + " for user " + user + " on the table " + table + " at the request of user " + credentials.user); } else throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.USER_DOESNT_EXIST); } @Override public void deleteTable(AuthInfo credentials, String table) throws AccumuloSecurityException { if (!hasSystemPermission(credentials, credentials.user, SystemPermission.DROP_TABLE) && !hasTablePermission(credentials, credentials.user, table, TablePermission.DROP_TABLE)) throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.PERMISSION_DENIED); try { synchronized (zooCache) { zooCache.clear(); IZooReaderWriter zoo = ZooReaderWriter.getRetryingInstance(); for (String user : zooCache.getChildren(ZKUserPath)) zoo.recursiveDelete(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + table, NodeMissingPolicy.SKIP); } } catch (KeeperException e) { log.error(e, e); throw new AccumuloSecurityException(credentials.user, SecurityErrorCode.CONNECTION_ERROR, e); } catch (InterruptedException e) { log.error(e, e); throw new RuntimeException(e); } } /** * All the static too methods used for this class, so that we can separate out stuff that isn't using ZooKeeper. That way, we can check the synchronization * model more easily, as we only need to check to make sure zooCache is cleared when things are written to ZooKeeper in methods that might use it. These * won't, and so don't need to be checked. */ static class Tool { private static final int SALT_LENGTH = 8; // Generates a byte array salt of length SALT_LENGTH private static byte[] generateSalt() { final SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); return salt; } private static byte[] hash(byte[] raw) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(Constants.PW_HASH_ALGORITHM); md.update(raw); return md.digest(); } public static boolean checkPass(byte[] password, byte[] zkData) { if (zkData == null) return false; byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(zkData, 0, salt, 0, SALT_LENGTH); byte[] passwordToCheck; try { passwordToCheck = convertPass(password, salt); } catch (NoSuchAlgorithmException e) { log.error("Count not create hashed password", e); return false; } return java.util.Arrays.equals(passwordToCheck, zkData); } public static byte[] createPass(byte[] password) throws AccumuloException { byte[] salt = generateSalt(); try { return convertPass(password, salt); } catch (NoSuchAlgorithmException e) { log.error("Count not create hashed password", e); throw new AccumuloException("Count not create hashed password", e); } } private static byte[] convertPass(byte[] password, byte[] salt) throws NoSuchAlgorithmException { byte[] plainSalt = new byte[password.length + SALT_LENGTH]; System.arraycopy(password, 0, plainSalt, 0, password.length); System.arraycopy(salt, 0, plainSalt, password.length, SALT_LENGTH); byte[] hashed = hash(plainSalt); byte[] saltedHash = new byte[SALT_LENGTH + hashed.length]; System.arraycopy(salt, 0, saltedHash, 0, SALT_LENGTH); System.arraycopy(hashed, 0, saltedHash, SALT_LENGTH, hashed.length); return saltedHash; // contains salt+hash(password+salt) } public static Authorizations convertAuthorizations(byte[] authorizations) { return new Authorizations(authorizations); } public static byte[] convertAuthorizations(Authorizations authorizations) { return authorizations.getAuthorizationsArray(); } public static byte[] convertSystemPermissions(Set<SystemPermission> systempermissions) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(systempermissions.size()); DataOutputStream out = new DataOutputStream(bytes); try { for (SystemPermission sp : systempermissions) out.writeByte(sp.getId()); } catch (IOException e) { log.error(e, e); throw new RuntimeException(e); // this is impossible with ByteArrayOutputStream; crash hard if this happens } return bytes.toByteArray(); } public static Set<SystemPermission> convertSystemPermissions(byte[] systempermissions) { ByteArrayInputStream bytes = new ByteArrayInputStream(systempermissions); DataInputStream in = new DataInputStream(bytes); Set<SystemPermission> toReturn = new HashSet<SystemPermission>(); try { while (in.available() > 0) toReturn.add(SystemPermission.getPermissionById(in.readByte())); } catch (IOException e) { log.error("User database is corrupt; error converting system permissions", e); toReturn.clear(); } return toReturn; } public static byte[] convertTablePermissions(Set<TablePermission> tablepermissions) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(tablepermissions.size()); DataOutputStream out = new DataOutputStream(bytes); try { for (TablePermission tp : tablepermissions) out.writeByte(tp.getId()); } catch (IOException e) { log.error(e, e); throw new RuntimeException(e); // this is impossible with ByteArrayOutputStream; crash hard if this happens } return bytes.toByteArray(); } public static Set<TablePermission> convertTablePermissions(byte[] tablepermissions) { Set<TablePermission> toReturn = new HashSet<TablePermission>(); for (byte b : tablepermissions) toReturn.add(TablePermission.getPermissionById(b)); return toReturn; } } @Override public void clearCache(String user) { zooCache.clear(ZKUserPath + "/" + user); } @Override public void clearCache(String user, String tableId) { zooCache.clear(ZKUserPath + "/" + user + ZKUserTablePerms + "/" + tableId); } }
ACCUMULO-357 small window for a node to be deleted found by the randomwalk test git-svn-id: 34b15016e43326dc17c8882923fac0cf651bfefb@1238748 13f79535-47bb-0310-9956-ffa450edef68
src/server/src/main/java/org/apache/accumulo/server/security/ZKAuthenticator.java
ACCUMULO-357 small window for a node to be deleted found by the randomwalk test
<ide><path>rc/server/src/main/java/org/apache/accumulo/server/security/ZKAuthenticator.java <ide> if (Tool.convertSystemPermissions(perms).contains(permission)) <ide> return true; <ide> zooCache.clear(ZKUserPath + "/" + user + ZKUserSysPerms); <add> perms = zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms); <add> if (perms == null) <add> return false; <ide> return Tool.convertSystemPermissions(zooCache.get(ZKUserPath + "/" + user + ZKUserSysPerms)).contains(permission); <ide> } <ide> throw new AccumuloSecurityException(user, SecurityErrorCode.USER_DOESNT_EXIST); // user doesn't exist
Java
lgpl-2.1
95faddd544b367b04100383d4744fa2d87e0677b
0
felixion/flxsmb,felixion/flxsmb,felixion/flxsmb
/* jcifs smb client library in Java * Copyright (C) 2000 "Michael B. Allen" <jcifs at samba dot org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.smb; import java.net.URLConnection; import java.net.URL; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.security.Principal; import jcifs.Config; import jcifs.util.LogStream; import jcifs.UniAddress; import jcifs.netbios.NbtAddress; import jcifs.dcerpc.*; import jcifs.dcerpc.msrpc.*; import java.util.Date; /** * This class represents a resource on an SMB network. Mainly these * resources are files and directories however an <code>SmbFile</code> * may also refer to servers and workgroups. If the resource is a file or * directory the methods of <code>SmbFile</code> follow the behavior of * the well known {@link java.io.File} class. One fundamental difference * is the usage of a URL scheme [1] to specify the target file or * directory. SmbFile URLs have the following syntax: * * <blockquote><pre> * smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value[param2=value2[...]]] * </pre></blockquote> * * This example: * * <blockquote><pre> * smb://storage15/public/foo.txt * </pre></blockquote> * * would reference the file <code>foo.txt</code> in the share * <code>public</code> on the server <code>storage15</code>. In addition * to referencing files and directories, jCIFS can also address servers, * and workgroups. * <p> * <font color="#800000"><i>Important: all SMB URLs that represent * workgroups, servers, shares, or directories require a trailing slash '/'. * </i></font> * <p> * When using the <tt>java.net.URL</tt> class with * 'smb://' URLs it is necessary to first call the static * <tt>jcifs.Config.registerSmbURLHandler();</tt> method. This is required * to register the SMB protocol handler. * <p> * The userinfo component of the SMB URL (<tt>domain;user:pass</tt>) must * be URL encoded if it contains reserved characters. According to RFC 2396 * these characters are non US-ASCII characters and most meta characters * however jCIFS will work correctly with anything but '@' which is used * to delimit the userinfo component from the server and '%' which is the * URL escape character itself. * <p> * The server * component may a traditional NetBIOS name, a DNS name, or IP * address. These name resolution mechanisms and their resolution order * can be changed (See <a href="../../../resolver.html">Setting Name * Resolution Properties</a>). The servername and path components are * not case sensitive but the domain, username, and password components * are. It is also likely that properties must be specified for jcifs * to function (See <a href="../../overview-summary.html#scp">Setting * JCIFS Properties</a>). Here are some examples of SMB URLs with brief * descriptions of what they do: * * <p>[1] This URL scheme is based largely on the <i>SMB * Filesharing URL Scheme</i> IETF draft. * * <p><table border="1" cellpadding="3" cellspacing="0" width="100%"> * <tr bgcolor="#ccccff"> * <td colspan="2"><b>SMB URL Examples</b></td> * <tr><td width="20%"><b>URL</b></td><td><b>Description</b></td></tr> * * <tr><td width="20%"><code>smb://users-nyc;miallen:mypass@angus/tmp/</code></td><td> * This URL references a share called <code>tmp</code> on the server * <code>angus</code> as user <code>miallen</code> who's password is * <code>mypass</code>. * </td></tr> * * <tr><td width="20%"> * <code>smb://Administrator:P%40ss@msmith1/c/WINDOWS/Desktop/foo.txt</code></td><td> * A relativly sophisticated example that references a file * <code>msmith1</code>'s desktop as user <code>Administrator</code>. Notice the '@' is URL encoded with the '%40' hexcode escape. * </td></tr> * * <tr><td width="20%"><code>smb://angus/</code></td><td> * This references only a server. The behavior of some methods is different * in this context(e.g. you cannot <code>delete</code> a server) however * as you might expect the <code>list</code> method will list the available * shares on this server. * </td></tr> * * <tr><td width="20%"><code>smb://myworkgroup/</code></td><td> * This syntactically is identical to the above example. However if * <code>myworkgroup</code> happends to be a workgroup(which is indeed * suggested by the name) the <code>list</code> method will return * a list of servers that have registered themselves as members of * <code>myworkgroup</code>. * </td></tr> * * <tr><td width="20%"><code>smb://</code></td><td> * Just as <code>smb://server/</code> lists shares and * <code>smb://workgroup/</code> lists servers, the <code>smb://</code> * URL lists all available workgroups on a netbios LAN. Again, * in this context many methods are not valid and return default * values(e.g. <code>isHidden</code> will always return false). * </td></tr> * * <tr><td width="20%"><code>smb://angus.foo.net/d/jcifs/pipes.doc</code></td><td> * The server name may also be a DNS name as it is in this example. See * <a href="../../../resolver.html">Setting Name Resolution Properties</a> * for details. * </td></tr> * * <tr><td width="20%"><code>smb://192.168.1.15/ADMIN$/</code></td><td> * The server name may also be an IP address. See <a * href="../../../resolver.html">Setting Name Resolution Properties</a> * for details. * </td></tr> * * <tr><td width="20%"> * <code>smb://domain;username:password@server/share/path/to/file.txt</code></td><td> * A prototypical example that uses all the fields. * </td></tr> * * <tr><td width="20%"><code>smb://myworkgroup/angus/ &lt;-- ILLEGAL </code></td><td> * Despite the hierarchial relationship between workgroups, servers, and * filesystems this example is not valid. * </td></tr> * * <tr><td width="20%"> * <code>smb://server/share/path/to/dir &lt;-- ILLEGAL </code></td><td> * URLs that represent workgroups, servers, shares, or directories require a trailing slash '/'. * </td></tr> * * <tr><td width="20%"> * <code>smb://MYGROUP/?SERVER=192.168.10.15</code></td><td> * SMB URLs support some query string parameters. In this example * the <code>SERVER</code> parameter is used to override the * server name service lookup to contact the server 192.168.10.15 * (presumably known to be a master * browser) for the server list in workgroup <code>MYGROUP</code>. * </td></tr> * * </table> * * <p>A second constructor argument may be specified to augment the URL * for better programmatic control when processing many files under * a common base. This is slightly different from the corresponding * <code>java.io.File</code> usage; a '/' at the beginning of the second * parameter will still use the server component of the first parameter. The * examples below illustrate the resulting URLs when this second contructor * argument is used. * * <p><table border="1" cellpadding="3" cellspacing="0" width="100%"> * <tr bgcolor="#ccccff"> * <td colspan="3"> * <b>Examples Of SMB URLs When Augmented With A Second Constructor Parameter</b></td> * <tr><td width="20%"> * <b>First Parameter</b></td><td><b>Second Parameter</b></td><td><b>Result</b></td></tr> * * <tr><td width="20%"><code> * smb://host/share/a/b/ * </code></td><td width="20%"><code> * c/d/ * </code></td><td><code> * smb://host/share/a/b/c/d/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/foo/bar/ * </code></td><td width="20%"><code> * /share2/zig/zag * </code></td><td><code> * smb://host/share2/zig/zag * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/foo/bar/ * </code></td><td width="20%"><code> * ../zip/ * </code></td><td><code> * smb://host/share/foo/zip/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/zig/zag * </code></td><td width="20%"><code> * smb://foo/bar/ * </code></td><td><code> * smb://foo/bar/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/foo/ * </code></td><td width="20%"><code> * ../.././.././../foo/ * </code></td><td><code> * smb://host/foo/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/zig/zag * </code></td><td width="20%"><code> * / * </code></td><td><code> * smb://host/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://server/ * </code></td><td width="20%"><code> * ../ * </code></td><td><code> * smb://server/ * </code></td></tr> * * <tr><td width="20%"><code> * smb:// * </code></td><td width="20%"><code> * myworkgroup/ * </code></td><td><code> * smb://myworkgroup/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://myworkgroup/ * </code></td><td width="20%"><code> * angus/ * </code></td><td><code> * smb://myworkgroup/angus/ &lt;-- ILLEGAL<br>(But if you first create an <tt>SmbFile</tt> with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second <tt>String</tt> parameter jCIFS will factor out the 'workgroup'.) * </code></td></tr> * * </table> * * <p>Instances of the <code>SmbFile</code> class are immutable; that is, * once created, the abstract pathname represented by an SmbFile object * will never change. * * @see java.io.File */ public class SmbFile extends URLConnection implements SmbConstants { static final int O_RDONLY = 0x01; static final int O_WRONLY = 0x02; static final int O_RDWR = 0x03; static final int O_APPEND = 0x04; // Open Function Encoding // create if the file does not exist static final int O_CREAT = 0x0010; // fail if the file exists static final int O_EXCL = 0x0020; // truncate if the file exists static final int O_TRUNC = 0x0040; // share access /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients (including other threads making calls into jCIFS) * will not be permitted to access the target file and will receive "The * file is being accessed by another process" message. */ public static final int FILE_NO_SHARE = 0x00; /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients will be permitted to read from the target file while * this file is open. This constant may be logically OR'd with other share * access flags. */ public static final int FILE_SHARE_READ = 0x01; /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients will be permitted to write to the target file while * this file is open. This constant may be logically OR'd with other share * access flags. */ public static final int FILE_SHARE_WRITE = 0x02; /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients will be permitted to delete the target file while * this file is open. This constant may be logically OR'd with other share * access flags. */ public static final int FILE_SHARE_DELETE = 0x04; // file attribute encoding /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> will be read-only */ public static final int ATTR_READONLY = 0x01; /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> will be hidden */ public static final int ATTR_HIDDEN = 0x02; /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> will be a system file */ public static final int ATTR_SYSTEM = 0x04; /** * A file with this bit on as returned by <tt>getAttributes()</tt> is * a volume */ public static final int ATTR_VOLUME = 0x08; /** * A file with this bit on as returned by <tt>getAttributes()</tt> is * a directory */ public static final int ATTR_DIRECTORY = 0x10; /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> is an archived file */ public static final int ATTR_ARCHIVE = 0x20; // extended file attribute encoding(others same as above) static final int ATTR_COMPRESSED = 0x800; static final int ATTR_NORMAL = 0x080; static final int ATTR_TEMPORARY = 0x100; static final int ATTR_GET_MASK = 0x7FFF; /* orig 0x7fff */ static final int ATTR_SET_MASK = 0x30A7; /* orig 0x0027 */ static final int DEFAULT_ATTR_EXPIRATION_PERIOD = 30000; // orig 5000; static final int HASH_DOT = ".".hashCode(); static final int HASH_DOT_DOT = "..".hashCode(); static LogStream log = LogStream.getInstance(); static long attrExpirationPeriod; static boolean ignoreCopyToException; static { try { Class.forName( "jcifs.Config" ); } catch( ClassNotFoundException cnfe ) { cnfe.printStackTrace(); } attrExpirationPeriod = Config.getLong( "jcifs.smb.client.attrExpirationPeriod", DEFAULT_ATTR_EXPIRATION_PERIOD ); ignoreCopyToException = Config.getBoolean( "jcifs.smb.client.ignoreCopyToException", true ); dfs = new Dfs(); } /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a regular file or directory. */ public static final int TYPE_FILESYSTEM = 0x01; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a workgroup. */ public static final int TYPE_WORKGROUP = 0x02; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a server. */ public static final int TYPE_SERVER = 0x04; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a share. */ public static final int TYPE_SHARE = 0x08; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a named pipe. */ public static final int TYPE_NAMED_PIPE = 0x10; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a printer. */ public static final int TYPE_PRINTER = 0x20; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a communications device. */ public static final int TYPE_COMM = 0x40; private String canon; // Initially null; set by getUncPath; dir must end with '/' private String share; // Can be null private long createTime; private long lastModified; private long lastAccessed; private long changeTime; private int attributes = 0; private long attrExpiration; private long size; private long sizeExpiration; private boolean isExists; private int shareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; private SmbComBlankResponse blank_resp = null; private DfsReferral dfsReferral = null; // For getDfsPath() and getServerWithDfs() protected static Dfs dfs; NtlmPasswordAuthentication auth; // Cannot be null SmbTree tree = null; // Initially null String unc; // Initially null; set by getUncPath; never ends with '/' int fid; // Initially 0; set by open() int type; boolean opened; int tree_num; /** * Constructs an SmbFile representing a resource on an SMB network such as * a file or directory. See the description and examples of smb URLs above. * * @param url A URL string * @throws MalformedURLException * If the <code>parent</code> and <code>child</code> parameters * do not follow the prescribed syntax */ public SmbFile( String url ) throws MalformedURLException { this( new URL( null, url, Handler.SMB_HANDLER )); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>parent SmbFile</code>. See the description above for examples * of using the second <code>name</code> parameter. * * @param context A base <code>SmbFile</code> * @param name A path string relative to the <code>parent</code> paremeter * @throws MalformedURLException * If the <code>parent</code> and <code>child</code> parameters * do not follow the prescribed syntax * @throws UnknownHostException * If the server or workgroup of the <tt>context</tt> file cannot be determined */ public SmbFile( SmbFile context, String name ) throws MalformedURLException, UnknownHostException { this( context.isWorkgroup0() ? new URL( null, "smb://" + name, Handler.SMB_HANDLER ) : new URL( context.url, name, Handler.SMB_HANDLER ), context.auth ); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>parent</code>. See the description above for examples of * using the second <code>chile</code> parameter. * * @param context A URL string * @param name A path string relative to the <code>context</code> paremeter * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( String context, String name ) throws MalformedURLException { this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER )); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. * * @param url A URL string * @param auth The credentials the client should use for authentication * @throws MalformedURLException * If the <code>url</code> parameter does not follow the prescribed syntax */ public SmbFile( String url, NtlmPasswordAuthentication auth ) throws MalformedURLException { this( new URL( null, url, Handler.SMB_HANDLER ), auth ); } /** * Constructs an SmbFile representing a file on an SMB network. The * <tt>shareAccess</tt> parameter controls what permissions other * clients have when trying to access the same file while this instance * is still open. This value is either <tt>FILE_NO_SHARE</tt> or any * combination of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, * and <tt>FILE_SHARE_DELETE</tt> logically OR'd together. * * @param url A URL string * @param auth The credentials the client should use for authentication * @param shareAccess Specifies what access other clients have while this file is open. * @throws MalformedURLException * If the <code>url</code> parameter does not follow the prescribed syntax */ public SmbFile( String url, NtlmPasswordAuthentication auth, int shareAccess ) throws MalformedURLException { this( new URL( null, url, Handler.SMB_HANDLER ), auth ); if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) { throw new RuntimeException( "Illegal shareAccess parameter" ); } this.shareAccess = shareAccess; } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>context</code>. See the description above for examples of * using the second <code>name</code> parameter. * * @param context A URL string * @param name A path string relative to the <code>context</code> paremeter * @param auth The credentials the client should use for authentication * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( String context, String name, NtlmPasswordAuthentication auth ) throws MalformedURLException { this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth ); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>context</code>. See the description above for examples of * using the second <code>name</code> parameter. The <tt>shareAccess</tt> * parameter controls what permissions other clients have when trying * to access the same file while this instance is still open. This * value is either <tt>FILE_NO_SHARE</tt> or any combination * of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and * <tt>FILE_SHARE_DELETE</tt> logically OR'd together. * * @param context A URL string * @param name A path string relative to the <code>context</code> paremeter * @param auth The credentials the client should use for authentication * @param shareAccess Specifies what access other clients have while this file is open. * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( String context, String name, NtlmPasswordAuthentication auth, int shareAccess ) throws MalformedURLException { this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth ); if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) { throw new RuntimeException( "Illegal shareAccess parameter" ); } this.shareAccess = shareAccess; } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>context</code>. See the description above for examples of * using the second <code>name</code> parameter. The <tt>shareAccess</tt> * parameter controls what permissions other clients have when trying * to access the same file while this instance is still open. This * value is either <tt>FILE_NO_SHARE</tt> or any combination * of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and * <tt>FILE_SHARE_DELETE</tt> logically OR'd together. * * @param context A base <code>SmbFile</code> * @param name A path string relative to the <code>context</code> file path * @param shareAccess Specifies what access other clients have while this file is open. * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( SmbFile context, String name, int shareAccess ) throws MalformedURLException, UnknownHostException { this( context.isWorkgroup0() ? new URL( null, "smb://" + name, Handler.SMB_HANDLER ) : new URL( context.url, name, Handler.SMB_HANDLER ), context.auth ); if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) { throw new RuntimeException( "Illegal shareAccess parameter" ); } this.shareAccess = shareAccess; } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory from a <tt>URL</tt> object. * * @param url The URL of the target resource */ public SmbFile( URL url ) { this( url, new NtlmPasswordAuthentication( url.getUserInfo() )); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory from a <tt>URL</tt> object and an * <tt>NtlmPasswordAuthentication</tt> object. * * @param url The URL of the target resource * @param auth The credentials the client should use for authentication */ public SmbFile( URL url, NtlmPasswordAuthentication auth ) { super( url ); this.auth = auth == null ? new NtlmPasswordAuthentication( url.getUserInfo() ) : auth; getUncPath0(); } SmbFile( SmbFile context, String name, int type, int attributes, long createTime, long lastModified, long lastAccessed, long size ) throws MalformedURLException, UnknownHostException { this( context.isWorkgroup0() ? new URL( null, "smb://" + name + "/", Handler.SMB_HANDLER ) : new URL( context.url, name + (( attributes & ATTR_DIRECTORY ) > 0 ? "/" : "" ))); /* why was this removed before? DFS? copyTo? Am I going around in circles? */ auth = context.auth; if( context.share != null ) { this.tree = context.tree; this.dfsReferral = context.dfsReferral; } int last = name.length() - 1; if( name.charAt( last ) == '/' ) { name = name.substring( 0, last ); } if( context.share == null ) { this.unc = "\\"; } else if( context.unc.equals( "\\" )) { this.unc = '\\' + name; } else { this.unc = context.unc + '\\' + name; } /* why? am I going around in circles? * this.type = type == TYPE_WORKGROUP ? 0 : type; */ this.type = type; this.attributes = attributes; this.createTime = createTime; // need to change constructor to get this... need to look at implications of that this.changeTime = changeTime; this.lastModified = lastModified; this.lastAccessed = lastAccessed; this.size = size; isExists = true; attrExpiration = sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; } private SmbComBlankResponse blank_resp() { if( blank_resp == null ) { blank_resp = new SmbComBlankResponse(); } return blank_resp; } void resolveDfs(ServerMessageBlock request) throws SmbException { if (request instanceof SmbComClose) return; if (request != null) request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS; return; // connect0(); // DfsReferral dr = dfs.resolve( // tree.session.transport.tconHostName, // tree.share, // unc, // auth); // if (dr != null) { // String service = null; // if (request != null) { // switch( request.command ) { // case ServerMessageBlock.SMB_COM_TRANSACTION: // case ServerMessageBlock.SMB_COM_TRANSACTION2: // switch( ((SmbComTransaction)request).subCommand & 0xFF ) { // case SmbComTransaction.TRANS2_GET_DFS_REFERRAL: // break; // default: // service = "A:"; // } // break; // default: // service = "A:"; // } // } // DfsReferral start = dr; // SmbException se = null; // do { // try { // if (log.level >= 2) // log.println("DFS redirect: " + dr); // UniAddress addr = UniAddress.getByName(dr.server); // SmbTransport trans = SmbTransport.getSmbTransport(addr, url.getPort()); // /* This is a key point. This is where we set the "tree" of this file which // * is like changing the rug out from underneath our feet. // */ // /* Technically we should also try to authenticate here but that means doing the session setup and tree connect separately. For now a simple connect will at least tell us if the host is alive. That should be sufficient for 99% of the cases. We can revisit this again for 2.0. // */ // trans.connect(); // tree = trans.getSmbSession( auth ).getSmbTree( dr.share, service ); // if (dr != start && dr.key != null) { // dr.map.put(dr.key, dr); // } // se = null; // break; // } catch (IOException ioe) { // if (ioe instanceof SmbException) { // se = (SmbException)ioe; // } else { // se = new SmbException(dr.server, ioe); // } // } // dr = dr.next; // } while (dr != start); // if (se != null) // throw se; // if (log.level >= 3) // log.println( dr ); // dfsReferral = dr; // if (dr.pathConsumed < 0) { // dr.pathConsumed = 0; // } else if (dr.pathConsumed > unc.length()) { // dr.pathConsumed = unc.length(); // } // String dunc = unc.substring(dr.pathConsumed); // if (dunc.equals("")) // dunc = "\\"; // if (!dr.path.equals("")) // dunc = "\\" + dr.path + dunc; // unc = dunc; // if (request != null && // request.path != null && // request.path.endsWith("\\") && // dunc.endsWith("\\") == false) { // dunc += "\\"; // } // if (request != null) { // request.path = dunc; // request.flags2 |= ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS; // } // } else if (tree.inDomainDfs && // !(request instanceof NtTransQuerySecurityDesc) && // !(request instanceof SmbComClose) && // !(request instanceof SmbComFindClose2)) { // throw new SmbException(NtStatus.NT_STATUS_NOT_FOUND, false); // } else { // if (request != null) // request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS; // } } void send( ServerMessageBlock request, ServerMessageBlock response ) throws SmbException { for( ;; ) { resolveDfs(request); try { tree.send( request, response ); break; } catch( DfsReferral dre ) { if( dre.resolveHashes ) { throw dre; } request.reset(); } } } static String queryLookup( String query, String param ) { char in[] = query.toCharArray(); int i, ch, st, eq; st = eq = 0; for( i = 0; i < in.length; i++) { ch = in[i]; if( ch == '&' ) { if( eq > st ) { String p = new String( in, st, eq - st ); if( p.equalsIgnoreCase( param )) { eq++; return new String( in, eq, i - eq ); } } st = i + 1; } else if( ch == '=' ) { eq = i; } } if( eq > st ) { String p = new String( in, st, eq - st ); if( p.equalsIgnoreCase( param )) { eq++; return new String( in, eq, in.length - eq ); } } return null; } UniAddress[] addresses; int addressIndex; UniAddress getAddress() throws UnknownHostException { if (addressIndex == 0) return getFirstAddress(); return addresses[addressIndex - 1]; } UniAddress getFirstAddress() throws UnknownHostException { addressIndex = 0; String host = url.getHost(); String path = url.getPath(); String query = url.getQuery(); if( query != null ) { String server = queryLookup( query, "server" ); if( server != null && server.length() > 0 ) { addresses = new UniAddress[1]; addresses[0] = UniAddress.getByName( server ); return getNextAddress(); } String address = queryLookup(query, "address"); if (address != null && address.length() > 0) { byte[] ip = java.net.InetAddress.getByName(address).getAddress(); addresses = new UniAddress[1]; addresses[0] = new UniAddress(java.net.InetAddress.getByAddress(host, ip)); return getNextAddress(); } } if (host.length() == 0) { try { NbtAddress addr = NbtAddress.getByName( NbtAddress.MASTER_BROWSER_NAME, 0x01, null); addresses = new UniAddress[1]; addresses[0] = UniAddress.getByName( addr.getHostAddress() ); } catch( UnknownHostException uhe ) { NtlmPasswordAuthentication.initDefaults(); if( NtlmPasswordAuthentication.DEFAULT_DOMAIN.equals( "?" )) { throw uhe; } addresses = UniAddress.getAllByName( NtlmPasswordAuthentication.DEFAULT_DOMAIN, true ); } } else if( path.length() == 0 || path.equals( "/" )) { addresses = UniAddress.getAllByName( host, true ); } else { addresses = UniAddress.getAllByName(host, false); } return getNextAddress(); } UniAddress getNextAddress() { UniAddress addr = null; if (addressIndex < addresses.length) addr = addresses[addressIndex++]; return addr; } boolean hasNextAddress() { return addressIndex < addresses.length; } void connect0() throws SmbException { try { connect(); } catch( UnknownHostException uhe ) { throw new SmbException( "Failed to connect to server", uhe ); } catch( SmbException se ) { throw se; } catch( IOException ioe ) { throw new SmbException( "Failed to connect to server", ioe ); } } void doConnect() throws IOException { SmbTransport trans; UniAddress addr; addr = getAddress(); if (tree != null) { trans = tree.session.transport; } else { trans = SmbTransport.getSmbTransport(addr, url.getPort()); tree = trans.getSmbSession(auth).getSmbTree(share, null); } String hostName = getServerWithDfs(); // tree.inDomainDfs = dfs.resolve(hostName, tree.share, null, auth) != null; tree.inDomainDfs = false; if (tree.inDomainDfs) { tree.connectionState = 2; } try { if( log.level >= 3 ) log.println( "doConnect: " + addr ); tree.treeConnect(null, null); } catch (SmbAuthException sae) { NtlmPasswordAuthentication a; SmbSession ssn; if (share == null) { // IPC$ - try "anonymous" credentials ssn = trans.getSmbSession(NtlmPasswordAuthentication.NULL); tree = ssn.getSmbTree(null, null); tree.treeConnect(null, null); } else if ((a = NtlmAuthenticator.requestNtlmPasswordAuthentication( url.toString(), sae)) != null) { auth = a; ssn = trans.getSmbSession(auth); tree = ssn.getSmbTree(share, null); // tree.inDomainDfs = dfs.resolve(hostName, tree.share, null, auth) != null; tree.inDomainDfs = false; if (tree.inDomainDfs) { tree.connectionState = 2; } tree.treeConnect(null, null); } else { if (log.level >= 1 && hasNextAddress()) sae.printStackTrace(log); throw sae; } } } /** * It is not necessary to call this method directly. This is the * <tt>URLConnection</tt> implementation of <tt>connect()</tt>. */ public void connect() throws IOException { SmbTransport trans; SmbSession ssn; UniAddress addr; if( isConnected() ) { return; } getUncPath0(); getFirstAddress(); for ( ;; ) { try { doConnect(); return; } catch(SmbAuthException sae) { throw sae; // Prevents account lockout on servers with multiple IPs } catch(SmbException se) { if (getNextAddress() == null) throw se; if (log.level >= 3) se.printStackTrace(log); } } } boolean isConnected() { return tree != null && tree.connectionState == 2; } int open0( int flags, int access, int attrs, int options ) throws SmbException { int f; connect0(); if( log.level >= 3 ) log.println( "open0: " + unc ); /* * NT Create AndX / Open AndX Request / Response */ if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) { SmbComNTCreateAndXResponse response = new SmbComNTCreateAndXResponse(); SmbComNTCreateAndX request = new SmbComNTCreateAndX( unc, flags, access, shareAccess, attrs, options, null ); if (this instanceof SmbNamedPipe) { request.flags0 |= 0x16; request.desiredAccess |= 0x20000; response.isExtended = true; } send( request, response ); f = response.fid; attributes = response.extFileAttributes & ATTR_GET_MASK; attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; isExists = true; } else { SmbComOpenAndXResponse response = new SmbComOpenAndXResponse(); send( new SmbComOpenAndX( unc, access, flags, null ), response ); f = response.fid; } return f; } public void open( int flags, int access, int attrs, int options ) throws SmbException { if( isOpen() ) { return; } fid = open0( flags, access, attrs, options ); opened = true; tree_num = tree.tree_num; } public boolean isOpen() { boolean ans = opened && isConnected() && tree_num == tree.tree_num; return ans; } void close( int f, long lastWriteTime ) throws SmbException { if( log.level >= 3 ) log.println( "close: " + f ); /* * Close Request / Response */ send( new SmbComClose( f, lastWriteTime ), blank_resp() ); } void close( long lastWriteTime ) throws SmbException { if( isOpen() == false ) { return; } close( fid, lastWriteTime ); opened = false; } public void close() throws SmbException { close( 0L ); } /** * Returns the <tt>NtlmPasswordAuthentication</tt> object used as * credentials with this file or pipe. This can be used to retrieve the * username for example: * <tt> * String username = f.getPrincipal().getName(); * </tt> * The <tt>Principal</tt> object returned will never be <tt>null</tt> * however the username can be <tt>null</tt> indication anonymous * credentials were used (e.g. some IPC$ services). */ public Principal getPrincipal() { return auth; } /** * Returns the last component of the target URL. This will * effectively be the name of the file or directory represented by this * <code>SmbFile</code> or in the case of URLs that only specify a server * or workgroup, the server or workgroup will be returned. The name of * the root URL <code>smb://</code> is also <code>smb://</code>. If this * <tt>SmbFile</tt> refers to a workgroup, server, share, or directory, * the name will include a trailing slash '/' so that composing new * <tt>SmbFile</tt>s will maintain the trailing slash requirement. * * @return The last component of the URL associated with this SMB * resource or <code>smb://</code> if the resource is <code>smb://</code> * itself. */ public String getName() { getUncPath0(); if( canon.length() > 1 ) { int i = canon.length() - 2; while( canon.charAt( i ) != '/' ) { i--; } return canon.substring( i + 1 ); } else if( share != null ) { return share + '/'; } else if( url.getHost().length() > 0 ) { return url.getHost() + '/'; } else { return "smb://"; } } /** * Everything but the last component of the URL representing this SMB * resource is effectivly it's parent. The root URL <code>smb://</code> * does not have a parent. In this case <code>smb://</code> is returned. * * @return The parent directory of this SMB resource or * <code>smb://</code> if the resource refers to the root of the URL * hierarchy which incedentally is also <code>smb://</code>. */ public String getParent() { String str = url.getAuthority(); if( str.length() > 0 ) { StringBuffer sb = new StringBuffer( "smb://" ); sb.append( str ); getUncPath0(); if( canon.length() > 1 ) { sb.append( canon ); } else { sb.append( '/' ); } str = sb.toString(); int i = str.length() - 2; while( str.charAt( i ) != '/' ) { i--; } return str.substring( 0, i + 1 ); } return "smb://"; } /** * Returns the full uncanonicalized URL of this SMB resource. An * <code>SmbFile</code> constructed with the result of this method will * result in an <code>SmbFile</code> that is equal to the original. * * @return The uncanonicalized full URL of this SMB resource. */ public String getPath() { return url.toString(); } String getUncPath0() { if( unc == null ) { char[] in = url.getPath().toCharArray(); char[] out = new char[in.length]; int length = in.length, i, o, state, s; /* The canonicalization routine */ state = 0; o = 0; for( i = 0; i < length; i++ ) { switch( state ) { case 0: if( in[i] != '/' ) { return null; } out[o++] = in[i]; state = 1; break; case 1: if( in[i] == '/' ) { break; } else if( in[i] == '.' && (( i + 1 ) >= length || in[i + 1] == '/' )) { i++; break; } else if(( i + 1 ) < length && in[i] == '.' && in[i + 1] == '.' && (( i + 2 ) >= length || in[i + 2] == '/' )) { i += 2; if( o == 1 ) break; do { o--; } while( o > 1 && out[o - 1] != '/' ); break; } state = 2; case 2: if( in[i] == '/' ) { state = 1; } out[o++] = in[i]; break; } } canon = new String( out, 0, o ); if( o > 1 ) { o--; i = canon.indexOf( '/', 1 ); if( i < 0 ) { share = canon.substring( 1 ); unc = "\\"; } else if( i == o ) { share = canon.substring( 1, i ); unc = "\\"; } else { share = canon.substring( 1, i ); unc = canon.substring( i, out[o] == '/' ? o : o + 1 ); unc = unc.replace( '/', '\\' ); } } else { share = null; unc = "\\"; } } return unc; } /** * Retuns the Windows UNC style path with backslashs intead of forward slashes. * * @return The UNC path. */ public String getUncPath() { getUncPath0(); if( share == null ) { return "\\\\" + url.getHost(); } return "\\\\" + url.getHost() + canon.replace( '/', '\\' ); } /** * Returns the full URL of this SMB resource with '.' and '..' components * factored out. An <code>SmbFile</code> constructed with the result of * this method will result in an <code>SmbFile</code> that is equal to * the original. * * @return The canonicalized URL of this SMB resource. */ public String getCanonicalPath() { String str = url.getAuthority(); getUncPath0(); if( str.length() > 0 ) { return "smb://" + url.getAuthority() + canon; } return "smb://"; } /** * Retrieves the share associated with this SMB resource. In * the case of <code>smb://</code>, <code>smb://workgroup/</code>, * and <code>smb://server/</code> URLs which do not specify a share, * <code>null</code> will be returned. * * @return The share component or <code>null</code> if there is no share */ public String getShare() { return share; } String getServerWithDfs() { if (dfsReferral != null) { return dfsReferral.server; } return getServer(); } /** * Retrieve the hostname of the server for this SMB resource. If this * <code>SmbFile</code> references a workgroup, the name of the workgroup * is returned. If this <code>SmbFile</code> refers to the root of this * SMB network hierarchy, <code>null</code> is returned. * * @return The server or workgroup name or <code>null</code> if this * <code>SmbFile</code> refers to the root <code>smb://</code> resource. */ public String getServer() { String str = url.getHost(); if( str.length() == 0 ) { return null; } return str; } /** * Returns type of of object this <tt>SmbFile</tt> represents. * @return <tt>TYPE_FILESYSTEM, TYPE_WORKGROUP, TYPE_SERVER, TYPE_SHARE, * TYPE_PRINTER, TYPE_NAMED_PIPE</tt>, or <tt>TYPE_COMM</tt>. */ public int getType() throws SmbException { if( type == 0 ) { if( getUncPath0().length() > 1 ) { type = TYPE_FILESYSTEM; } else if( share != null ) { // treeConnect good enough to test service type connect0(); if( share.equals( "IPC$" )) { type = TYPE_NAMED_PIPE; } else if( tree.service.equals( "LPT1:" )) { type = TYPE_PRINTER; } else if( tree.service.equals( "COMM" )) { type = TYPE_COMM; } else { type = TYPE_SHARE; } } else if( url.getAuthority() == null || url.getAuthority().length() == 0 ) { type = TYPE_WORKGROUP; } else { UniAddress addr; try { addr = getAddress(); } catch( UnknownHostException uhe ) { throw new SmbException( url.toString(), uhe ); } if( addr.getAddress() instanceof NbtAddress ) { int code = ((NbtAddress)addr.getAddress()).getNameType(); if( code == 0x1d || code == 0x1b ) { type = TYPE_WORKGROUP; return type; } } type = TYPE_SERVER; } } return type; } boolean isWorkgroup0() throws UnknownHostException { if( type == TYPE_WORKGROUP || url.getHost().length() == 0 ) { type = TYPE_WORKGROUP; return true; } else { getUncPath0(); if( share == null ) { UniAddress addr = getAddress(); if( addr.getAddress() instanceof NbtAddress ) { int code = ((NbtAddress)addr.getAddress()).getNameType(); if( code == 0x1d || code == 0x1b ) { type = TYPE_WORKGROUP; return true; } } type = TYPE_SERVER; } } return false; } Info queryPath( String path, int infoLevel ) throws SmbException { connect0(); if (log.level >= 3) log.println( "queryPath: " + path ); /* normally we'd check the negotiatedCapabilities for CAP_NT_SMBS * however I can't seem to get a good last modified time from * SMB_COM_QUERY_INFORMATION so if NT_SMBs are requested * by the server than in this case that's what it will get * regardless of what jcifs.smb.client.useNTSmbs is set * to(overrides negotiatedCapabilities). */ /* We really should do the referral before this in case * the redirected target has different capabilities. But * the way we have been doing that is to call exists() which * calls this method so another technique will be necessary * to support DFS referral _to_ Win95/98/ME. */ if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) { /* * Trans2 Query Path Information Request / Response */ Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse( infoLevel ); send( new Trans2QueryPathInformation( path, infoLevel ), response ); return response.info; } else { /* * Query Information Request / Response */ SmbComQueryInformationResponse response = new SmbComQueryInformationResponse( tree.session.transport.server.serverTimeZone * 1000 * 60L ); send( new SmbComQueryInformation( path ), response ); return response; } } /** * Tests to see if the SMB resource exists. If the resource refers * only to a server, this method determines if the server exists on the * network and is advertising SMB services. If this resource refers to * a workgroup, this method determines if the workgroup name is valid on * the local SMB network. If this <code>SmbFile</code> refers to the root * <code>smb://</code> resource <code>true</code> is always returned. If * this <code>SmbFile</code> is a traditional file or directory, it will * be queried for on the specified server as expected. * * @return <code>true</code> if the resource exists or is alive or * <code>false</code> otherwise */ public boolean exists() throws SmbException { if( attrExpiration > System.currentTimeMillis() ) { return isExists; } attributes = ATTR_READONLY | ATTR_DIRECTORY; changeTime = 0L; createTime = 0L; lastModified = 0L; lastAccessed = 0L; isExists = false; try { if( url.getHost().length() == 0 ) { } else if( share == null ) { if( getType() == TYPE_WORKGROUP ) { UniAddress.getByName( url.getHost(), true ); } else { UniAddress.getByName( url.getHost() ).getHostName(); } } else if( getUncPath0().length() == 1 || share.equalsIgnoreCase( "IPC$" )) { connect0(); // treeConnect is good enough } else { Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_ALL_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); changeTime = info.getChangeTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); size = info.getSize(); sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; } /* If any of the above fail, isExists will not be set true */ isExists = true; } catch( UnknownHostException uhe ) { } catch( SmbException se ) { switch (se.getNtStatus()) { case NtStatus.NT_STATUS_NO_SUCH_FILE: case NtStatus.NT_STATUS_OBJECT_NAME_INVALID: case NtStatus.NT_STATUS_OBJECT_NAME_NOT_FOUND: case NtStatus.NT_STATUS_OBJECT_PATH_NOT_FOUND: break; default: throw se; } } attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; return isExists; } /** * Tests to see if the file this <code>SmbFile</code> represents can be * read. Because any file, directory, or other resource can be read if it * exists, this method simply calls the <code>exists</code> method. * * @return <code>true</code> if the file is read-only */ public boolean canRead() throws SmbException { if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for reading? return true; } return exists(); // try opening and catch sharing violation? } /** * Tests to see if the file this <code>SmbFile</code> represents * exists and is not marked read-only. By default, resources are * considered to be read-only and therefore for <code>smb://</code>, * <code>smb://workgroup/</code>, and <code>smb://server/</code> resources * will be read-only. * * @return <code>true</code> if the resource exists is not marked * read-only */ public boolean canWrite() throws SmbException { if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for writing? return true; } return exists() && ( attributes & ATTR_READONLY ) == 0; } /** * Tests to see if the file this <code>SmbFile</code> represents is a directory. * * @return <code>true</code> if this <code>SmbFile</code> is a directory */ public boolean isDirectory() throws SmbException { if( getUncPath0().length() == 1 ) { return true; } if (!exists()) return false; return ( attributes & ATTR_DIRECTORY ) == ATTR_DIRECTORY; } /** * Tests to see if the file this <code>SmbFile</code> represents is not a directory. * * @return <code>true</code> if this <code>SmbFile</code> is not a directory */ public boolean isFile() throws SmbException { if( getUncPath0().length() == 1 ) { return false; } exists(); return ( attributes & ATTR_DIRECTORY ) == 0; } /** * Tests to see if the file this SmbFile represents is marked as * hidden. This method will also return true for shares with names that * end with '$' such as <code>IPC$</code> or <code>C$</code>. * * @return <code>true</code> if the <code>SmbFile</code> is marked as being hidden */ public boolean isHidden() throws SmbException { if( share == null ) { return false; } else if( getUncPath0().length() == 1 ) { if( share.endsWith( "$" )) { return true; } return false; } exists(); return ( attributes & ATTR_HIDDEN ) == ATTR_HIDDEN; } /** * If the path of this <code>SmbFile</code> falls within a DFS volume, * this method will return the referral path to which it maps. Otherwise * <code>null</code> is returned. */ public String getDfsPath() throws SmbException { resolveDfs(null); if( dfsReferral == null ) { return null; } String path = "smb:/" + dfsReferral.server + "/" + dfsReferral.share + unc; path = path.replace( '\\', '/' ); if (isDirectory()) { path += '/'; } return path; } /** * Retrieve the time this <code>SmbFile</code> was created. The value * returned is suitable for constructing a {@link java.util.Date} object * (i.e. seconds since Epoch 1970). Times should be the same as those * reported using the properties dialog of the Windows Explorer program. * * For Win95/98/Me this is actually the last write time. It is currently * not possible to retrieve the create time from files on these systems. * * @return The number of milliseconds since the 00:00:00 GMT, January 1, * 1970 as a <code>long</code> value */ public long createTime() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return createTime; } return 0L; } public long changeTime() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return changeTime; } return 0L; } /** * Retrieve the last time the file represented by this * <code>SmbFile</code> was modified. The value returned is suitable for * constructing a {@link java.util.Date} object (i.e. seconds since Epoch * 1970). Times should be the same as those reported using the properties * dialog of the Windows Explorer program. * * @return The number of milliseconds since the 00:00:00 GMT, January 1, * 1970 as a <code>long</code> value */ public long lastModified() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return lastModified; } return 0L; } /** * Retrieve the last time the file represented by this * <code>SmbFile</code> was accessed. The value returned is suitable for * constructing a {@link java.util.Date} object (i.e. seconds since Epoch * 1970). Times should be the same as those reported using the properties * dialog of the Windows Explorer program. * * @return The number of milliseconds since the 00:00:00 GMT, January 1, * 1970 as a <code>long</code> value */ public long lastAccessed() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return lastAccessed; } return 0L; } /** * List the contents of this SMB resource. The list returned by this * method will be; * * <ul> * <li> files and directories contained within this resource if the * resource is a normal disk file directory, * <li> all available NetBIOS workgroups or domains if this resource is * the top level URL <code>smb://</code>, * <li> all servers registered as members of a NetBIOS workgroup if this * resource refers to a workgroup in a <code>smb://workgroup/</code> URL, * <li> all browseable shares of a server including printers, IPC * services, or disk volumes if this resource is a server URL in the form * <code>smb://server/</code>, * <li> or <code>null</code> if the resource cannot be resolved. * </ul> * * @return A <code>String[]</code> array of files and directories, * workgroups, servers, or shares depending on the context of the * resource URL */ public String[] list() throws SmbException { return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); } /** * List the contents of this SMB resource. The list returned will be * identical to the list returned by the parameterless <code>list()</code> * method minus filenames filtered by the specified filter. * * @param filter a filename filter to exclude filenames from the results * @throws SmbException # @return An array of filenames */ public String[] list( SmbFilenameFilter filter ) throws SmbException { return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null ); } /** * List the contents of this SMB resource as an array of * <code>SmbFile</code> objects. This method is much more efficient than * the regular <code>list</code> method when querying attributes of each * file in the result set. * <p> * The list of <code>SmbFile</code>s returned by this method will be; * * <ul> * <li> files and directories contained within this resource if the * resource is a normal disk file directory, * <li> all available NetBIOS workgroups or domains if this resource is * the top level URL <code>smb://</code>, * <li> all servers registered as members of a NetBIOS workgroup if this * resource refers to a workgroup in a <code>smb://workgroup/</code> URL, * <li> all browseable shares of a server including printers, IPC * services, or disk volumes if this resource is a server URL in the form * <code>smb://server/</code>, * <li> or <code>null</code> if the resource cannot be resolved. * </ul> * * @return An array of <code>SmbFile</code> objects representing file * and directories, workgroups, servers, or shares depending on the context * of the resource URL */ public SmbFile[] listFiles() throws SmbException { return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); } /** * The CIFS protocol provides for DOS "wildcards" to be used as * a performance enhancement. The client does not have to filter * the names and the server does not have to return all directory * entries. * <p> * The wildcard expression may consist of two special meta * characters in addition to the normal filename characters. The '*' * character matches any number of characters in part of a name. If * the expression begins with one or more '?'s then exactly that * many characters will be matched whereas if it ends with '?'s * it will match that many characters <i>or less</i>. * <p> * Wildcard expressions will not filter workgroup names or server names. * * <blockquote><pre> * winnt> ls c?o* * clock.avi -rw-- 82944 Mon Oct 14 1996 1:38 AM * Cookies drw-- 0 Fri Nov 13 1998 9:42 PM * 2 items in 5ms * </pre></blockquote> * * @param wildcard a wildcard expression * @throws SmbException * @return An array of <code>SmbFile</code> objects representing file * and directories, workgroups, servers, or shares depending on the context * of the resource URL */ public SmbFile[] listFiles( String wildcard ) throws SmbException { return listFiles( wildcard, ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); } /** * List the contents of this SMB resource. The list returned will be * identical to the list returned by the parameterless <code>listFiles()</code> * method minus files filtered by the specified filename filter. * * @param filter a filter to exclude files from the results * @return An array of <tt>SmbFile</tt> objects * @throws SmbException */ public SmbFile[] listFiles( SmbFilenameFilter filter ) throws SmbException { return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null ); } /** * List the contents of this SMB resource. The list returned will be * identical to the list returned by the parameterless <code>listFiles()</code> * method minus filenames filtered by the specified filter. * * @param filter a file filter to exclude files from the results * @return An array of <tt>SmbFile</tt> objects */ public SmbFile[] listFiles( SmbFileFilter filter ) throws SmbException { return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, filter ); } String[] list( String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException { ArrayList list = new ArrayList(); doEnum(list, false, wildcard, searchAttributes, fnf, ff); return (String[])list.toArray(new String[list.size()]); } SmbFile[] listFiles( String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException { ArrayList list = new ArrayList(); doEnum(list, true, wildcard, searchAttributes, fnf, ff); return (SmbFile[])list.toArray(new SmbFile[list.size()]); } void doEnum(ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff) throws SmbException { if (ff != null && ff instanceof DosFileFilter) { DosFileFilter dff = (DosFileFilter)ff; if (dff.wildcard != null) wildcard = dff.wildcard; searchAttributes = dff.attributes; } try { int hostlen = url.getHost().length(); if (hostlen == 0 || getType() == TYPE_WORKGROUP) { doNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff); } else if (share == null) { doShareEnum(list, files, wildcard, searchAttributes, fnf, ff); } else { doFindFirstNext(list, files, wildcard, searchAttributes, fnf, ff); } } catch (UnknownHostException uhe) { throw new SmbException(url.toString(), uhe); } catch (MalformedURLException mue) { throw new SmbException(url.toString(), mue); } } void doShareEnum(ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff) throws SmbException, UnknownHostException, MalformedURLException { String p = url.getPath(); IOException last = null; FileEntry[] entries; UniAddress addr; FileEntry e; HashMap map; if (p.lastIndexOf('/') != (p.length() - 1)) throw new SmbException(url.toString() + " directory must end with '/'"); if (getType() != TYPE_SERVER) throw new SmbException("The requested list operations is invalid: " + url.toString()); map = new HashMap(); if (dfs.isTrustedDomain(getServer(), auth)) { /* The server name is actually the name of a trusted * domain. Add DFS roots to the list. */ try { entries = doDfsRootEnum(); for (int ei = 0; ei < entries.length; ei++) { e = entries[ei]; if (map.containsKey(e) == false) map.put(e, e); } } catch (IOException ioe) { if (log.level >= 4) ioe.printStackTrace(log); } } addr = getFirstAddress(); while (addr != null) { try { doConnect(); try { entries = doMsrpcShareEnum(); } catch(IOException ioe) { if (log.level >= 3) ioe.printStackTrace(log); entries = doNetShareEnum(); } for (int ei = 0; ei < entries.length; ei++) { e = entries[ei]; if (map.containsKey(e) == false) map.put(e, e); } break; } catch(IOException ioe) { if (log.level >= 3) ioe.printStackTrace(log); last = ioe; } addr = getNextAddress(); } if (last != null && map.isEmpty()) { if (last instanceof SmbException == false) throw new SmbException(url.toString(), last); throw (SmbException)last; } Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { e = (FileEntry)iter.next(); String name = e.getName(); if (fnf != null && fnf.accept(this, name) == false) continue; if (name.length() > 0) { // if !files we don't need to create SmbFiles here SmbFile f = new SmbFile(this, name, e.getType(), ATTR_READONLY | ATTR_DIRECTORY, 0L, 0L, 0L, 0L ); if (ff != null && ff.accept(f) == false) continue; if (files) { list.add(f); } else { list.add(name); } } } } FileEntry[] doDfsRootEnum() throws IOException { MsrpcDfsRootEnum rpc; DcerpcHandle handle = null; FileEntry[] entries; handle = DcerpcHandle.getHandle("ncacn_np:" + getAddress().getHostAddress() + "[\\PIPE\\netdfs]", auth); try { rpc = new MsrpcDfsRootEnum(getServer()); handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); return rpc.getEntries(); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 4) ioe.printStackTrace(log); } } } FileEntry[] doMsrpcShareEnum() throws IOException { MsrpcShareEnum rpc; DcerpcHandle handle; rpc = new MsrpcShareEnum(url.getHost()); /* JCIFS will build a composite list of shares if the target host has * multiple IP addresses such as when domain-based DFS is in play. Because * of this, to ensure that we query each IP individually without re-resolving * the hostname and getting a different IP, we must use the current addresses * IP rather than just url.getHost() like we were using prior to 1.2.16. */ handle = DcerpcHandle.getHandle("ncacn_np:" + getAddress().getHostAddress() + "[\\PIPE\\srvsvc]", auth); try { handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); return rpc.getEntries(); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 4) ioe.printStackTrace(log); } } } FileEntry[] doNetShareEnum() throws SmbException { SmbComTransaction req = new NetShareEnum(); SmbComTransactionResponse resp = new NetShareEnumResponse(); send(req, resp); if (resp.status != SmbException.ERROR_SUCCESS) throw new SmbException(resp.status, true); return resp.results; } void doNetServerEnum(ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff) throws SmbException, UnknownHostException, MalformedURLException { int listType = url.getHost().length() == 0 ? 0 : getType(); SmbComTransaction req; SmbComTransactionResponse resp; if (listType == 0) { connect0(); req = new NetServerEnum2(tree.session.transport.server.oemDomainName, NetServerEnum2.SV_TYPE_DOMAIN_ENUM ); resp = new NetServerEnum2Response(); } else if (listType == TYPE_WORKGROUP) { req = new NetServerEnum2(url.getHost(), NetServerEnum2.SV_TYPE_ALL); resp = new NetServerEnum2Response(); } else { throw new SmbException( "The requested list operations is invalid: " + url.toString() ); } boolean more; do { int n; send(req, resp); if (resp.status != SmbException.ERROR_SUCCESS && resp.status != SmbException.ERROR_MORE_DATA) { throw new SmbException( resp.status, true ); } more = resp.status == SmbException.ERROR_MORE_DATA; n = more ? resp.numEntries - 1 : resp.numEntries; for (int i = 0; i < n; i++) { FileEntry e = resp.results[i]; String name = e.getName(); if (fnf != null && fnf.accept(this, name) == false) continue; if (name.length() > 0) { // if !files we don't need to create SmbFiles here SmbFile f = new SmbFile(this, name, e.getType(), ATTR_READONLY | ATTR_DIRECTORY, 0L, 0L, 0L, 0L ); if (ff != null && ff.accept(f) == false) continue; if (files) { list.add(f); } else { list.add(name); } } } if (getType() != TYPE_WORKGROUP) { break; } req.subCommand = (byte)SmbComTransaction.NET_SERVER_ENUM3; req.reset(0, ((NetServerEnum2Response)resp).lastName); resp.reset(); } while(more); } void doFindFirstNext( ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException, UnknownHostException, MalformedURLException { SmbComTransaction req; Trans2FindFirst2Response resp; int sid; String path = getUncPath0(); String p = url.getPath(); if( p.lastIndexOf( '/' ) != ( p.length() - 1 )) { throw new SmbException( url.toString() + " directory must end with '/'" ); } req = new Trans2FindFirst2( path, wildcard, searchAttributes ); resp = new Trans2FindFirst2Response(); if( log.level >= 3 ) log.println( "doFindFirstNext: " + req.path ); send( req, resp ); sid = resp.sid; req = new Trans2FindNext2( sid, resp.resumeKey, resp.lastName ); /* The only difference between first2 and next2 responses is subCommand * so let's recycle the response object. */ resp.subCommand = SmbComTransaction.TRANS2_FIND_NEXT2; for( ;; ) { for( int i = 0; i < resp.numEntries; i++ ) { FileEntry e = resp.results[i]; String name = e.getName(); if( name.length() < 3 ) { int h = name.hashCode(); if( h == HASH_DOT || h == HASH_DOT_DOT ) { if (name.equals(".") || name.equals("..")) continue; } } if( fnf != null && fnf.accept( this, name ) == false ) { continue; } if( name.length() > 0 ) { SmbFile f = new SmbFile( this, name, TYPE_FILESYSTEM, e.getAttributes(), e.createTime(), e.lastModified(), e.lastAccessed(), e.length() ); if( ff != null && ff.accept( f ) == false ) { continue; } if( files ) { list.add( f ); } else { list.add( name ); } } } if( resp.isEndOfSearch || resp.numEntries == 0 ) { break; } req.reset( resp.resumeKey, resp.lastName ); resp.reset(); send( req, resp ); } try { send( new SmbComFindClose2( sid ), blank_resp() ); } catch (SmbException se) { if( log.level >= 4 ) se.printStackTrace( log ); } } /** * Changes the name of the file this <code>SmbFile</code> represents to the name * designated by the <code>SmbFile</code> argument. * <p/> * <i>Remember: <code>SmbFile</code>s are immutible and therefore * the path associated with this <code>SmbFile</code> object will not * change). To access the renamed file it is necessary to construct a * new <tt>SmbFile</tt></i>. * * @param dest An <code>SmbFile</code> that represents the new pathname * @throws NullPointerException * If the <code>dest</code> argument is <code>null</code> */ public void renameTo( SmbFile dest ) throws SmbException { if( getUncPath0().length() == 1 || dest.getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } resolveDfs(null); dest.resolveDfs(null); /* * This check is to determine whether we are renaming a file to a * destination path that's not in the current session. We're modifying * it to ignore the case when the destination file has no session, * because if you skip DFS resolution (previous step) the session * won't be established. */ if (!tree.equals(dest.tree) && dest.tree != null) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } if( log.level >= 3 ) log.println( "renameTo: " + unc + " -> " + dest.unc ); attrExpiration = sizeExpiration = 0; dest.attrExpiration = 0; /* * Rename Request / Response */ send( new SmbComRename( unc, dest.unc ), blank_resp() ); } class WriterThread extends Thread { byte[] b; int n; long off; boolean ready; SmbFile dest; SmbException e = null; boolean useNTSmbs; SmbComWriteAndX reqx; SmbComWrite req; ServerMessageBlock resp; WriterThread() throws SmbException { super( "JCIFS-WriterThread" ); useNTSmbs = tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS ); if( useNTSmbs ) { reqx = new SmbComWriteAndX(); resp = new SmbComWriteAndXResponse(); } else { req = new SmbComWrite(); resp = new SmbComWriteResponse(); } ready = false; } synchronized void write( byte[] b, int n, SmbFile dest, long off ) { this.b = b; this.n = n; this.dest = dest; this.off = off; ready = false; notify(); } public void run() { synchronized( this ) { try { for( ;; ) { notify(); ready = true; while( ready ) { wait(); } if( n == -1 ) { return; } if( useNTSmbs ) { reqx.setParam( dest.fid, off, n, b, 0, n ); dest.send( reqx, resp ); } else { req.setParam( dest.fid, off, n, b, 0, n ); dest.send( req, resp ); } } } catch( SmbException e ) { this.e = e; } catch( Exception x ) { this.e = new SmbException( "WriterThread", x ); } notify(); } } } void copyTo0( SmbFile dest, byte[][] b, int bsize, WriterThread w, SmbComReadAndX req, SmbComReadAndXResponse resp ) throws SmbException { int i; if( attrExpiration < System.currentTimeMillis() ) { attributes = ATTR_READONLY | ATTR_DIRECTORY; createTime = 0L; lastModified = 0L; isExists = false; Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); /* If any of the above fails, isExists will not be set true */ isExists = true; attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; } if( isDirectory() ) { SmbFile[] files; SmbFile ndest; String path = dest.getUncPath0(); if( path.length() > 1 ) { try { dest.mkdir(); dest.setPathInformation( attributes, createTime, lastModified ); } catch( SmbException se ) { if( se.getNtStatus() != NtStatus.NT_STATUS_ACCESS_DENIED && se.getNtStatus() != NtStatus.NT_STATUS_OBJECT_NAME_COLLISION ) { throw se; } } } files = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); try { for( i = 0; i < files.length; i++ ) { ndest = new SmbFile( dest, files[i].getName(), files[i].type, files[i].attributes, files[i].createTime, files[i].lastModified, files[i].lastAccessed, files[i].size ); files[i].copyTo0( ndest, b, bsize, w, req, resp ); } } catch( UnknownHostException uhe ) { throw new SmbException( url.toString(), uhe ); } catch( MalformedURLException mue ) { throw new SmbException( url.toString(), mue ); } } else { long off; try { open( SmbFile.O_RDONLY, 0, ATTR_NORMAL, 0 ); try { dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC, FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES, attributes, 0 ); } catch( SmbAuthException sae ) { if(( dest.attributes & ATTR_READONLY ) != 0 ) { /* Remove READONLY and try again */ dest.setPathInformation( dest.attributes & ~ATTR_READONLY, 0L, 0L ); dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC, FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES, attributes, 0 ); } else { throw sae; } } i = 0; off = 0L; for( ;; ) { req.setParam( fid, off, bsize ); resp.setParam( b[i], 0 ); send( req, resp ); synchronized( w ) { if( w.e != null ) { throw w.e; } while( !w.ready ) { try { w.wait(); } catch( InterruptedException ie ) { throw new SmbException( dest.url.toString(), ie ); } } if( w.e != null ) { throw w.e; } if( resp.dataLength <= 0 ) { break; } w.write( b[i], resp.dataLength, dest, off ); } i = i == 1 ? 0 : 1; off += resp.dataLength; } dest.send( new Trans2SetFileInformation( dest.fid, attributes, createTime, lastModified ), new Trans2SetFileInformationResponse() ); dest.close( 0L ); } catch( SmbException se ) { if (ignoreCopyToException == false) throw new SmbException("Failed to copy file from [" + this.toString() + "] to [" + dest.toString() + "]", se); if( log.level > 1 ) se.printStackTrace( log ); } finally { close(); } } } /** * This method will copy the file or directory represented by this * <tt>SmbFile</tt> and it's sub-contents to the location specified by the * <tt>dest</tt> parameter. This file and the destination file do not * need to be on the same host. This operation does not copy extended * file attibutes such as ACLs but it does copy regular attributes as * well as create and last write times. This method is almost twice as * efficient as manually copying as it employs an additional write * thread to read and write data concurrently. * <p/> * It is not possible (nor meaningful) to copy entire workgroups or * servers. * * @param dest the destination file or directory * @throws SmbException */ public void copyTo( SmbFile dest ) throws SmbException { SmbComReadAndX req; SmbComReadAndXResponse resp; WriterThread w; int bsize; byte[][] b; /* Should be able to copy an entire share actually */ if( share == null || dest.share == null) { throw new SmbException( "Invalid operation for workgroups or servers" ); } req = new SmbComReadAndX(); resp = new SmbComReadAndXResponse(); connect0(); dest.connect0(); /* At this point the maxBufferSize values are from the server * exporting the volumes, not the one that we will actually * end up performing IO with. If the server hosting the * actual files has a smaller maxBufSize this could be * incorrect. To handle this properly it is necessary * to redirect the tree to the target server first before * establishing buffer size. These exists() calls facilitate * that. */ resolveDfs(null); /* It is invalid for the source path to be a child of the destination * path or visa versa. */ try { if (getAddress().equals( dest.getAddress() ) && canon.regionMatches( true, 0, dest.canon, 0, Math.min( canon.length(), dest.canon.length() ))) { throw new SmbException( "Source and destination paths overlap." ); } } catch (UnknownHostException uhe) { } w = new WriterThread(); w.setDaemon( true ); w.start(); /* Downgrade one transport to the lower of the negotiated buffer sizes * so we can just send whatever is received. */ SmbTransport t1 = tree.session.transport; SmbTransport t2 = dest.tree.session.transport; if( t1.snd_buf_size < t2.snd_buf_size ) { t2.snd_buf_size = t1.snd_buf_size; } else { t1.snd_buf_size = t2.snd_buf_size; } bsize = Math.min( t1.rcv_buf_size - 70, t1.snd_buf_size - 70 ); b = new byte[2][bsize]; try { copyTo0( dest, b, bsize, w, req, resp ); } finally { w.write( null, -1, null, 0 ); } } /** * This method will delete the file or directory specified by this * <code>SmbFile</code>. If the target is a directory, the contents of * the directory will be deleted as well. If a file within the directory or * it's sub-directories is marked read-only, the read-only status will * be removed and the file will be deleted. * * @throws SmbException */ public void delete() throws SmbException { exists(); getUncPath0(); delete( unc ); } void delete( String fileName ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } if( System.currentTimeMillis() > attrExpiration ) { attributes = ATTR_READONLY | ATTR_DIRECTORY; createTime = 0L; lastModified = 0L; isExists = false; Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; isExists = true; } if(( attributes & ATTR_READONLY ) != 0 ) { setReadWrite(); } /* * Delete or Delete Directory Request / Response */ if( log.level >= 3 ) log.println( "delete: " + fileName ); if(( attributes & ATTR_DIRECTORY ) != 0 ) { /* Recursively delete directory contents */ try { SmbFile[] l = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); for( int i = 0; i < l.length; i++ ) { l[i].delete(); } } catch( SmbException se ) { /* Oracle FilesOnline version 9.0.4 doesn't send '.' and '..' so * listFiles may generate undesireable "cannot find * the file specified". */ if( se.getNtStatus() != SmbException.NT_STATUS_NO_SUCH_FILE ) { throw se; } } send( new SmbComDeleteDirectory( fileName ), blank_resp() ); } else { send( new SmbComDelete( fileName ), blank_resp() ); } attrExpiration = sizeExpiration = 0; } /** * Returns the length of this <tt>SmbFile</tt> in bytes. If this object * is a <tt>TYPE_SHARE</tt> the total capacity of the disk shared in * bytes is returned. If this object is a directory or a type other than * <tt>TYPE_SHARE</tt>, 0L is returned. * * @return The length of the file in bytes or 0 if this * <code>SmbFile</code> is not a file. * @throws SmbException */ public long length() throws SmbException { if( attrExpiration > System.currentTimeMillis() ) { return size; } if( getType() == TYPE_SHARE ) { Trans2QueryFSInformationResponse response; int level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION; response = new Trans2QueryFSInformationResponse( level ); send( new Trans2QueryFSInformation( level ), response ); size = response.info.getCapacity(); } else if( getUncPath0().length() > 1 && type != TYPE_NAMED_PIPE ) { Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_ALL_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); changeTime = info.getChangeTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; size = info.getSize(); } else { size = 0L; } sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; return size; } /** * This method returns the free disk space in bytes of the drive this share * represents or the drive on which the directory or file resides. Objects * other than <tt>TYPE_SHARE</tt> or <tt>TYPE_FILESYSTEM</tt> will result * in 0L being returned. * * @return the free disk space in bytes of the drive on which this file or * directory resides */ public long getDiskFreeSpace() throws SmbException { if( getType() == TYPE_SHARE || type == TYPE_FILESYSTEM ) { int level = Trans2QueryFSInformationResponse.SMB_FS_FULL_SIZE_INFORMATION; try { return queryFSInformation(level); } catch( SmbException ex ) { switch (ex.getNtStatus()) { case NtStatus.NT_STATUS_INVALID_INFO_CLASS: case NtStatus.NT_STATUS_UNSUCCESSFUL: // NetApp Filer // SMB_FS_FULL_SIZE_INFORMATION not supported by the server. level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION; return queryFSInformation(level); } throw ex; } } return 0L; } private long queryFSInformation( int level ) throws SmbException { Trans2QueryFSInformationResponse response; response = new Trans2QueryFSInformationResponse( level ); send( new Trans2QueryFSInformation( level ), response ); if( type == TYPE_SHARE ) { size = response.info.getCapacity(); sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; } return response.info.getFree(); } /** * Creates a directory with the path specified by this * <code>SmbFile</code>. For this method to be successful, the target * must not already exist. This method will fail when * used with <code>smb://</code>, <code>smb://workgroup/</code>, * <code>smb://server/</code>, or <code>smb://server/share/</code> URLs * because workgroups, servers, and shares cannot be dynamically created * (although in the future it may be possible to create shares). * * @throws SmbException */ public void mkdir() throws SmbException { String path = getUncPath0(); if( path.length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } /* * Create Directory Request / Response */ if( log.level >= 3 ) log.println( "mkdir: " + path ); send( new SmbComCreateDirectory( path ), blank_resp() ); attrExpiration = sizeExpiration = 0; } /** * Creates a directory with the path specified by this <tt>SmbFile</tt> * and any parent directories that do not exist. This method will fail * when used with <code>smb://</code>, <code>smb://workgroup/</code>, * <code>smb://server/</code>, or <code>smb://server/share/</code> URLs * because workgroups, servers, and shares cannot be dynamically created * (although in the future it may be possible to create shares). * * @throws SmbException */ public void mkdirs() throws SmbException { SmbFile parent; try { parent = new SmbFile( getParent(), auth ); } catch( IOException ioe ) { return; } if( parent.exists() == false ) { parent.mkdirs(); } mkdir(); } /** * Create a new file but fail if it already exists. The check for * existance of the file and it's creation are an atomic operation with * respect to other filesystem activities. */ public void createNewFile() throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } close( open0( O_RDWR | O_CREAT | O_EXCL, 0, ATTR_NORMAL, 0 ), 0L ); } void setPathInformation( int attrs, long ctime, long mtime ) throws SmbException { int f, dir; exists(); if (attrs == 0) { // not setting attributes.. so default it to what we currently have dir = attributes; } else { dir = attributes & ATTR_DIRECTORY; } f = open0( O_RDONLY, FILE_WRITE_ATTRIBUTES, dir, dir != 0 ? 0x0001 : 0x0040 ); send( new Trans2SetFileInformation( f, attrs | dir, ctime, mtime ), new Trans2SetFileInformationResponse() ); close( f, 0L ); attrExpiration = 0; } void setPathInformation( int attrs, long ctime, long atime, long mtime ) throws SmbException { int f, dir; exists(); if (attrs == 0) { // not setting attributes.. so default it to what we currently have dir = attributes; } else { dir = attributes & ATTR_DIRECTORY; } f = open0( O_RDONLY, FILE_WRITE_ATTRIBUTES, dir & ATTR_DIRECTORY, (dir & ATTR_DIRECTORY) != 0 ? 0x0001 : 0x0040 ); send( new Trans2SetFileInformation( f, attrs | dir, ctime, atime, mtime ), new Trans2SetFileInformationResponse() ); close( f, 0L ); attrExpiration = 0; } public void setTimes( long ctime, long atime, long mtime ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, ctime, atime, mtime ); } /** * Set the create time of the file. The time is specified as milliseconds * from Jan 1, 1970 which is the same as that which is returned by the * <tt>createTime()</tt> method. * <p/> * This method does not apply to workgroups, servers, or shares. * * @param time the create time as milliseconds since Jan 1, 1970 */ public void setCreateTime( long time ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, time, 0L ); } /** * Set the access time of the file. The time is specified as milliseconds * from Jan 1, 1970 which is the same as that which is returned by the * <tt>createTime()</tt> method. * <p/> * This method does not apply to workgroups, servers, or shares. * * @param time the create time as milliseconds since Jan 1, 1970 */ public void setAccessTime( long time ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, 0L, time, 0L ); } /** * Set the last modified time of the file. The time is specified as milliseconds * from Jan 1, 1970 which is the same as that which is returned by the * <tt>lastModified()</tt>, <tt>getLastModified()</tt>, and <tt>getDate()</tt> methods. * <p/> * This method does not apply to workgroups, servers, or shares. * * @param time the last modified time as milliseconds since Jan 1, 1970 */ public void setLastModified( long time ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, 0L, time ); } /** * Return the attributes of this file. Attributes are represented as a * bitset that must be masked with <tt>ATTR_*</tt> constants to determine * if they are set or unset. The value returned is suitable for use with * the <tt>setAttributes()</tt> method. * * @return the <tt>ATTR_*</tt> attributes associated with this file * @throws SmbException */ public int getAttributes() throws SmbException { if( getUncPath0().length() == 1 ) { return 0; } exists(); return attributes & ATTR_GET_MASK; } /** * Set the attributes of this file. Attributes are composed into a * bitset by bitwise ORing the <tt>ATTR_*</tt> constants. Setting the * value returned by <tt>getAttributes</tt> will result in both files * having the same attributes. * @throws SmbException */ public void setAttributes( int attrs ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( attrs & ATTR_SET_MASK, 0L, 0L ); } /** * Make this file read-only. This is shorthand for <tt>setAttributes( * getAttributes() | ATTR_READ_ONLY )</tt>. * * @throws SmbException */ public void setReadOnly() throws SmbException { setAttributes( getAttributes() | ATTR_READONLY ); } /** * Turn off the read-only attribute of this file. This is shorthand for * <tt>setAttributes( getAttributes() & ~ATTR_READONLY )</tt>. * * @throws SmbException */ public void setReadWrite() throws SmbException { setAttributes( getAttributes() & ~ATTR_READONLY ); } /** * Returns a {@link java.net.URL} for this <code>SmbFile</code>. The * <code>URL</code> may be used as any other <code>URL</code> might to * access an SMB resource. Currently only retrieving data and information * is supported (i.e. no <tt>doOutput</tt>). * * @deprecated Use getURL() instead * @return A new <code>{@link java.net.URL}</code> for this <code>SmbFile</code> * @throws MalformedURLException */ public URL toURL() throws MalformedURLException { return url; } /** * Computes a hashCode for this file based on the URL string and IP * address if the server. The hashing function uses the hashcode of the * server address, the canonical representation of the URL, and does not * compare authentication information. In essance, two * <code>SmbFile</code> objects that refer to * the same file should generate the same hashcode provided it is possible * to make such a determination. * * @return A hashcode for this abstract file * @throws SmbException */ public int hashCode() { int hash; try { hash = getAddress().hashCode(); } catch( UnknownHostException uhe ) { hash = getServer().toUpperCase().hashCode(); } getUncPath0(); return hash + canon.toUpperCase().hashCode(); } protected boolean pathNamesPossiblyEqual(String path1, String path2) { int p1, p2, l1, l2; // if unsure return this method returns true p1 = path1.lastIndexOf('/'); p2 = path2.lastIndexOf('/'); l1 = path1.length() - p1; l2 = path2.length() - p2; // anything with dots voids comparison if (l1 > 1 && path1.charAt(p1 + 1) == '.') return true; if (l2 > 1 && path2.charAt(p2 + 1) == '.') return true; return l1 == l2 && path1.regionMatches(true, p1, path2, p2, l1); } /** * Tests to see if two <code>SmbFile</code> objects are equal. Two * SmbFile objects are equal when they reference the same SMB * resource. More specifically, two <code>SmbFile</code> objects are * equals if their server IP addresses are equal and the canonicalized * representation of their URLs, minus authentication parameters, are * case insensitivly and lexographically equal. * <p/> * For example, assuming the server <code>angus</code> resolves to the * <code>192.168.1.15</code> IP address, the below URLs would result in * <code>SmbFile</code>s that are equal. * * <p><blockquote><pre> * smb://192.168.1.15/share/DIR/foo.txt * smb://angus/share/data/../dir/foo.txt * </pre></blockquote> * * @param obj Another <code>SmbFile</code> object to compare for equality * @return <code>true</code> if the two objects refer to the same SMB resource * and <code>false</code> otherwise * @throws SmbException */ public boolean equals( Object obj ) { if (obj instanceof SmbFile) { SmbFile f = (SmbFile)obj; boolean ret; if (this == f) return true; /* If uncertain, pathNamesPossiblyEqual returns true. * Comparing canonical paths is definitive. */ if (pathNamesPossiblyEqual(url.getPath(), f.url.getPath())) { getUncPath0(); f.getUncPath0(); if (canon.equalsIgnoreCase(f.canon)) { try { ret = getAddress().equals(f.getAddress()); } catch( UnknownHostException uhe ) { ret = getServer().equalsIgnoreCase(f.getServer()); } return ret; } } } return false; } /* public boolean equals( Object obj ) { return obj instanceof SmbFile && obj.hashCode() == hashCode(); } */ /** * Returns the string representation of this SmbFile object. This will * be the same as the URL used to construct this <code>SmbFile</code>. * This method will return the same value * as <code>getPath</code>. * * @return The original URL representation of this SMB resource * @throws SmbException */ public String toString() { return url.toString(); } /* URLConnection implementation */ /** * This URLConnection method just returns the result of <tt>length()</tt>. * * @return the length of this file or 0 if it refers to a directory */ public int getContentLength() { try { return (int)(length() & 0xFFFFFFFFL); } catch( SmbException se ) { } return 0; } /** * This URLConnection method just returns the result of <tt>lastModified</tt>. * * @return the last modified data as milliseconds since Jan 1, 1970 */ public long getDate() { try { return lastModified(); } catch( SmbException se ) { } return 0L; } /** * This URLConnection method just returns the result of <tt>lastModified</tt>. * * @return the last modified data as milliseconds since Jan 1, 1970 */ public long getLastModified() { try { return lastModified(); } catch( SmbException se ) { } return 0L; } /** * This URLConnection method just returns a new <tt>SmbFileInputStream</tt> created with this file. * * @throws IOException thrown by <tt>SmbFileInputStream</tt> constructor */ public InputStream getInputStream() throws IOException { return new SmbFileInputStream( this ); } /** * This URLConnection method just returns a new <tt>SmbFileOutputStream</tt> created with this file. * * @throws IOException thrown by <tt>SmbFileOutputStream</tt> constructor */ public OutputStream getOutputStream() throws IOException { return new SmbFileOutputStream( this ); } private void processAces(ACE[] aces, boolean resolveSids) throws IOException { String server = getServerWithDfs(); int ai; if (resolveSids) { SID[] sids = new SID[aces.length]; String[] names = null; for (ai = 0; ai < aces.length; ai++) { sids[ai] = aces[ai].sid; } for (int off = 0; off < sids.length; off += 64) { int len = sids.length - off; if (len > 64) len = 64; SID.resolveSids(server, auth, sids, off, len); } } else { for (ai = 0; ai < aces.length; ai++) { aces[ai].sid.origin_server = server; aces[ai].sid.origin_auth = auth; } } } /** * -------------- MPRV PATCH ------------- * Get security descriptor * @param resolveSids true if the sids are resolved * @return security descriptor * @throws IOException */ public SecurityDescriptor getSecurityDescriptor(boolean resolveSids) throws IOException { int f; ACE[] aces; f = open0(O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0); /* * NtTrans Query Security Desc Request / Response */ NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); try { send(request, response); } finally { close(f, 0L); } return response.securityDescriptor; } /** * Return an array of Access Control Entry (ACE) objects representing * the security descriptor associated with this files or directory. * If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. * * @param resolveSids Attempt to resolve the SIDs within each ACE form * their numeric representation to their corresponding account names. */ public ACE[] getSecurity(boolean resolveSids) throws IOException { SecurityDescriptor sd = getSecurityDescriptor(resolveSids); ACE[] aces = sd.aces; if (aces != null) processAces(aces, resolveSids); return aces; } public SID getOwnerUser() throws IOException { int f = open0(O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0); /* * NtTrans Query Security Desc Request / Response */ NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x01); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); send(request, response); close(f, 0L); return response.securityDescriptor.owner_user; } public SID getOwnerGroup() throws IOException { int f = open0(O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0); /* * NtTrans Query Security Desc Request / Response */ NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x02); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); send(request, response); close(f, 0L); return response.securityDescriptor.owner_group; } /** * -------------- MPRV PATCH ------------- * @param sd security descriptor that will be revoked * @param sid user/group for which the permission will be revoked * @param maskToRevoke mask to revoke * @return error code * @throws IOException */ public int revokePermission(SecurityDescriptor sd, SID sid, int maskToRevoke) throws IOException { int f; f = open0(O_RDWR, WRITE_DAC, 0, isDirectory() ? 1 : 0); /* * NtTrans Update Security Desc Request / Response */ NtTransRevokePermissionInSecurityDesc request = new NtTransRevokePermissionInSecurityDesc(f, 0x04, sd, sid, maskToRevoke); NtTransSetSecurityDescResponse response = new NtTransSetSecurityDescResponse(); try { send(request, response); } finally { close(f, 0L); } return response.errorCode; } /** * Return an array of Access Control Entry (ACE) objects representing * the share permissions on the share exporting this file or directory. * If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. * <p> * Note that this is different from calling <tt>getSecurity</tt> on a * share. There are actually two different ACLs for shares - the ACL on * the share and the ACL on the folder being shared. * Go to <i>Computer Management</i> * &gt; <i>System Tools</i> &gt; <i>Shared Folders</i> &gt <i>Shares</i> and * look at the <i>Properties</i> for a share. You will see two tabs - one * for "Share Permissions" and another for "Security". These correspond to * the ACLs returned by <tt>getShareSecurity</tt> and <tt>getSecurity</tt> * respectively. * @param resolveSids Attempt to resolve the SIDs within each ACE form * their numeric representation to their corresponding account names. */ public ACE[] getShareSecurity(boolean resolveSids) throws IOException { String p = url.getPath(); MsrpcShareGetInfo rpc; DcerpcHandle handle; ACE[] aces; resolveDfs(null); String server = getServerWithDfs(); rpc = new MsrpcShareGetInfo(server, tree.share); handle = DcerpcHandle.getHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", auth); try { handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); aces = rpc.getSecurity(); if (aces != null) processAces(aces, resolveSids); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 1) ioe.printStackTrace(log); } } return aces; } /** * Return an array of Access Control Entry (ACE) objects representing * the security descriptor associated with this file or directory. * <p> * Initially, the SIDs within each ACE will not be resolved however when * <tt>getType()</tt>, <tt>getDomainName()</tt>, <tt>getAccountName()</tt>, * or <tt>toString()</tt> is called, the names will attempt to be * resolved. If the names cannot be resolved (e.g. due to temporary * network failure), the said methods will return default values (usually * <tt>S-X-Y-Z</tt> strings of fragments of). * <p> * Alternatively <tt>getSecurity(true)</tt> may be used to resolve all * SIDs together and detect network failures. */ public ACE[] getSecurity() throws IOException { return getSecurity(false); } /** * Gets the server's time * @return time on server (milliseconds since 1970) * @throws SmbException error negotiating with server */ public long serverTime() throws SmbException { if (tree == null) exists(); return tree.session.transport.server.serverTime; } /** * Gets the server's time * @return time on server * @throws SmbException error negotiating with server */ public Date getServerTime() throws SmbException { return new Date(serverTime()); } public String getFilesystem() throws SmbException { if (tree == null) exists(); return tree.filesystem; } public int setOwner(SID owner) throws IOException { int f; f = open0(O_RDWR | O_EXCL, WRITE_DAC | WRITE_OWNER, 0, isDirectory() ? 1 : 0x4000); /* * NtTrans Update Security Desc Request / Response */ NtTransSetSecurityDescOwner request = new NtTransSetSecurityDescOwner(f, owner); NtTransSetSecurityDescResponse response = new NtTransSetSecurityDescResponse(); try { send(request, response); } finally { close(f, 0L); } return response.errorCode; } public void expireCachedAttributes() { attrExpiration = 0; } }
src/jcifs/smb/SmbFile.java
/* jcifs smb client library in Java * Copyright (C) 2000 "Michael B. Allen" <jcifs at samba dot org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package jcifs.smb; import java.net.URLConnection; import java.net.URL; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.security.Principal; import jcifs.Config; import jcifs.util.LogStream; import jcifs.UniAddress; import jcifs.netbios.NbtAddress; import jcifs.dcerpc.*; import jcifs.dcerpc.msrpc.*; import java.util.Date; /** * This class represents a resource on an SMB network. Mainly these * resources are files and directories however an <code>SmbFile</code> * may also refer to servers and workgroups. If the resource is a file or * directory the methods of <code>SmbFile</code> follow the behavior of * the well known {@link java.io.File} class. One fundamental difference * is the usage of a URL scheme [1] to specify the target file or * directory. SmbFile URLs have the following syntax: * * <blockquote><pre> * smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]]][?[param=value[param2=value2[...]]] * </pre></blockquote> * * This example: * * <blockquote><pre> * smb://storage15/public/foo.txt * </pre></blockquote> * * would reference the file <code>foo.txt</code> in the share * <code>public</code> on the server <code>storage15</code>. In addition * to referencing files and directories, jCIFS can also address servers, * and workgroups. * <p> * <font color="#800000"><i>Important: all SMB URLs that represent * workgroups, servers, shares, or directories require a trailing slash '/'. * </i></font> * <p> * When using the <tt>java.net.URL</tt> class with * 'smb://' URLs it is necessary to first call the static * <tt>jcifs.Config.registerSmbURLHandler();</tt> method. This is required * to register the SMB protocol handler. * <p> * The userinfo component of the SMB URL (<tt>domain;user:pass</tt>) must * be URL encoded if it contains reserved characters. According to RFC 2396 * these characters are non US-ASCII characters and most meta characters * however jCIFS will work correctly with anything but '@' which is used * to delimit the userinfo component from the server and '%' which is the * URL escape character itself. * <p> * The server * component may a traditional NetBIOS name, a DNS name, or IP * address. These name resolution mechanisms and their resolution order * can be changed (See <a href="../../../resolver.html">Setting Name * Resolution Properties</a>). The servername and path components are * not case sensitive but the domain, username, and password components * are. It is also likely that properties must be specified for jcifs * to function (See <a href="../../overview-summary.html#scp">Setting * JCIFS Properties</a>). Here are some examples of SMB URLs with brief * descriptions of what they do: * * <p>[1] This URL scheme is based largely on the <i>SMB * Filesharing URL Scheme</i> IETF draft. * * <p><table border="1" cellpadding="3" cellspacing="0" width="100%"> * <tr bgcolor="#ccccff"> * <td colspan="2"><b>SMB URL Examples</b></td> * <tr><td width="20%"><b>URL</b></td><td><b>Description</b></td></tr> * * <tr><td width="20%"><code>smb://users-nyc;miallen:mypass@angus/tmp/</code></td><td> * This URL references a share called <code>tmp</code> on the server * <code>angus</code> as user <code>miallen</code> who's password is * <code>mypass</code>. * </td></tr> * * <tr><td width="20%"> * <code>smb://Administrator:P%40ss@msmith1/c/WINDOWS/Desktop/foo.txt</code></td><td> * A relativly sophisticated example that references a file * <code>msmith1</code>'s desktop as user <code>Administrator</code>. Notice the '@' is URL encoded with the '%40' hexcode escape. * </td></tr> * * <tr><td width="20%"><code>smb://angus/</code></td><td> * This references only a server. The behavior of some methods is different * in this context(e.g. you cannot <code>delete</code> a server) however * as you might expect the <code>list</code> method will list the available * shares on this server. * </td></tr> * * <tr><td width="20%"><code>smb://myworkgroup/</code></td><td> * This syntactically is identical to the above example. However if * <code>myworkgroup</code> happends to be a workgroup(which is indeed * suggested by the name) the <code>list</code> method will return * a list of servers that have registered themselves as members of * <code>myworkgroup</code>. * </td></tr> * * <tr><td width="20%"><code>smb://</code></td><td> * Just as <code>smb://server/</code> lists shares and * <code>smb://workgroup/</code> lists servers, the <code>smb://</code> * URL lists all available workgroups on a netbios LAN. Again, * in this context many methods are not valid and return default * values(e.g. <code>isHidden</code> will always return false). * </td></tr> * * <tr><td width="20%"><code>smb://angus.foo.net/d/jcifs/pipes.doc</code></td><td> * The server name may also be a DNS name as it is in this example. See * <a href="../../../resolver.html">Setting Name Resolution Properties</a> * for details. * </td></tr> * * <tr><td width="20%"><code>smb://192.168.1.15/ADMIN$/</code></td><td> * The server name may also be an IP address. See <a * href="../../../resolver.html">Setting Name Resolution Properties</a> * for details. * </td></tr> * * <tr><td width="20%"> * <code>smb://domain;username:password@server/share/path/to/file.txt</code></td><td> * A prototypical example that uses all the fields. * </td></tr> * * <tr><td width="20%"><code>smb://myworkgroup/angus/ &lt;-- ILLEGAL </code></td><td> * Despite the hierarchial relationship between workgroups, servers, and * filesystems this example is not valid. * </td></tr> * * <tr><td width="20%"> * <code>smb://server/share/path/to/dir &lt;-- ILLEGAL </code></td><td> * URLs that represent workgroups, servers, shares, or directories require a trailing slash '/'. * </td></tr> * * <tr><td width="20%"> * <code>smb://MYGROUP/?SERVER=192.168.10.15</code></td><td> * SMB URLs support some query string parameters. In this example * the <code>SERVER</code> parameter is used to override the * server name service lookup to contact the server 192.168.10.15 * (presumably known to be a master * browser) for the server list in workgroup <code>MYGROUP</code>. * </td></tr> * * </table> * * <p>A second constructor argument may be specified to augment the URL * for better programmatic control when processing many files under * a common base. This is slightly different from the corresponding * <code>java.io.File</code> usage; a '/' at the beginning of the second * parameter will still use the server component of the first parameter. The * examples below illustrate the resulting URLs when this second contructor * argument is used. * * <p><table border="1" cellpadding="3" cellspacing="0" width="100%"> * <tr bgcolor="#ccccff"> * <td colspan="3"> * <b>Examples Of SMB URLs When Augmented With A Second Constructor Parameter</b></td> * <tr><td width="20%"> * <b>First Parameter</b></td><td><b>Second Parameter</b></td><td><b>Result</b></td></tr> * * <tr><td width="20%"><code> * smb://host/share/a/b/ * </code></td><td width="20%"><code> * c/d/ * </code></td><td><code> * smb://host/share/a/b/c/d/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/foo/bar/ * </code></td><td width="20%"><code> * /share2/zig/zag * </code></td><td><code> * smb://host/share2/zig/zag * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/foo/bar/ * </code></td><td width="20%"><code> * ../zip/ * </code></td><td><code> * smb://host/share/foo/zip/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/zig/zag * </code></td><td width="20%"><code> * smb://foo/bar/ * </code></td><td><code> * smb://foo/bar/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/foo/ * </code></td><td width="20%"><code> * ../.././.././../foo/ * </code></td><td><code> * smb://host/foo/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://host/share/zig/zag * </code></td><td width="20%"><code> * / * </code></td><td><code> * smb://host/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://server/ * </code></td><td width="20%"><code> * ../ * </code></td><td><code> * smb://server/ * </code></td></tr> * * <tr><td width="20%"><code> * smb:// * </code></td><td width="20%"><code> * myworkgroup/ * </code></td><td><code> * smb://myworkgroup/ * </code></td></tr> * * <tr><td width="20%"><code> * smb://myworkgroup/ * </code></td><td width="20%"><code> * angus/ * </code></td><td><code> * smb://myworkgroup/angus/ &lt;-- ILLEGAL<br>(But if you first create an <tt>SmbFile</tt> with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second <tt>String</tt> parameter jCIFS will factor out the 'workgroup'.) * </code></td></tr> * * </table> * * <p>Instances of the <code>SmbFile</code> class are immutable; that is, * once created, the abstract pathname represented by an SmbFile object * will never change. * * @see java.io.File */ public class SmbFile extends URLConnection implements SmbConstants { static final int O_RDONLY = 0x01; static final int O_WRONLY = 0x02; static final int O_RDWR = 0x03; static final int O_APPEND = 0x04; // Open Function Encoding // create if the file does not exist static final int O_CREAT = 0x0010; // fail if the file exists static final int O_EXCL = 0x0020; // truncate if the file exists static final int O_TRUNC = 0x0040; // share access /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients (including other threads making calls into jCIFS) * will not be permitted to access the target file and will receive "The * file is being accessed by another process" message. */ public static final int FILE_NO_SHARE = 0x00; /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients will be permitted to read from the target file while * this file is open. This constant may be logically OR'd with other share * access flags. */ public static final int FILE_SHARE_READ = 0x01; /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients will be permitted to write to the target file while * this file is open. This constant may be logically OR'd with other share * access flags. */ public static final int FILE_SHARE_WRITE = 0x02; /** * When specified as the <tt>shareAccess</tt> constructor parameter, * other SMB clients will be permitted to delete the target file while * this file is open. This constant may be logically OR'd with other share * access flags. */ public static final int FILE_SHARE_DELETE = 0x04; // file attribute encoding /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> will be read-only */ public static final int ATTR_READONLY = 0x01; /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> will be hidden */ public static final int ATTR_HIDDEN = 0x02; /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> will be a system file */ public static final int ATTR_SYSTEM = 0x04; /** * A file with this bit on as returned by <tt>getAttributes()</tt> is * a volume */ public static final int ATTR_VOLUME = 0x08; /** * A file with this bit on as returned by <tt>getAttributes()</tt> is * a directory */ public static final int ATTR_DIRECTORY = 0x10; /** * A file with this bit on as returned by <tt>getAttributes()</tt> or set * with <tt>setAttributes()</tt> is an archived file */ public static final int ATTR_ARCHIVE = 0x20; // extended file attribute encoding(others same as above) static final int ATTR_COMPRESSED = 0x800; static final int ATTR_NORMAL = 0x080; static final int ATTR_TEMPORARY = 0x100; static final int ATTR_GET_MASK = 0x7FFF; /* orig 0x7fff */ static final int ATTR_SET_MASK = 0x30A7; /* orig 0x0027 */ static final int DEFAULT_ATTR_EXPIRATION_PERIOD = 30000; // orig 5000; static final int HASH_DOT = ".".hashCode(); static final int HASH_DOT_DOT = "..".hashCode(); static LogStream log = LogStream.getInstance(); static long attrExpirationPeriod; static boolean ignoreCopyToException; static { try { Class.forName( "jcifs.Config" ); } catch( ClassNotFoundException cnfe ) { cnfe.printStackTrace(); } attrExpirationPeriod = Config.getLong( "jcifs.smb.client.attrExpirationPeriod", DEFAULT_ATTR_EXPIRATION_PERIOD ); ignoreCopyToException = Config.getBoolean( "jcifs.smb.client.ignoreCopyToException", true ); dfs = new Dfs(); } /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a regular file or directory. */ public static final int TYPE_FILESYSTEM = 0x01; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a workgroup. */ public static final int TYPE_WORKGROUP = 0x02; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a server. */ public static final int TYPE_SERVER = 0x04; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a share. */ public static final int TYPE_SHARE = 0x08; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a named pipe. */ public static final int TYPE_NAMED_PIPE = 0x10; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a printer. */ public static final int TYPE_PRINTER = 0x20; /** * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt> * represents is a communications device. */ public static final int TYPE_COMM = 0x40; private String canon; // Initially null; set by getUncPath; dir must end with '/' private String share; // Can be null private long createTime; private long lastModified; private long lastAccessed; private long changeTime; private int attributes = 0; private long attrExpiration; private long size; private long sizeExpiration; private boolean isExists; private int shareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; private SmbComBlankResponse blank_resp = null; private DfsReferral dfsReferral = null; // For getDfsPath() and getServerWithDfs() protected static Dfs dfs; NtlmPasswordAuthentication auth; // Cannot be null SmbTree tree = null; // Initially null String unc; // Initially null; set by getUncPath; never ends with '/' int fid; // Initially 0; set by open() int type; boolean opened; int tree_num; /** * Constructs an SmbFile representing a resource on an SMB network such as * a file or directory. See the description and examples of smb URLs above. * * @param url A URL string * @throws MalformedURLException * If the <code>parent</code> and <code>child</code> parameters * do not follow the prescribed syntax */ public SmbFile( String url ) throws MalformedURLException { this( new URL( null, url, Handler.SMB_HANDLER )); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>parent SmbFile</code>. See the description above for examples * of using the second <code>name</code> parameter. * * @param context A base <code>SmbFile</code> * @param name A path string relative to the <code>parent</code> paremeter * @throws MalformedURLException * If the <code>parent</code> and <code>child</code> parameters * do not follow the prescribed syntax * @throws UnknownHostException * If the server or workgroup of the <tt>context</tt> file cannot be determined */ public SmbFile( SmbFile context, String name ) throws MalformedURLException, UnknownHostException { this( context.isWorkgroup0() ? new URL( null, "smb://" + name, Handler.SMB_HANDLER ) : new URL( context.url, name, Handler.SMB_HANDLER ), context.auth ); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>parent</code>. See the description above for examples of * using the second <code>chile</code> parameter. * * @param context A URL string * @param name A path string relative to the <code>context</code> paremeter * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( String context, String name ) throws MalformedURLException { this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER )); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. * * @param url A URL string * @param auth The credentials the client should use for authentication * @throws MalformedURLException * If the <code>url</code> parameter does not follow the prescribed syntax */ public SmbFile( String url, NtlmPasswordAuthentication auth ) throws MalformedURLException { this( new URL( null, url, Handler.SMB_HANDLER ), auth ); } /** * Constructs an SmbFile representing a file on an SMB network. The * <tt>shareAccess</tt> parameter controls what permissions other * clients have when trying to access the same file while this instance * is still open. This value is either <tt>FILE_NO_SHARE</tt> or any * combination of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, * and <tt>FILE_SHARE_DELETE</tt> logically OR'd together. * * @param url A URL string * @param auth The credentials the client should use for authentication * @param shareAccess Specifies what access other clients have while this file is open. * @throws MalformedURLException * If the <code>url</code> parameter does not follow the prescribed syntax */ public SmbFile( String url, NtlmPasswordAuthentication auth, int shareAccess ) throws MalformedURLException { this( new URL( null, url, Handler.SMB_HANDLER ), auth ); if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) { throw new RuntimeException( "Illegal shareAccess parameter" ); } this.shareAccess = shareAccess; } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>context</code>. See the description above for examples of * using the second <code>name</code> parameter. * * @param context A URL string * @param name A path string relative to the <code>context</code> paremeter * @param auth The credentials the client should use for authentication * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( String context, String name, NtlmPasswordAuthentication auth ) throws MalformedURLException { this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth ); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>context</code>. See the description above for examples of * using the second <code>name</code> parameter. The <tt>shareAccess</tt> * parameter controls what permissions other clients have when trying * to access the same file while this instance is still open. This * value is either <tt>FILE_NO_SHARE</tt> or any combination * of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and * <tt>FILE_SHARE_DELETE</tt> logically OR'd together. * * @param context A URL string * @param name A path string relative to the <code>context</code> paremeter * @param auth The credentials the client should use for authentication * @param shareAccess Specifies what access other clients have while this file is open. * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( String context, String name, NtlmPasswordAuthentication auth, int shareAccess ) throws MalformedURLException { this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth ); if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) { throw new RuntimeException( "Illegal shareAccess parameter" ); } this.shareAccess = shareAccess; } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory. The second parameter is a relative path from * the <code>context</code>. See the description above for examples of * using the second <code>name</code> parameter. The <tt>shareAccess</tt> * parameter controls what permissions other clients have when trying * to access the same file while this instance is still open. This * value is either <tt>FILE_NO_SHARE</tt> or any combination * of <tt>FILE_SHARE_READ</tt>, <tt>FILE_SHARE_WRITE</tt>, and * <tt>FILE_SHARE_DELETE</tt> logically OR'd together. * * @param context A base <code>SmbFile</code> * @param name A path string relative to the <code>context</code> file path * @param shareAccess Specifies what access other clients have while this file is open. * @throws MalformedURLException * If the <code>context</code> and <code>name</code> parameters * do not follow the prescribed syntax */ public SmbFile( SmbFile context, String name, int shareAccess ) throws MalformedURLException, UnknownHostException { this( context.isWorkgroup0() ? new URL( null, "smb://" + name, Handler.SMB_HANDLER ) : new URL( context.url, name, Handler.SMB_HANDLER ), context.auth ); if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) { throw new RuntimeException( "Illegal shareAccess parameter" ); } this.shareAccess = shareAccess; } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory from a <tt>URL</tt> object. * * @param url The URL of the target resource */ public SmbFile( URL url ) { this( url, new NtlmPasswordAuthentication( url.getUserInfo() )); } /** * Constructs an SmbFile representing a resource on an SMB network such * as a file or directory from a <tt>URL</tt> object and an * <tt>NtlmPasswordAuthentication</tt> object. * * @param url The URL of the target resource * @param auth The credentials the client should use for authentication */ public SmbFile( URL url, NtlmPasswordAuthentication auth ) { super( url ); this.auth = auth == null ? new NtlmPasswordAuthentication( url.getUserInfo() ) : auth; getUncPath0(); } SmbFile( SmbFile context, String name, int type, int attributes, long createTime, long lastModified, long lastAccessed, long size ) throws MalformedURLException, UnknownHostException { this( context.isWorkgroup0() ? new URL( null, "smb://" + name + "/", Handler.SMB_HANDLER ) : new URL( context.url, name + (( attributes & ATTR_DIRECTORY ) > 0 ? "/" : "" ))); /* why was this removed before? DFS? copyTo? Am I going around in circles? */ auth = context.auth; if( context.share != null ) { this.tree = context.tree; this.dfsReferral = context.dfsReferral; } int last = name.length() - 1; if( name.charAt( last ) == '/' ) { name = name.substring( 0, last ); } if( context.share == null ) { this.unc = "\\"; } else if( context.unc.equals( "\\" )) { this.unc = '\\' + name; } else { this.unc = context.unc + '\\' + name; } /* why? am I going around in circles? * this.type = type == TYPE_WORKGROUP ? 0 : type; */ this.type = type; this.attributes = attributes; this.createTime = createTime; // need to change constructor to get this... need to look at implications of that this.changeTime = changeTime; this.lastModified = lastModified; this.lastAccessed = lastAccessed; this.size = size; isExists = true; attrExpiration = sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; } private SmbComBlankResponse blank_resp() { if( blank_resp == null ) { blank_resp = new SmbComBlankResponse(); } return blank_resp; } void resolveDfs(ServerMessageBlock request) throws SmbException { if (request instanceof SmbComClose) return; if (request != null) request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS; return; // connect0(); // DfsReferral dr = dfs.resolve( // tree.session.transport.tconHostName, // tree.share, // unc, // auth); // if (dr != null) { // String service = null; // if (request != null) { // switch( request.command ) { // case ServerMessageBlock.SMB_COM_TRANSACTION: // case ServerMessageBlock.SMB_COM_TRANSACTION2: // switch( ((SmbComTransaction)request).subCommand & 0xFF ) { // case SmbComTransaction.TRANS2_GET_DFS_REFERRAL: // break; // default: // service = "A:"; // } // break; // default: // service = "A:"; // } // } // DfsReferral start = dr; // SmbException se = null; // do { // try { // if (log.level >= 2) // log.println("DFS redirect: " + dr); // UniAddress addr = UniAddress.getByName(dr.server); // SmbTransport trans = SmbTransport.getSmbTransport(addr, url.getPort()); // /* This is a key point. This is where we set the "tree" of this file which // * is like changing the rug out from underneath our feet. // */ // /* Technically we should also try to authenticate here but that means doing the session setup and tree connect separately. For now a simple connect will at least tell us if the host is alive. That should be sufficient for 99% of the cases. We can revisit this again for 2.0. // */ // trans.connect(); // tree = trans.getSmbSession( auth ).getSmbTree( dr.share, service ); // if (dr != start && dr.key != null) { // dr.map.put(dr.key, dr); // } // se = null; // break; // } catch (IOException ioe) { // if (ioe instanceof SmbException) { // se = (SmbException)ioe; // } else { // se = new SmbException(dr.server, ioe); // } // } // dr = dr.next; // } while (dr != start); // if (se != null) // throw se; // if (log.level >= 3) // log.println( dr ); // dfsReferral = dr; // if (dr.pathConsumed < 0) { // dr.pathConsumed = 0; // } else if (dr.pathConsumed > unc.length()) { // dr.pathConsumed = unc.length(); // } // String dunc = unc.substring(dr.pathConsumed); // if (dunc.equals("")) // dunc = "\\"; // if (!dr.path.equals("")) // dunc = "\\" + dr.path + dunc; // unc = dunc; // if (request != null && // request.path != null && // request.path.endsWith("\\") && // dunc.endsWith("\\") == false) { // dunc += "\\"; // } // if (request != null) { // request.path = dunc; // request.flags2 |= ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS; // } // } else if (tree.inDomainDfs && // !(request instanceof NtTransQuerySecurityDesc) && // !(request instanceof SmbComClose) && // !(request instanceof SmbComFindClose2)) { // throw new SmbException(NtStatus.NT_STATUS_NOT_FOUND, false); // } else { // if (request != null) // request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS; // } } void send( ServerMessageBlock request, ServerMessageBlock response ) throws SmbException { for( ;; ) { resolveDfs(request); try { tree.send( request, response ); break; } catch( DfsReferral dre ) { if( dre.resolveHashes ) { throw dre; } request.reset(); } } } static String queryLookup( String query, String param ) { char in[] = query.toCharArray(); int i, ch, st, eq; st = eq = 0; for( i = 0; i < in.length; i++) { ch = in[i]; if( ch == '&' ) { if( eq > st ) { String p = new String( in, st, eq - st ); if( p.equalsIgnoreCase( param )) { eq++; return new String( in, eq, i - eq ); } } st = i + 1; } else if( ch == '=' ) { eq = i; } } if( eq > st ) { String p = new String( in, st, eq - st ); if( p.equalsIgnoreCase( param )) { eq++; return new String( in, eq, in.length - eq ); } } return null; } UniAddress[] addresses; int addressIndex; UniAddress getAddress() throws UnknownHostException { if (addressIndex == 0) return getFirstAddress(); return addresses[addressIndex - 1]; } UniAddress getFirstAddress() throws UnknownHostException { addressIndex = 0; String host = url.getHost(); String path = url.getPath(); String query = url.getQuery(); if( query != null ) { String server = queryLookup( query, "server" ); if( server != null && server.length() > 0 ) { addresses = new UniAddress[1]; addresses[0] = UniAddress.getByName( server ); return getNextAddress(); } String address = queryLookup(query, "address"); if (address != null && address.length() > 0) { byte[] ip = java.net.InetAddress.getByName(address).getAddress(); addresses = new UniAddress[1]; addresses[0] = new UniAddress(java.net.InetAddress.getByAddress(host, ip)); return getNextAddress(); } } if (host.length() == 0) { try { NbtAddress addr = NbtAddress.getByName( NbtAddress.MASTER_BROWSER_NAME, 0x01, null); addresses = new UniAddress[1]; addresses[0] = UniAddress.getByName( addr.getHostAddress() ); } catch( UnknownHostException uhe ) { NtlmPasswordAuthentication.initDefaults(); if( NtlmPasswordAuthentication.DEFAULT_DOMAIN.equals( "?" )) { throw uhe; } addresses = UniAddress.getAllByName( NtlmPasswordAuthentication.DEFAULT_DOMAIN, true ); } } else if( path.length() == 0 || path.equals( "/" )) { addresses = UniAddress.getAllByName( host, true ); } else { addresses = UniAddress.getAllByName(host, false); } return getNextAddress(); } UniAddress getNextAddress() { UniAddress addr = null; if (addressIndex < addresses.length) addr = addresses[addressIndex++]; return addr; } boolean hasNextAddress() { return addressIndex < addresses.length; } void connect0() throws SmbException { try { connect(); } catch( UnknownHostException uhe ) { throw new SmbException( "Failed to connect to server", uhe ); } catch( SmbException se ) { throw se; } catch( IOException ioe ) { throw new SmbException( "Failed to connect to server", ioe ); } } void doConnect() throws IOException { SmbTransport trans; UniAddress addr; addr = getAddress(); if (tree != null) { trans = tree.session.transport; } else { trans = SmbTransport.getSmbTransport(addr, url.getPort()); tree = trans.getSmbSession(auth).getSmbTree(share, null); } String hostName = getServerWithDfs(); // tree.inDomainDfs = dfs.resolve(hostName, tree.share, null, auth) != null; tree.inDomainDfs = false; if (tree.inDomainDfs) { tree.connectionState = 2; } try { if( log.level >= 3 ) log.println( "doConnect: " + addr ); tree.treeConnect(null, null); } catch (SmbAuthException sae) { NtlmPasswordAuthentication a; SmbSession ssn; if (share == null) { // IPC$ - try "anonymous" credentials ssn = trans.getSmbSession(NtlmPasswordAuthentication.NULL); tree = ssn.getSmbTree(null, null); tree.treeConnect(null, null); } else if ((a = NtlmAuthenticator.requestNtlmPasswordAuthentication( url.toString(), sae)) != null) { auth = a; ssn = trans.getSmbSession(auth); tree = ssn.getSmbTree(share, null); // tree.inDomainDfs = dfs.resolve(hostName, tree.share, null, auth) != null; tree.inDomainDfs = false; if (tree.inDomainDfs) { tree.connectionState = 2; } tree.treeConnect(null, null); } else { if (log.level >= 1 && hasNextAddress()) sae.printStackTrace(log); throw sae; } } } /** * It is not necessary to call this method directly. This is the * <tt>URLConnection</tt> implementation of <tt>connect()</tt>. */ public void connect() throws IOException { SmbTransport trans; SmbSession ssn; UniAddress addr; if( isConnected() ) { return; } getUncPath0(); getFirstAddress(); for ( ;; ) { try { doConnect(); return; } catch(SmbAuthException sae) { throw sae; // Prevents account lockout on servers with multiple IPs } catch(SmbException se) { if (getNextAddress() == null) throw se; if (log.level >= 3) se.printStackTrace(log); } } } boolean isConnected() { return tree != null && tree.connectionState == 2; } int open0( int flags, int access, int attrs, int options ) throws SmbException { int f; connect0(); if( log.level >= 3 ) log.println( "open0: " + unc ); /* * NT Create AndX / Open AndX Request / Response */ if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) { SmbComNTCreateAndXResponse response = new SmbComNTCreateAndXResponse(); SmbComNTCreateAndX request = new SmbComNTCreateAndX( unc, flags, access, shareAccess, attrs, options, null ); if (this instanceof SmbNamedPipe) { request.flags0 |= 0x16; request.desiredAccess |= 0x20000; response.isExtended = true; } send( request, response ); f = response.fid; attributes = response.extFileAttributes & ATTR_GET_MASK; attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; isExists = true; } else { SmbComOpenAndXResponse response = new SmbComOpenAndXResponse(); send( new SmbComOpenAndX( unc, access, flags, null ), response ); f = response.fid; } return f; } public void open( int flags, int access, int attrs, int options ) throws SmbException { if( isOpen() ) { return; } fid = open0( flags, access, attrs, options ); opened = true; tree_num = tree.tree_num; } public boolean isOpen() { boolean ans = opened && isConnected() && tree_num == tree.tree_num; return ans; } void close( int f, long lastWriteTime ) throws SmbException { if( log.level >= 3 ) log.println( "close: " + f ); /* * Close Request / Response */ send( new SmbComClose( f, lastWriteTime ), blank_resp() ); } void close( long lastWriteTime ) throws SmbException { if( isOpen() == false ) { return; } close( fid, lastWriteTime ); opened = false; } public void close() throws SmbException { close( 0L ); } /** * Returns the <tt>NtlmPasswordAuthentication</tt> object used as * credentials with this file or pipe. This can be used to retrieve the * username for example: * <tt> * String username = f.getPrincipal().getName(); * </tt> * The <tt>Principal</tt> object returned will never be <tt>null</tt> * however the username can be <tt>null</tt> indication anonymous * credentials were used (e.g. some IPC$ services). */ public Principal getPrincipal() { return auth; } /** * Returns the last component of the target URL. This will * effectively be the name of the file or directory represented by this * <code>SmbFile</code> or in the case of URLs that only specify a server * or workgroup, the server or workgroup will be returned. The name of * the root URL <code>smb://</code> is also <code>smb://</code>. If this * <tt>SmbFile</tt> refers to a workgroup, server, share, or directory, * the name will include a trailing slash '/' so that composing new * <tt>SmbFile</tt>s will maintain the trailing slash requirement. * * @return The last component of the URL associated with this SMB * resource or <code>smb://</code> if the resource is <code>smb://</code> * itself. */ public String getName() { getUncPath0(); if( canon.length() > 1 ) { int i = canon.length() - 2; while( canon.charAt( i ) != '/' ) { i--; } return canon.substring( i + 1 ); } else if( share != null ) { return share + '/'; } else if( url.getHost().length() > 0 ) { return url.getHost() + '/'; } else { return "smb://"; } } /** * Everything but the last component of the URL representing this SMB * resource is effectivly it's parent. The root URL <code>smb://</code> * does not have a parent. In this case <code>smb://</code> is returned. * * @return The parent directory of this SMB resource or * <code>smb://</code> if the resource refers to the root of the URL * hierarchy which incedentally is also <code>smb://</code>. */ public String getParent() { String str = url.getAuthority(); if( str.length() > 0 ) { StringBuffer sb = new StringBuffer( "smb://" ); sb.append( str ); getUncPath0(); if( canon.length() > 1 ) { sb.append( canon ); } else { sb.append( '/' ); } str = sb.toString(); int i = str.length() - 2; while( str.charAt( i ) != '/' ) { i--; } return str.substring( 0, i + 1 ); } return "smb://"; } /** * Returns the full uncanonicalized URL of this SMB resource. An * <code>SmbFile</code> constructed with the result of this method will * result in an <code>SmbFile</code> that is equal to the original. * * @return The uncanonicalized full URL of this SMB resource. */ public String getPath() { return url.toString(); } String getUncPath0() { if( unc == null ) { char[] in = url.getPath().toCharArray(); char[] out = new char[in.length]; int length = in.length, i, o, state, s; /* The canonicalization routine */ state = 0; o = 0; for( i = 0; i < length; i++ ) { switch( state ) { case 0: if( in[i] != '/' ) { return null; } out[o++] = in[i]; state = 1; break; case 1: if( in[i] == '/' ) { break; } else if( in[i] == '.' && (( i + 1 ) >= length || in[i + 1] == '/' )) { i++; break; } else if(( i + 1 ) < length && in[i] == '.' && in[i + 1] == '.' && (( i + 2 ) >= length || in[i + 2] == '/' )) { i += 2; if( o == 1 ) break; do { o--; } while( o > 1 && out[o - 1] != '/' ); break; } state = 2; case 2: if( in[i] == '/' ) { state = 1; } out[o++] = in[i]; break; } } canon = new String( out, 0, o ); if( o > 1 ) { o--; i = canon.indexOf( '/', 1 ); if( i < 0 ) { share = canon.substring( 1 ); unc = "\\"; } else if( i == o ) { share = canon.substring( 1, i ); unc = "\\"; } else { share = canon.substring( 1, i ); unc = canon.substring( i, out[o] == '/' ? o : o + 1 ); unc = unc.replace( '/', '\\' ); } } else { share = null; unc = "\\"; } } return unc; } /** * Retuns the Windows UNC style path with backslashs intead of forward slashes. * * @return The UNC path. */ public String getUncPath() { getUncPath0(); if( share == null ) { return "\\\\" + url.getHost(); } return "\\\\" + url.getHost() + canon.replace( '/', '\\' ); } /** * Returns the full URL of this SMB resource with '.' and '..' components * factored out. An <code>SmbFile</code> constructed with the result of * this method will result in an <code>SmbFile</code> that is equal to * the original. * * @return The canonicalized URL of this SMB resource. */ public String getCanonicalPath() { String str = url.getAuthority(); getUncPath0(); if( str.length() > 0 ) { return "smb://" + url.getAuthority() + canon; } return "smb://"; } /** * Retrieves the share associated with this SMB resource. In * the case of <code>smb://</code>, <code>smb://workgroup/</code>, * and <code>smb://server/</code> URLs which do not specify a share, * <code>null</code> will be returned. * * @return The share component or <code>null</code> if there is no share */ public String getShare() { return share; } String getServerWithDfs() { if (dfsReferral != null) { return dfsReferral.server; } return getServer(); } /** * Retrieve the hostname of the server for this SMB resource. If this * <code>SmbFile</code> references a workgroup, the name of the workgroup * is returned. If this <code>SmbFile</code> refers to the root of this * SMB network hierarchy, <code>null</code> is returned. * * @return The server or workgroup name or <code>null</code> if this * <code>SmbFile</code> refers to the root <code>smb://</code> resource. */ public String getServer() { String str = url.getHost(); if( str.length() == 0 ) { return null; } return str; } /** * Returns type of of object this <tt>SmbFile</tt> represents. * @return <tt>TYPE_FILESYSTEM, TYPE_WORKGROUP, TYPE_SERVER, TYPE_SHARE, * TYPE_PRINTER, TYPE_NAMED_PIPE</tt>, or <tt>TYPE_COMM</tt>. */ public int getType() throws SmbException { if( type == 0 ) { if( getUncPath0().length() > 1 ) { type = TYPE_FILESYSTEM; } else if( share != null ) { // treeConnect good enough to test service type connect0(); if( share.equals( "IPC$" )) { type = TYPE_NAMED_PIPE; } else if( tree.service.equals( "LPT1:" )) { type = TYPE_PRINTER; } else if( tree.service.equals( "COMM" )) { type = TYPE_COMM; } else { type = TYPE_SHARE; } } else if( url.getAuthority() == null || url.getAuthority().length() == 0 ) { type = TYPE_WORKGROUP; } else { UniAddress addr; try { addr = getAddress(); } catch( UnknownHostException uhe ) { throw new SmbException( url.toString(), uhe ); } if( addr.getAddress() instanceof NbtAddress ) { int code = ((NbtAddress)addr.getAddress()).getNameType(); if( code == 0x1d || code == 0x1b ) { type = TYPE_WORKGROUP; return type; } } type = TYPE_SERVER; } } return type; } boolean isWorkgroup0() throws UnknownHostException { if( type == TYPE_WORKGROUP || url.getHost().length() == 0 ) { type = TYPE_WORKGROUP; return true; } else { getUncPath0(); if( share == null ) { UniAddress addr = getAddress(); if( addr.getAddress() instanceof NbtAddress ) { int code = ((NbtAddress)addr.getAddress()).getNameType(); if( code == 0x1d || code == 0x1b ) { type = TYPE_WORKGROUP; return true; } } type = TYPE_SERVER; } } return false; } Info queryPath( String path, int infoLevel ) throws SmbException { connect0(); if (log.level >= 3) log.println( "queryPath: " + path ); /* normally we'd check the negotiatedCapabilities for CAP_NT_SMBS * however I can't seem to get a good last modified time from * SMB_COM_QUERY_INFORMATION so if NT_SMBs are requested * by the server than in this case that's what it will get * regardless of what jcifs.smb.client.useNTSmbs is set * to(overrides negotiatedCapabilities). */ /* We really should do the referral before this in case * the redirected target has different capabilities. But * the way we have been doing that is to call exists() which * calls this method so another technique will be necessary * to support DFS referral _to_ Win95/98/ME. */ if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) { /* * Trans2 Query Path Information Request / Response */ Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse( infoLevel ); send( new Trans2QueryPathInformation( path, infoLevel ), response ); return response.info; } else { /* * Query Information Request / Response */ SmbComQueryInformationResponse response = new SmbComQueryInformationResponse( tree.session.transport.server.serverTimeZone * 1000 * 60L ); send( new SmbComQueryInformation( path ), response ); return response; } } /** * Tests to see if the SMB resource exists. If the resource refers * only to a server, this method determines if the server exists on the * network and is advertising SMB services. If this resource refers to * a workgroup, this method determines if the workgroup name is valid on * the local SMB network. If this <code>SmbFile</code> refers to the root * <code>smb://</code> resource <code>true</code> is always returned. If * this <code>SmbFile</code> is a traditional file or directory, it will * be queried for on the specified server as expected. * * @return <code>true</code> if the resource exists or is alive or * <code>false</code> otherwise */ public boolean exists() throws SmbException { if( attrExpiration > System.currentTimeMillis() ) { return isExists; } attributes = ATTR_READONLY | ATTR_DIRECTORY; changeTime = 0L; createTime = 0L; lastModified = 0L; lastAccessed = 0L; isExists = false; try { if( url.getHost().length() == 0 ) { } else if( share == null ) { if( getType() == TYPE_WORKGROUP ) { UniAddress.getByName( url.getHost(), true ); } else { UniAddress.getByName( url.getHost() ).getHostName(); } } else if( getUncPath0().length() == 1 || share.equalsIgnoreCase( "IPC$" )) { connect0(); // treeConnect is good enough } else { Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_ALL_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); changeTime = info.getChangeTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); size = info.getSize(); sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; } /* If any of the above fail, isExists will not be set true */ isExists = true; } catch( UnknownHostException uhe ) { } catch( SmbException se ) { switch (se.getNtStatus()) { case NtStatus.NT_STATUS_NO_SUCH_FILE: case NtStatus.NT_STATUS_OBJECT_NAME_INVALID: case NtStatus.NT_STATUS_OBJECT_NAME_NOT_FOUND: case NtStatus.NT_STATUS_OBJECT_PATH_NOT_FOUND: break; default: throw se; } } attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; return isExists; } /** * Tests to see if the file this <code>SmbFile</code> represents can be * read. Because any file, directory, or other resource can be read if it * exists, this method simply calls the <code>exists</code> method. * * @return <code>true</code> if the file is read-only */ public boolean canRead() throws SmbException { if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for reading? return true; } return exists(); // try opening and catch sharing violation? } /** * Tests to see if the file this <code>SmbFile</code> represents * exists and is not marked read-only. By default, resources are * considered to be read-only and therefore for <code>smb://</code>, * <code>smb://workgroup/</code>, and <code>smb://server/</code> resources * will be read-only. * * @return <code>true</code> if the resource exists is not marked * read-only */ public boolean canWrite() throws SmbException { if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for writing? return true; } return exists() && ( attributes & ATTR_READONLY ) == 0; } /** * Tests to see if the file this <code>SmbFile</code> represents is a directory. * * @return <code>true</code> if this <code>SmbFile</code> is a directory */ public boolean isDirectory() throws SmbException { if( getUncPath0().length() == 1 ) { return true; } if (!exists()) return false; return ( attributes & ATTR_DIRECTORY ) == ATTR_DIRECTORY; } /** * Tests to see if the file this <code>SmbFile</code> represents is not a directory. * * @return <code>true</code> if this <code>SmbFile</code> is not a directory */ public boolean isFile() throws SmbException { if( getUncPath0().length() == 1 ) { return false; } exists(); return ( attributes & ATTR_DIRECTORY ) == 0; } /** * Tests to see if the file this SmbFile represents is marked as * hidden. This method will also return true for shares with names that * end with '$' such as <code>IPC$</code> or <code>C$</code>. * * @return <code>true</code> if the <code>SmbFile</code> is marked as being hidden */ public boolean isHidden() throws SmbException { if( share == null ) { return false; } else if( getUncPath0().length() == 1 ) { if( share.endsWith( "$" )) { return true; } return false; } exists(); return ( attributes & ATTR_HIDDEN ) == ATTR_HIDDEN; } /** * If the path of this <code>SmbFile</code> falls within a DFS volume, * this method will return the referral path to which it maps. Otherwise * <code>null</code> is returned. */ public String getDfsPath() throws SmbException { resolveDfs(null); if( dfsReferral == null ) { return null; } String path = "smb:/" + dfsReferral.server + "/" + dfsReferral.share + unc; path = path.replace( '\\', '/' ); if (isDirectory()) { path += '/'; } return path; } /** * Retrieve the time this <code>SmbFile</code> was created. The value * returned is suitable for constructing a {@link java.util.Date} object * (i.e. seconds since Epoch 1970). Times should be the same as those * reported using the properties dialog of the Windows Explorer program. * * For Win95/98/Me this is actually the last write time. It is currently * not possible to retrieve the create time from files on these systems. * * @return The number of milliseconds since the 00:00:00 GMT, January 1, * 1970 as a <code>long</code> value */ public long createTime() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return createTime; } return 0L; } public long changeTime() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return changeTime; } return 0L; } /** * Retrieve the last time the file represented by this * <code>SmbFile</code> was modified. The value returned is suitable for * constructing a {@link java.util.Date} object (i.e. seconds since Epoch * 1970). Times should be the same as those reported using the properties * dialog of the Windows Explorer program. * * @return The number of milliseconds since the 00:00:00 GMT, January 1, * 1970 as a <code>long</code> value */ public long lastModified() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return lastModified; } return 0L; } /** * Retrieve the last time the file represented by this * <code>SmbFile</code> was accessed. The value returned is suitable for * constructing a {@link java.util.Date} object (i.e. seconds since Epoch * 1970). Times should be the same as those reported using the properties * dialog of the Windows Explorer program. * * @return The number of milliseconds since the 00:00:00 GMT, January 1, * 1970 as a <code>long</code> value */ public long lastAccessed() throws SmbException { if( getUncPath0().length() > 1 ) { exists(); return lastAccessed; } return 0L; } /** * List the contents of this SMB resource. The list returned by this * method will be; * * <ul> * <li> files and directories contained within this resource if the * resource is a normal disk file directory, * <li> all available NetBIOS workgroups or domains if this resource is * the top level URL <code>smb://</code>, * <li> all servers registered as members of a NetBIOS workgroup if this * resource refers to a workgroup in a <code>smb://workgroup/</code> URL, * <li> all browseable shares of a server including printers, IPC * services, or disk volumes if this resource is a server URL in the form * <code>smb://server/</code>, * <li> or <code>null</code> if the resource cannot be resolved. * </ul> * * @return A <code>String[]</code> array of files and directories, * workgroups, servers, or shares depending on the context of the * resource URL */ public String[] list() throws SmbException { return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); } /** * List the contents of this SMB resource. The list returned will be * identical to the list returned by the parameterless <code>list()</code> * method minus filenames filtered by the specified filter. * * @param filter a filename filter to exclude filenames from the results * @throws SmbException # @return An array of filenames */ public String[] list( SmbFilenameFilter filter ) throws SmbException { return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null ); } /** * List the contents of this SMB resource as an array of * <code>SmbFile</code> objects. This method is much more efficient than * the regular <code>list</code> method when querying attributes of each * file in the result set. * <p> * The list of <code>SmbFile</code>s returned by this method will be; * * <ul> * <li> files and directories contained within this resource if the * resource is a normal disk file directory, * <li> all available NetBIOS workgroups or domains if this resource is * the top level URL <code>smb://</code>, * <li> all servers registered as members of a NetBIOS workgroup if this * resource refers to a workgroup in a <code>smb://workgroup/</code> URL, * <li> all browseable shares of a server including printers, IPC * services, or disk volumes if this resource is a server URL in the form * <code>smb://server/</code>, * <li> or <code>null</code> if the resource cannot be resolved. * </ul> * * @return An array of <code>SmbFile</code> objects representing file * and directories, workgroups, servers, or shares depending on the context * of the resource URL */ public SmbFile[] listFiles() throws SmbException { return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); } /** * The CIFS protocol provides for DOS "wildcards" to be used as * a performance enhancement. The client does not have to filter * the names and the server does not have to return all directory * entries. * <p> * The wildcard expression may consist of two special meta * characters in addition to the normal filename characters. The '*' * character matches any number of characters in part of a name. If * the expression begins with one or more '?'s then exactly that * many characters will be matched whereas if it ends with '?'s * it will match that many characters <i>or less</i>. * <p> * Wildcard expressions will not filter workgroup names or server names. * * <blockquote><pre> * winnt> ls c?o* * clock.avi -rw-- 82944 Mon Oct 14 1996 1:38 AM * Cookies drw-- 0 Fri Nov 13 1998 9:42 PM * 2 items in 5ms * </pre></blockquote> * * @param wildcard a wildcard expression * @throws SmbException * @return An array of <code>SmbFile</code> objects representing file * and directories, workgroups, servers, or shares depending on the context * of the resource URL */ public SmbFile[] listFiles( String wildcard ) throws SmbException { return listFiles( wildcard, ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); } /** * List the contents of this SMB resource. The list returned will be * identical to the list returned by the parameterless <code>listFiles()</code> * method minus files filtered by the specified filename filter. * * @param filter a filter to exclude files from the results * @return An array of <tt>SmbFile</tt> objects * @throws SmbException */ public SmbFile[] listFiles( SmbFilenameFilter filter ) throws SmbException { return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null ); } /** * List the contents of this SMB resource. The list returned will be * identical to the list returned by the parameterless <code>listFiles()</code> * method minus filenames filtered by the specified filter. * * @param filter a file filter to exclude files from the results * @return An array of <tt>SmbFile</tt> objects */ public SmbFile[] listFiles( SmbFileFilter filter ) throws SmbException { return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, filter ); } String[] list( String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException { ArrayList list = new ArrayList(); doEnum(list, false, wildcard, searchAttributes, fnf, ff); return (String[])list.toArray(new String[list.size()]); } SmbFile[] listFiles( String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException { ArrayList list = new ArrayList(); doEnum(list, true, wildcard, searchAttributes, fnf, ff); return (SmbFile[])list.toArray(new SmbFile[list.size()]); } void doEnum(ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff) throws SmbException { if (ff != null && ff instanceof DosFileFilter) { DosFileFilter dff = (DosFileFilter)ff; if (dff.wildcard != null) wildcard = dff.wildcard; searchAttributes = dff.attributes; } try { int hostlen = url.getHost().length(); if (hostlen == 0 || getType() == TYPE_WORKGROUP) { doNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff); } else if (share == null) { doShareEnum(list, files, wildcard, searchAttributes, fnf, ff); } else { doFindFirstNext(list, files, wildcard, searchAttributes, fnf, ff); } } catch (UnknownHostException uhe) { throw new SmbException(url.toString(), uhe); } catch (MalformedURLException mue) { throw new SmbException(url.toString(), mue); } } void doShareEnum(ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff) throws SmbException, UnknownHostException, MalformedURLException { String p = url.getPath(); IOException last = null; FileEntry[] entries; UniAddress addr; FileEntry e; HashMap map; if (p.lastIndexOf('/') != (p.length() - 1)) throw new SmbException(url.toString() + " directory must end with '/'"); if (getType() != TYPE_SERVER) throw new SmbException("The requested list operations is invalid: " + url.toString()); map = new HashMap(); if (dfs.isTrustedDomain(getServer(), auth)) { /* The server name is actually the name of a trusted * domain. Add DFS roots to the list. */ try { entries = doDfsRootEnum(); for (int ei = 0; ei < entries.length; ei++) { e = entries[ei]; if (map.containsKey(e) == false) map.put(e, e); } } catch (IOException ioe) { if (log.level >= 4) ioe.printStackTrace(log); } } addr = getFirstAddress(); while (addr != null) { try { doConnect(); try { entries = doMsrpcShareEnum(); } catch(IOException ioe) { if (log.level >= 3) ioe.printStackTrace(log); entries = doNetShareEnum(); } for (int ei = 0; ei < entries.length; ei++) { e = entries[ei]; if (map.containsKey(e) == false) map.put(e, e); } break; } catch(IOException ioe) { if (log.level >= 3) ioe.printStackTrace(log); last = ioe; } addr = getNextAddress(); } if (last != null && map.isEmpty()) { if (last instanceof SmbException == false) throw new SmbException(url.toString(), last); throw (SmbException)last; } Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { e = (FileEntry)iter.next(); String name = e.getName(); if (fnf != null && fnf.accept(this, name) == false) continue; if (name.length() > 0) { // if !files we don't need to create SmbFiles here SmbFile f = new SmbFile(this, name, e.getType(), ATTR_READONLY | ATTR_DIRECTORY, 0L, 0L, 0L, 0L ); if (ff != null && ff.accept(f) == false) continue; if (files) { list.add(f); } else { list.add(name); } } } } FileEntry[] doDfsRootEnum() throws IOException { MsrpcDfsRootEnum rpc; DcerpcHandle handle = null; FileEntry[] entries; handle = DcerpcHandle.getHandle("ncacn_np:" + getAddress().getHostAddress() + "[\\PIPE\\netdfs]", auth); try { rpc = new MsrpcDfsRootEnum(getServer()); handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); return rpc.getEntries(); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 4) ioe.printStackTrace(log); } } } FileEntry[] doMsrpcShareEnum() throws IOException { MsrpcShareEnum rpc; DcerpcHandle handle; rpc = new MsrpcShareEnum(url.getHost()); /* JCIFS will build a composite list of shares if the target host has * multiple IP addresses such as when domain-based DFS is in play. Because * of this, to ensure that we query each IP individually without re-resolving * the hostname and getting a different IP, we must use the current addresses * IP rather than just url.getHost() like we were using prior to 1.2.16. */ handle = DcerpcHandle.getHandle("ncacn_np:" + getAddress().getHostAddress() + "[\\PIPE\\srvsvc]", auth); try { handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); return rpc.getEntries(); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 4) ioe.printStackTrace(log); } } } FileEntry[] doNetShareEnum() throws SmbException { SmbComTransaction req = new NetShareEnum(); SmbComTransactionResponse resp = new NetShareEnumResponse(); send(req, resp); if (resp.status != SmbException.ERROR_SUCCESS) throw new SmbException(resp.status, true); return resp.results; } void doNetServerEnum(ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff) throws SmbException, UnknownHostException, MalformedURLException { int listType = url.getHost().length() == 0 ? 0 : getType(); SmbComTransaction req; SmbComTransactionResponse resp; if (listType == 0) { connect0(); req = new NetServerEnum2(tree.session.transport.server.oemDomainName, NetServerEnum2.SV_TYPE_DOMAIN_ENUM ); resp = new NetServerEnum2Response(); } else if (listType == TYPE_WORKGROUP) { req = new NetServerEnum2(url.getHost(), NetServerEnum2.SV_TYPE_ALL); resp = new NetServerEnum2Response(); } else { throw new SmbException( "The requested list operations is invalid: " + url.toString() ); } boolean more; do { int n; send(req, resp); if (resp.status != SmbException.ERROR_SUCCESS && resp.status != SmbException.ERROR_MORE_DATA) { throw new SmbException( resp.status, true ); } more = resp.status == SmbException.ERROR_MORE_DATA; n = more ? resp.numEntries - 1 : resp.numEntries; for (int i = 0; i < n; i++) { FileEntry e = resp.results[i]; String name = e.getName(); if (fnf != null && fnf.accept(this, name) == false) continue; if (name.length() > 0) { // if !files we don't need to create SmbFiles here SmbFile f = new SmbFile(this, name, e.getType(), ATTR_READONLY | ATTR_DIRECTORY, 0L, 0L, 0L, 0L ); if (ff != null && ff.accept(f) == false) continue; if (files) { list.add(f); } else { list.add(name); } } } if (getType() != TYPE_WORKGROUP) { break; } req.subCommand = (byte)SmbComTransaction.NET_SERVER_ENUM3; req.reset(0, ((NetServerEnum2Response)resp).lastName); resp.reset(); } while(more); } void doFindFirstNext( ArrayList list, boolean files, String wildcard, int searchAttributes, SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException, UnknownHostException, MalformedURLException { SmbComTransaction req; Trans2FindFirst2Response resp; int sid; String path = getUncPath0(); String p = url.getPath(); if( p.lastIndexOf( '/' ) != ( p.length() - 1 )) { throw new SmbException( url.toString() + " directory must end with '/'" ); } req = new Trans2FindFirst2( path, wildcard, searchAttributes ); resp = new Trans2FindFirst2Response(); if( log.level >= 3 ) log.println( "doFindFirstNext: " + req.path ); send( req, resp ); sid = resp.sid; req = new Trans2FindNext2( sid, resp.resumeKey, resp.lastName ); /* The only difference between first2 and next2 responses is subCommand * so let's recycle the response object. */ resp.subCommand = SmbComTransaction.TRANS2_FIND_NEXT2; for( ;; ) { for( int i = 0; i < resp.numEntries; i++ ) { FileEntry e = resp.results[i]; String name = e.getName(); if( name.length() < 3 ) { int h = name.hashCode(); if( h == HASH_DOT || h == HASH_DOT_DOT ) { if (name.equals(".") || name.equals("..")) continue; } } if( fnf != null && fnf.accept( this, name ) == false ) { continue; } if( name.length() > 0 ) { SmbFile f = new SmbFile( this, name, TYPE_FILESYSTEM, e.getAttributes(), e.createTime(), e.lastModified(), e.lastAccessed(), e.length() ); if( ff != null && ff.accept( f ) == false ) { continue; } if( files ) { list.add( f ); } else { list.add( name ); } } } if( resp.isEndOfSearch || resp.numEntries == 0 ) { break; } req.reset( resp.resumeKey, resp.lastName ); resp.reset(); send( req, resp ); } try { send( new SmbComFindClose2( sid ), blank_resp() ); } catch (SmbException se) { if( log.level >= 4 ) se.printStackTrace( log ); } } /** * Changes the name of the file this <code>SmbFile</code> represents to the name * designated by the <code>SmbFile</code> argument. * <p/> * <i>Remember: <code>SmbFile</code>s are immutible and therefore * the path associated with this <code>SmbFile</code> object will not * change). To access the renamed file it is necessary to construct a * new <tt>SmbFile</tt></i>. * * @param dest An <code>SmbFile</code> that represents the new pathname * @throws NullPointerException * If the <code>dest</code> argument is <code>null</code> */ public void renameTo( SmbFile dest ) throws SmbException { if( getUncPath0().length() == 1 || dest.getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } resolveDfs(null); dest.resolveDfs(null); /* * This check is to determine whether we are renaming a file to a * destination path that's not in the current session. We're modifying * it to ignore the case when the destination file has no session, * because if you skip DFS resolution (previous step) the session * won't be established. */ if (!tree.equals(dest.tree) && dest.tree != null) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } if( log.level >= 3 ) log.println( "renameTo: " + unc + " -> " + dest.unc ); attrExpiration = sizeExpiration = 0; dest.attrExpiration = 0; /* * Rename Request / Response */ send( new SmbComRename( unc, dest.unc ), blank_resp() ); } class WriterThread extends Thread { byte[] b; int n; long off; boolean ready; SmbFile dest; SmbException e = null; boolean useNTSmbs; SmbComWriteAndX reqx; SmbComWrite req; ServerMessageBlock resp; WriterThread() throws SmbException { super( "JCIFS-WriterThread" ); useNTSmbs = tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS ); if( useNTSmbs ) { reqx = new SmbComWriteAndX(); resp = new SmbComWriteAndXResponse(); } else { req = new SmbComWrite(); resp = new SmbComWriteResponse(); } ready = false; } synchronized void write( byte[] b, int n, SmbFile dest, long off ) { this.b = b; this.n = n; this.dest = dest; this.off = off; ready = false; notify(); } public void run() { synchronized( this ) { try { for( ;; ) { notify(); ready = true; while( ready ) { wait(); } if( n == -1 ) { return; } if( useNTSmbs ) { reqx.setParam( dest.fid, off, n, b, 0, n ); dest.send( reqx, resp ); } else { req.setParam( dest.fid, off, n, b, 0, n ); dest.send( req, resp ); } } } catch( SmbException e ) { this.e = e; } catch( Exception x ) { this.e = new SmbException( "WriterThread", x ); } notify(); } } } void copyTo0( SmbFile dest, byte[][] b, int bsize, WriterThread w, SmbComReadAndX req, SmbComReadAndXResponse resp ) throws SmbException { int i; if( attrExpiration < System.currentTimeMillis() ) { attributes = ATTR_READONLY | ATTR_DIRECTORY; createTime = 0L; lastModified = 0L; isExists = false; Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); /* If any of the above fails, isExists will not be set true */ isExists = true; attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; } if( isDirectory() ) { SmbFile[] files; SmbFile ndest; String path = dest.getUncPath0(); if( path.length() > 1 ) { try { dest.mkdir(); dest.setPathInformation( attributes, createTime, lastModified ); } catch( SmbException se ) { if( se.getNtStatus() != NtStatus.NT_STATUS_ACCESS_DENIED && se.getNtStatus() != NtStatus.NT_STATUS_OBJECT_NAME_COLLISION ) { throw se; } } } files = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); try { for( i = 0; i < files.length; i++ ) { ndest = new SmbFile( dest, files[i].getName(), files[i].type, files[i].attributes, files[i].createTime, files[i].lastModified, files[i].lastAccessed, files[i].size ); files[i].copyTo0( ndest, b, bsize, w, req, resp ); } } catch( UnknownHostException uhe ) { throw new SmbException( url.toString(), uhe ); } catch( MalformedURLException mue ) { throw new SmbException( url.toString(), mue ); } } else { long off; try { open( SmbFile.O_RDONLY, 0, ATTR_NORMAL, 0 ); try { dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC, FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES, attributes, 0 ); } catch( SmbAuthException sae ) { if(( dest.attributes & ATTR_READONLY ) != 0 ) { /* Remove READONLY and try again */ dest.setPathInformation( dest.attributes & ~ATTR_READONLY, 0L, 0L ); dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC, FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES, attributes, 0 ); } else { throw sae; } } i = 0; off = 0L; for( ;; ) { req.setParam( fid, off, bsize ); resp.setParam( b[i], 0 ); send( req, resp ); synchronized( w ) { if( w.e != null ) { throw w.e; } while( !w.ready ) { try { w.wait(); } catch( InterruptedException ie ) { throw new SmbException( dest.url.toString(), ie ); } } if( w.e != null ) { throw w.e; } if( resp.dataLength <= 0 ) { break; } w.write( b[i], resp.dataLength, dest, off ); } i = i == 1 ? 0 : 1; off += resp.dataLength; } dest.send( new Trans2SetFileInformation( dest.fid, attributes, createTime, lastModified ), new Trans2SetFileInformationResponse() ); dest.close( 0L ); } catch( SmbException se ) { if (ignoreCopyToException == false) throw new SmbException("Failed to copy file from [" + this.toString() + "] to [" + dest.toString() + "]", se); if( log.level > 1 ) se.printStackTrace( log ); } finally { close(); } } } /** * This method will copy the file or directory represented by this * <tt>SmbFile</tt> and it's sub-contents to the location specified by the * <tt>dest</tt> parameter. This file and the destination file do not * need to be on the same host. This operation does not copy extended * file attibutes such as ACLs but it does copy regular attributes as * well as create and last write times. This method is almost twice as * efficient as manually copying as it employs an additional write * thread to read and write data concurrently. * <p/> * It is not possible (nor meaningful) to copy entire workgroups or * servers. * * @param dest the destination file or directory * @throws SmbException */ public void copyTo( SmbFile dest ) throws SmbException { SmbComReadAndX req; SmbComReadAndXResponse resp; WriterThread w; int bsize; byte[][] b; /* Should be able to copy an entire share actually */ if( share == null || dest.share == null) { throw new SmbException( "Invalid operation for workgroups or servers" ); } req = new SmbComReadAndX(); resp = new SmbComReadAndXResponse(); connect0(); dest.connect0(); /* At this point the maxBufferSize values are from the server * exporting the volumes, not the one that we will actually * end up performing IO with. If the server hosting the * actual files has a smaller maxBufSize this could be * incorrect. To handle this properly it is necessary * to redirect the tree to the target server first before * establishing buffer size. These exists() calls facilitate * that. */ resolveDfs(null); /* It is invalid for the source path to be a child of the destination * path or visa versa. */ try { if (getAddress().equals( dest.getAddress() ) && canon.regionMatches( true, 0, dest.canon, 0, Math.min( canon.length(), dest.canon.length() ))) { throw new SmbException( "Source and destination paths overlap." ); } } catch (UnknownHostException uhe) { } w = new WriterThread(); w.setDaemon( true ); w.start(); /* Downgrade one transport to the lower of the negotiated buffer sizes * so we can just send whatever is received. */ SmbTransport t1 = tree.session.transport; SmbTransport t2 = dest.tree.session.transport; if( t1.snd_buf_size < t2.snd_buf_size ) { t2.snd_buf_size = t1.snd_buf_size; } else { t1.snd_buf_size = t2.snd_buf_size; } bsize = Math.min( t1.rcv_buf_size - 70, t1.snd_buf_size - 70 ); b = new byte[2][bsize]; try { copyTo0( dest, b, bsize, w, req, resp ); } finally { w.write( null, -1, null, 0 ); } } /** * This method will delete the file or directory specified by this * <code>SmbFile</code>. If the target is a directory, the contents of * the directory will be deleted as well. If a file within the directory or * it's sub-directories is marked read-only, the read-only status will * be removed and the file will be deleted. * * @throws SmbException */ public void delete() throws SmbException { exists(); getUncPath0(); delete( unc ); } void delete( String fileName ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } if( System.currentTimeMillis() > attrExpiration ) { attributes = ATTR_READONLY | ATTR_DIRECTORY; createTime = 0L; lastModified = 0L; isExists = false; Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; isExists = true; } if(( attributes & ATTR_READONLY ) != 0 ) { setReadWrite(); } /* * Delete or Delete Directory Request / Response */ if( log.level >= 3 ) log.println( "delete: " + fileName ); if(( attributes & ATTR_DIRECTORY ) != 0 ) { /* Recursively delete directory contents */ try { SmbFile[] l = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null ); for( int i = 0; i < l.length; i++ ) { l[i].delete(); } } catch( SmbException se ) { /* Oracle FilesOnline version 9.0.4 doesn't send '.' and '..' so * listFiles may generate undesireable "cannot find * the file specified". */ if( se.getNtStatus() != SmbException.NT_STATUS_NO_SUCH_FILE ) { throw se; } } send( new SmbComDeleteDirectory( fileName ), blank_resp() ); } else { send( new SmbComDelete( fileName ), blank_resp() ); } attrExpiration = sizeExpiration = 0; } /** * Returns the length of this <tt>SmbFile</tt> in bytes. If this object * is a <tt>TYPE_SHARE</tt> the total capacity of the disk shared in * bytes is returned. If this object is a directory or a type other than * <tt>TYPE_SHARE</tt>, 0L is returned. * * @return The length of the file in bytes or 0 if this * <code>SmbFile</code> is not a file. * @throws SmbException */ public long length() throws SmbException { if( attrExpiration > System.currentTimeMillis() ) { return size; } if( getType() == TYPE_SHARE ) { Trans2QueryFSInformationResponse response; int level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION; response = new Trans2QueryFSInformationResponse( level ); send( new Trans2QueryFSInformation( level ), response ); size = response.info.getCapacity(); } else if( getUncPath0().length() > 1 && type != TYPE_NAMED_PIPE ) { Info info = queryPath( getUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_ALL_INFO ); attributes = info.getAttributes(); createTime = info.getCreateTime(); changeTime = info.getChangeTime(); lastModified = info.getLastWriteTime(); lastAccessed = info.getLastAccessTime(); attrExpiration = System.currentTimeMillis() + attrExpirationPeriod; size = info.getSize(); } else { size = 0L; } sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; return size; } /** * This method returns the free disk space in bytes of the drive this share * represents or the drive on which the directory or file resides. Objects * other than <tt>TYPE_SHARE</tt> or <tt>TYPE_FILESYSTEM</tt> will result * in 0L being returned. * * @return the free disk space in bytes of the drive on which this file or * directory resides */ public long getDiskFreeSpace() throws SmbException { if( getType() == TYPE_SHARE || type == TYPE_FILESYSTEM ) { int level = Trans2QueryFSInformationResponse.SMB_FS_FULL_SIZE_INFORMATION; try { return queryFSInformation(level); } catch( SmbException ex ) { switch (ex.getNtStatus()) { case NtStatus.NT_STATUS_INVALID_INFO_CLASS: case NtStatus.NT_STATUS_UNSUCCESSFUL: // NetApp Filer // SMB_FS_FULL_SIZE_INFORMATION not supported by the server. level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION; return queryFSInformation(level); } throw ex; } } return 0L; } private long queryFSInformation( int level ) throws SmbException { Trans2QueryFSInformationResponse response; response = new Trans2QueryFSInformationResponse( level ); send( new Trans2QueryFSInformation( level ), response ); if( type == TYPE_SHARE ) { size = response.info.getCapacity(); sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod; } return response.info.getFree(); } /** * Creates a directory with the path specified by this * <code>SmbFile</code>. For this method to be successful, the target * must not already exist. This method will fail when * used with <code>smb://</code>, <code>smb://workgroup/</code>, * <code>smb://server/</code>, or <code>smb://server/share/</code> URLs * because workgroups, servers, and shares cannot be dynamically created * (although in the future it may be possible to create shares). * * @throws SmbException */ public void mkdir() throws SmbException { String path = getUncPath0(); if( path.length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } /* * Create Directory Request / Response */ if( log.level >= 3 ) log.println( "mkdir: " + path ); send( new SmbComCreateDirectory( path ), blank_resp() ); attrExpiration = sizeExpiration = 0; } /** * Creates a directory with the path specified by this <tt>SmbFile</tt> * and any parent directories that do not exist. This method will fail * when used with <code>smb://</code>, <code>smb://workgroup/</code>, * <code>smb://server/</code>, or <code>smb://server/share/</code> URLs * because workgroups, servers, and shares cannot be dynamically created * (although in the future it may be possible to create shares). * * @throws SmbException */ public void mkdirs() throws SmbException { SmbFile parent; try { parent = new SmbFile( getParent(), auth ); } catch( IOException ioe ) { return; } if( parent.exists() == false ) { parent.mkdirs(); } mkdir(); } /** * Create a new file but fail if it already exists. The check for * existance of the file and it's creation are an atomic operation with * respect to other filesystem activities. */ public void createNewFile() throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } close( open0( O_RDWR | O_CREAT | O_EXCL, 0, ATTR_NORMAL, 0 ), 0L ); } void setPathInformation( int attrs, long ctime, long mtime ) throws SmbException { int f, dir; exists(); if (attrs == 0) { // not setting attributes.. so default it to what we currently have dir = attributes; } else { dir = attributes & ATTR_DIRECTORY; } f = open0( O_RDONLY, FILE_WRITE_ATTRIBUTES, dir, dir != 0 ? 0x0001 : 0x0040 ); send( new Trans2SetFileInformation( f, attrs | dir, ctime, mtime ), new Trans2SetFileInformationResponse() ); close( f, 0L ); attrExpiration = 0; } void setPathInformation( int attrs, long ctime, long atime, long mtime ) throws SmbException { int f, dir; exists(); if (attrs == 0) { // not setting attributes.. so default it to what we currently have dir = attributes; } else { dir = attributes & ATTR_DIRECTORY; } f = open0( O_RDONLY, FILE_WRITE_ATTRIBUTES, dir, dir != 0 ? 0x0001 : 0x0040 ); send( new Trans2SetFileInformation( f, attrs | dir, ctime, atime, mtime ), new Trans2SetFileInformationResponse() ); close( f, 0L ); attrExpiration = 0; } public void setTimes( long ctime, long atime, long mtime ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, ctime, atime, mtime ); } /** * Set the create time of the file. The time is specified as milliseconds * from Jan 1, 1970 which is the same as that which is returned by the * <tt>createTime()</tt> method. * <p/> * This method does not apply to workgroups, servers, or shares. * * @param time the create time as milliseconds since Jan 1, 1970 */ public void setCreateTime( long time ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, time, 0L ); } /** * Set the access time of the file. The time is specified as milliseconds * from Jan 1, 1970 which is the same as that which is returned by the * <tt>createTime()</tt> method. * <p/> * This method does not apply to workgroups, servers, or shares. * * @param time the create time as milliseconds since Jan 1, 1970 */ public void setAccessTime( long time ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, 0L, time, 0L ); } /** * Set the last modified time of the file. The time is specified as milliseconds * from Jan 1, 1970 which is the same as that which is returned by the * <tt>lastModified()</tt>, <tt>getLastModified()</tt>, and <tt>getDate()</tt> methods. * <p/> * This method does not apply to workgroups, servers, or shares. * * @param time the last modified time as milliseconds since Jan 1, 1970 */ public void setLastModified( long time ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( 0, 0L, time ); } /** * Return the attributes of this file. Attributes are represented as a * bitset that must be masked with <tt>ATTR_*</tt> constants to determine * if they are set or unset. The value returned is suitable for use with * the <tt>setAttributes()</tt> method. * * @return the <tt>ATTR_*</tt> attributes associated with this file * @throws SmbException */ public int getAttributes() throws SmbException { if( getUncPath0().length() == 1 ) { return 0; } exists(); return attributes & ATTR_GET_MASK; } /** * Set the attributes of this file. Attributes are composed into a * bitset by bitwise ORing the <tt>ATTR_*</tt> constants. Setting the * value returned by <tt>getAttributes</tt> will result in both files * having the same attributes. * @throws SmbException */ public void setAttributes( int attrs ) throws SmbException { if( getUncPath0().length() == 1 ) { throw new SmbException( "Invalid operation for workgroups, servers, or shares" ); } setPathInformation( attrs & ATTR_SET_MASK, 0L, 0L ); } /** * Make this file read-only. This is shorthand for <tt>setAttributes( * getAttributes() | ATTR_READ_ONLY )</tt>. * * @throws SmbException */ public void setReadOnly() throws SmbException { setAttributes( getAttributes() | ATTR_READONLY ); } /** * Turn off the read-only attribute of this file. This is shorthand for * <tt>setAttributes( getAttributes() & ~ATTR_READONLY )</tt>. * * @throws SmbException */ public void setReadWrite() throws SmbException { setAttributes( getAttributes() & ~ATTR_READONLY ); } /** * Returns a {@link java.net.URL} for this <code>SmbFile</code>. The * <code>URL</code> may be used as any other <code>URL</code> might to * access an SMB resource. Currently only retrieving data and information * is supported (i.e. no <tt>doOutput</tt>). * * @deprecated Use getURL() instead * @return A new <code>{@link java.net.URL}</code> for this <code>SmbFile</code> * @throws MalformedURLException */ public URL toURL() throws MalformedURLException { return url; } /** * Computes a hashCode for this file based on the URL string and IP * address if the server. The hashing function uses the hashcode of the * server address, the canonical representation of the URL, and does not * compare authentication information. In essance, two * <code>SmbFile</code> objects that refer to * the same file should generate the same hashcode provided it is possible * to make such a determination. * * @return A hashcode for this abstract file * @throws SmbException */ public int hashCode() { int hash; try { hash = getAddress().hashCode(); } catch( UnknownHostException uhe ) { hash = getServer().toUpperCase().hashCode(); } getUncPath0(); return hash + canon.toUpperCase().hashCode(); } protected boolean pathNamesPossiblyEqual(String path1, String path2) { int p1, p2, l1, l2; // if unsure return this method returns true p1 = path1.lastIndexOf('/'); p2 = path2.lastIndexOf('/'); l1 = path1.length() - p1; l2 = path2.length() - p2; // anything with dots voids comparison if (l1 > 1 && path1.charAt(p1 + 1) == '.') return true; if (l2 > 1 && path2.charAt(p2 + 1) == '.') return true; return l1 == l2 && path1.regionMatches(true, p1, path2, p2, l1); } /** * Tests to see if two <code>SmbFile</code> objects are equal. Two * SmbFile objects are equal when they reference the same SMB * resource. More specifically, two <code>SmbFile</code> objects are * equals if their server IP addresses are equal and the canonicalized * representation of their URLs, minus authentication parameters, are * case insensitivly and lexographically equal. * <p/> * For example, assuming the server <code>angus</code> resolves to the * <code>192.168.1.15</code> IP address, the below URLs would result in * <code>SmbFile</code>s that are equal. * * <p><blockquote><pre> * smb://192.168.1.15/share/DIR/foo.txt * smb://angus/share/data/../dir/foo.txt * </pre></blockquote> * * @param obj Another <code>SmbFile</code> object to compare for equality * @return <code>true</code> if the two objects refer to the same SMB resource * and <code>false</code> otherwise * @throws SmbException */ public boolean equals( Object obj ) { if (obj instanceof SmbFile) { SmbFile f = (SmbFile)obj; boolean ret; if (this == f) return true; /* If uncertain, pathNamesPossiblyEqual returns true. * Comparing canonical paths is definitive. */ if (pathNamesPossiblyEqual(url.getPath(), f.url.getPath())) { getUncPath0(); f.getUncPath0(); if (canon.equalsIgnoreCase(f.canon)) { try { ret = getAddress().equals(f.getAddress()); } catch( UnknownHostException uhe ) { ret = getServer().equalsIgnoreCase(f.getServer()); } return ret; } } } return false; } /* public boolean equals( Object obj ) { return obj instanceof SmbFile && obj.hashCode() == hashCode(); } */ /** * Returns the string representation of this SmbFile object. This will * be the same as the URL used to construct this <code>SmbFile</code>. * This method will return the same value * as <code>getPath</code>. * * @return The original URL representation of this SMB resource * @throws SmbException */ public String toString() { return url.toString(); } /* URLConnection implementation */ /** * This URLConnection method just returns the result of <tt>length()</tt>. * * @return the length of this file or 0 if it refers to a directory */ public int getContentLength() { try { return (int)(length() & 0xFFFFFFFFL); } catch( SmbException se ) { } return 0; } /** * This URLConnection method just returns the result of <tt>lastModified</tt>. * * @return the last modified data as milliseconds since Jan 1, 1970 */ public long getDate() { try { return lastModified(); } catch( SmbException se ) { } return 0L; } /** * This URLConnection method just returns the result of <tt>lastModified</tt>. * * @return the last modified data as milliseconds since Jan 1, 1970 */ public long getLastModified() { try { return lastModified(); } catch( SmbException se ) { } return 0L; } /** * This URLConnection method just returns a new <tt>SmbFileInputStream</tt> created with this file. * * @throws IOException thrown by <tt>SmbFileInputStream</tt> constructor */ public InputStream getInputStream() throws IOException { return new SmbFileInputStream( this ); } /** * This URLConnection method just returns a new <tt>SmbFileOutputStream</tt> created with this file. * * @throws IOException thrown by <tt>SmbFileOutputStream</tt> constructor */ public OutputStream getOutputStream() throws IOException { return new SmbFileOutputStream( this ); } private void processAces(ACE[] aces, boolean resolveSids) throws IOException { String server = getServerWithDfs(); int ai; if (resolveSids) { SID[] sids = new SID[aces.length]; String[] names = null; for (ai = 0; ai < aces.length; ai++) { sids[ai] = aces[ai].sid; } for (int off = 0; off < sids.length; off += 64) { int len = sids.length - off; if (len > 64) len = 64; SID.resolveSids(server, auth, sids, off, len); } } else { for (ai = 0; ai < aces.length; ai++) { aces[ai].sid.origin_server = server; aces[ai].sid.origin_auth = auth; } } } /** * -------------- MPRV PATCH ------------- * Get security descriptor * @param resolveSids true if the sids are resolved * @return security descriptor * @throws IOException */ public SecurityDescriptor getSecurityDescriptor(boolean resolveSids) throws IOException { int f; ACE[] aces; f = open0(O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0); /* * NtTrans Query Security Desc Request / Response */ NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); try { send(request, response); } finally { close(f, 0L); } return response.securityDescriptor; } /** * Return an array of Access Control Entry (ACE) objects representing * the security descriptor associated with this files or directory. * If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. * * @param resolveSids Attempt to resolve the SIDs within each ACE form * their numeric representation to their corresponding account names. */ public ACE[] getSecurity(boolean resolveSids) throws IOException { SecurityDescriptor sd = getSecurityDescriptor(resolveSids); ACE[] aces = sd.aces; if (aces != null) processAces(aces, resolveSids); return aces; } public SID getOwnerUser() throws IOException { int f = open0(O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0); /* * NtTrans Query Security Desc Request / Response */ NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x01); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); send(request, response); close(f, 0L); return response.securityDescriptor.owner_user; } public SID getOwnerGroup() throws IOException { int f = open0(O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0); /* * NtTrans Query Security Desc Request / Response */ NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x02); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); send(request, response); close(f, 0L); return response.securityDescriptor.owner_group; } /** * -------------- MPRV PATCH ------------- * @param sd security descriptor that will be revoked * @param sid user/group for which the permission will be revoked * @param maskToRevoke mask to revoke * @return error code * @throws IOException */ public int revokePermission(SecurityDescriptor sd, SID sid, int maskToRevoke) throws IOException { int f; f = open0(O_RDWR, WRITE_DAC, 0, isDirectory() ? 1 : 0); /* * NtTrans Update Security Desc Request / Response */ NtTransRevokePermissionInSecurityDesc request = new NtTransRevokePermissionInSecurityDesc(f, 0x04, sd, sid, maskToRevoke); NtTransSetSecurityDescResponse response = new NtTransSetSecurityDescResponse(); try { send(request, response); } finally { close(f, 0L); } return response.errorCode; } /** * Return an array of Access Control Entry (ACE) objects representing * the share permissions on the share exporting this file or directory. * If no DACL is present, null is returned. If the DACL is empty, an array with 0 elements is returned. * <p> * Note that this is different from calling <tt>getSecurity</tt> on a * share. There are actually two different ACLs for shares - the ACL on * the share and the ACL on the folder being shared. * Go to <i>Computer Management</i> * &gt; <i>System Tools</i> &gt; <i>Shared Folders</i> &gt <i>Shares</i> and * look at the <i>Properties</i> for a share. You will see two tabs - one * for "Share Permissions" and another for "Security". These correspond to * the ACLs returned by <tt>getShareSecurity</tt> and <tt>getSecurity</tt> * respectively. * @param resolveSids Attempt to resolve the SIDs within each ACE form * their numeric representation to their corresponding account names. */ public ACE[] getShareSecurity(boolean resolveSids) throws IOException { String p = url.getPath(); MsrpcShareGetInfo rpc; DcerpcHandle handle; ACE[] aces; resolveDfs(null); String server = getServerWithDfs(); rpc = new MsrpcShareGetInfo(server, tree.share); handle = DcerpcHandle.getHandle("ncacn_np:" + server + "[\\PIPE\\srvsvc]", auth); try { handle.sendrecv(rpc); if (rpc.retval != 0) throw new SmbException(rpc.retval, true); aces = rpc.getSecurity(); if (aces != null) processAces(aces, resolveSids); } finally { try { handle.close(); } catch(IOException ioe) { if (log.level >= 1) ioe.printStackTrace(log); } } return aces; } /** * Return an array of Access Control Entry (ACE) objects representing * the security descriptor associated with this file or directory. * <p> * Initially, the SIDs within each ACE will not be resolved however when * <tt>getType()</tt>, <tt>getDomainName()</tt>, <tt>getAccountName()</tt>, * or <tt>toString()</tt> is called, the names will attempt to be * resolved. If the names cannot be resolved (e.g. due to temporary * network failure), the said methods will return default values (usually * <tt>S-X-Y-Z</tt> strings of fragments of). * <p> * Alternatively <tt>getSecurity(true)</tt> may be used to resolve all * SIDs together and detect network failures. */ public ACE[] getSecurity() throws IOException { return getSecurity(false); } /** * Gets the server's time * @return time on server (milliseconds since 1970) * @throws SmbException error negotiating with server */ public long serverTime() throws SmbException { if (tree == null) exists(); return tree.session.transport.server.serverTime; } /** * Gets the server's time * @return time on server * @throws SmbException error negotiating with server */ public Date getServerTime() throws SmbException { return new Date(serverTime()); } public String getFilesystem() throws SmbException { if (tree == null) exists(); return tree.filesystem; } public int setOwner(SID owner) throws IOException { int f; f = open0(O_RDWR | O_EXCL, WRITE_DAC | WRITE_OWNER, 0, isDirectory() ? 1 : 0x4000); /* * NtTrans Update Security Desc Request / Response */ NtTransSetSecurityDescOwner request = new NtTransSetSecurityDescOwner(f, owner); NtTransSetSecurityDescResponse response = new NtTransSetSecurityDescResponse(); try { send(request, response); } finally { close(f, 0L); } return response.errorCode; } public void expireCachedAttributes() { attrExpiration = 0; } }
call open0 only with 0L or 0x10 attr mask
src/jcifs/smb/SmbFile.java
call open0 only with 0L or 0x10 attr mask
<ide><path>rc/jcifs/smb/SmbFile.java <ide> } <ide> <ide> f = open0( O_RDONLY, FILE_WRITE_ATTRIBUTES, <del> dir, dir != 0 ? 0x0001 : 0x0040 ); <add> dir & ATTR_DIRECTORY, (dir & ATTR_DIRECTORY) != 0 ? 0x0001 : 0x0040 ); <ide> send( new Trans2SetFileInformation( f, attrs | dir, ctime, atime, mtime ), <ide> new Trans2SetFileInformationResponse() ); <ide> close( f, 0L );
Java
mit
f61a18e1a154472ee291fdf88b6cf8a028588757
0
tsdl2013/SimpleFlatMapper,tsdl2013/SimpleFlatMapper,arnaudroger/SimpleFlatMapper,arnaudroger/SimpleFlatMapper,arnaudroger/SimpleFlatMapper
package org.sfm.jdbc; import static org.junit.Assert.assertEquals; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import org.sfm.beans.DbObject; import org.sfm.utils.DateHelper; import org.sfm.utils.Handler; public class DbHelper { private static final int NB_BENCHMARK_OBJECT = 10000; private static boolean objectDb; public static Connection objectDb() throws SQLException { Connection c = newHsqlDbConnection(); if (!objectDb) { Statement st = c.createStatement(); try { createDbObject(st); st.execute("insert into TEST_DB_OBJECT values(1, 'name 1', '[email protected]', TIMESTAMP'2014-03-04 11:10:03', 2, 'type4')"); c.commit(); } finally { st.close(); } } objectDb = true; return c; } public static void assertDbObjectMapping(DbObject dbObject) throws ParseException { assertEquals(1, dbObject.getId()); assertEquals("name 1", dbObject.getName()); assertEquals("[email protected]", dbObject.getEmail()); assertEquals(DateHelper.toDate("2014-03-04 11:10:03"), dbObject.getCreationTime()); assertEquals(DbObject.Type.type3, dbObject.getTypeOrdinal()); assertEquals(DbObject.Type.type4, dbObject.getTypeName()); } public static Connection benchmarkHsqlDb() throws SQLException { //Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:benchmarkdb", "SA", ""); Connection c = newHsqlDbConnection(); createTableAndInsertData(c); return c; } public static Connection benchmarkMysqlDb() throws SQLException { //Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:benchmarkdb", "SA", ""); Connection c = newMysqlDbConnection(); createTableAndInsertData(c); return c; } private static void createTableAndInsertData(Connection c) throws SQLException { Statement st = c.createStatement(); try { try { ResultSet rs = st.executeQuery("select count(*) from test_small_benchmark_object"); rs.next(); if (rs.getLong(1) == NB_BENCHMARK_OBJECT) { return; } }catch(Exception e) { // ignore } createSmallBenchmarkObject(st); PreparedStatement ps = c.prepareStatement("insert into test_small_benchmark_object values(?, ?, ?, ?)"); for(int i = 0; i < NB_BENCHMARK_OBJECT; i++) { ps.setLong(1, i); ps.setString(2, "name " + i); ps.setString(3, "name" + i + "@gmail.com"); ps.setInt(4, 2000 + (i % 14)); ps.execute(); } } finally { st.close(); } } private static void createDbObject(Statement st) throws SQLException { st.execute("create table test_db_object(" + " id bigint not null primary key," + " name varchar(100), " + " email varchar(100)," + " creation_Time timestamp, type_ordinal int, type_name varchar(10) )"); } private static void createSmallBenchmarkObject(Statement st) throws SQLException { st.execute("create table test_small_benchmark_object(" + " id bigint not null primary key," + " name varchar(100), " + " email varchar(100)," + " year_started int )"); } private static Connection newHsqlDbConnection() throws SQLException { return DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb", "SA", ""); } private static Connection newMysqlDbConnection() throws SQLException { return DriverManager.getConnection("jdbc:mysql://localhost/sfm", "sfm", ""); } public static void testDbObjectFromDb(Handler<PreparedStatement> handler ) throws SQLException, Exception, ParseException { Connection conn = DbHelper.objectDb(); try { PreparedStatement ps = conn.prepareStatement("select id, name, email, creation_time, type_ordinal, type_name from TEST_DB_OBJECT where id = 1 "); try { handler.handle(ps); } finally { ps.close(); } } finally { conn.close(); } } }
src/test/java/org/sfm/jdbc/DbHelper.java
package org.sfm.jdbc; import static org.junit.Assert.assertEquals; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import org.sfm.beans.DbObject; import org.sfm.utils.DateHelper; import org.sfm.utils.Handler; public class DbHelper { private static final int NB_BENCHMARK_OBJECT = 10000; private static boolean objectDb; public static Connection objectDb() throws SQLException { Connection c = newHsqlDbConnection(); if (!objectDb) { Statement st = c.createStatement(); try { createDbObject(st); st.execute("insert into TEST_DB_OBJECT values(1, 'name 1', '[email protected]', TIMESTAMP'2014-03-04 11:10:03', 2, 'type4')"); c.commit(); } finally { st.close(); } } objectDb = true; return c; } public static void assertDbObjectMapping(DbObject dbObject) throws ParseException { assertEquals(1, dbObject.getId()); assertEquals("name 1", dbObject.getName()); assertEquals("[email protected]", dbObject.getEmail()); assertEquals(DateHelper.toDate("2014-03-04 11:10:03"), dbObject.getCreationTime()); assertEquals(DbObject.Type.type3, dbObject.getTypeOrdinal()); assertEquals(DbObject.Type.type4, dbObject.getTypeName()); } public static Connection benchmarkHsqlDb() throws SQLException { //Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:benchmarkdb", "SA", ""); Connection c = newHsqlDbConnection(); createTableAndInsertData(c); return c; } public static Connection benchmarkMysqlDb() throws SQLException { //Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:benchmarkdb", "SA", ""); Connection c = newMysqlDbConnection(); createTableAndInsertData(c); return c; } private static void createTableAndInsertData(Connection c) throws SQLException { Statement st = c.createStatement(); try { createSmallBenchmarkObject(st); PreparedStatement ps = c.prepareStatement("insert into test_small_benchmark_object values(?, ?, ?, ?)"); for(int i = 0; i < NB_BENCHMARK_OBJECT; i++) { ps.setLong(1, i); ps.setString(2, "name " + i); ps.setString(3, "name" + i + "@gmail.com"); ps.setInt(4, 2000 + (i % 14)); ps.execute(); } } finally { st.close(); } } private static void createDbObject(Statement st) throws SQLException { st.execute("create table test_db_object(" + " id bigint not null primary key," + " name varchar(100), " + " email varchar(100)," + " creation_Time timestamp, type_ordinal int, type_name varchar(10) )"); } private static void createSmallBenchmarkObject(Statement st) throws SQLException { try { ResultSet rs = st.executeQuery("select count(*) table test_small_benchmark_object"); rs.next(); if (rs.getLong(1) == NB_BENCHMARK_OBJECT) { return; } }catch(Exception e) { // ignore } st.execute("create table test_small_benchmark_object(" + " id bigint not null primary key," + " name varchar(100), " + " email varchar(100)," + " year_started int )"); } private static Connection newHsqlDbConnection() throws SQLException { return DriverManager.getConnection("jdbc:hsqldb:mem:mymemdb", "SA", ""); } private static Connection newMysqlDbConnection() throws SQLException { return DriverManager.getConnection("jdbc:mysql://localhost/sfm", "sfm", ""); } public static void testDbObjectFromDb(Handler<PreparedStatement> handler ) throws SQLException, Exception, ParseException { Connection conn = DbHelper.objectDb(); try { PreparedStatement ps = conn.prepareStatement("select id, name, email, creation_time, type_ordinal, type_name from TEST_DB_OBJECT where id = 1 "); try { handler.handle(ps); } finally { ps.close(); } } finally { conn.close(); } } }
fix check if table already exists
src/test/java/org/sfm/jdbc/DbHelper.java
fix check if table already exists
<ide><path>rc/test/java/org/sfm/jdbc/DbHelper.java <ide> Statement st = c.createStatement(); <ide> <ide> try { <add> try { <add> ResultSet rs = st.executeQuery("select count(*) from test_small_benchmark_object"); <add> rs.next(); <add> if (rs.getLong(1) == NB_BENCHMARK_OBJECT) { <add> return; <add> } <add> }catch(Exception e) { <add> // ignore <add> } <add> <ide> createSmallBenchmarkObject(st); <ide> <ide> PreparedStatement ps = c.prepareStatement("insert into test_small_benchmark_object values(?, ?, ?, ?)"); <ide> } <ide> <ide> private static void createSmallBenchmarkObject(Statement st) throws SQLException { <del> try { <del> ResultSet rs = st.executeQuery("select count(*) table test_small_benchmark_object"); <del> rs.next(); <del> if (rs.getLong(1) == NB_BENCHMARK_OBJECT) { <del> return; <del> } <del> }catch(Exception e) { <del> // ignore <del> } <del> <ide> st.execute("create table test_small_benchmark_object(" <ide> + " id bigint not null primary key," <ide> + " name varchar(100), "
Java
mit
1a137227b6995a735555250b16251157d830c3f7
0
GluuFederation/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,madumlao/oxTrust,madumlao/oxTrust
/* * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2017, Gluu */ package org.gluu.oxtrust.api.saml; import javax.inject.Inject; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.gluu.oxtrust.util.OxTrustConstants; /** * WS endpoint for TrustRelationship actions. * * @author Dmitry Ognyannikov */ @Path("/saml/tr") public class TrustRelationshipWebService { //TODO @GET @Path("/read/{inum}/") @Produces(MediaType.APPLICATION_JSON) public String read(@PathParam("inum") String inum) { String result = null; //TODO return result; } @POST @Path("/create") @Produces(MediaType.TEXT_PLAIN) public String create() { String inum = null; //TODO return inum; } @PUT @Path("/update/{inum}/") @Produces(MediaType.TEXT_PLAIN) public String update(@PathParam("inum") String inum) { //TODO return OxTrustConstants.RESULT_SUCCESS; } @DELETE @Path("/delete/{inum}/") @Produces(MediaType.TEXT_PLAIN) public String delete(@PathParam("inum") String inum) { //TODO return OxTrustConstants.RESULT_SUCCESS; } @GET @Path("/list/") @Produces(MediaType.APPLICATION_JSON) public String list() { String list = null; //TODO return list; } }
server/src/main/java/org/gluu/oxtrust/api/saml/TrustRelationshipWebService.java
/* * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2017, Gluu */ package org.gluu.oxtrust.api.saml; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * WS endpoint for TrustRelationship actions. * * @author Dmitry Ognyannikov */ @Path("/saml/tr") public class TrustRelationshipWebService { //TODO public void read() { //TODO } public void create() { //TODO } public void update() { //TODO } public void delete() { //TODO } public void list() { //TODO } }
Prepare working prototype which demonstrates oxTrust API #784
server/src/main/java/org/gluu/oxtrust/api/saml/TrustRelationshipWebService.java
Prepare working prototype which demonstrates oxTrust API #784
<ide><path>erver/src/main/java/org/gluu/oxtrust/api/saml/TrustRelationshipWebService.java <ide> package org.gluu.oxtrust.api.saml; <ide> <ide> import javax.inject.Inject; <add>import javax.ws.rs.DELETE; <ide> import javax.ws.rs.GET; <add>import javax.ws.rs.POST; <add>import javax.ws.rs.PUT; <ide> import javax.ws.rs.Path; <ide> import javax.ws.rs.PathParam; <ide> import javax.ws.rs.Produces; <ide> import javax.ws.rs.core.MediaType; <add>import org.gluu.oxtrust.util.OxTrustConstants; <ide> <ide> /** <ide> * WS endpoint for TrustRelationship actions. <ide> public class TrustRelationshipWebService { <ide> //TODO <ide> <del> public void read() { <add> @GET <add> @Path("/read/{inum}/") <add> @Produces(MediaType.APPLICATION_JSON) <add> public String read(@PathParam("inum") String inum) { <add> String result = null; <ide> //TODO <add> return result; <ide> } <ide> <del> public void create() { <add> @POST <add> @Path("/create") <add> @Produces(MediaType.TEXT_PLAIN) <add> public String create() { <add> String inum = null; <ide> //TODO <add> return inum; <ide> } <ide> <del> public void update() { <add> @PUT <add> @Path("/update/{inum}/") <add> @Produces(MediaType.TEXT_PLAIN) <add> public String update(@PathParam("inum") String inum) { <ide> //TODO <add> return OxTrustConstants.RESULT_SUCCESS; <ide> } <ide> <del> public void delete() { <add> @DELETE <add> @Path("/delete/{inum}/") <add> @Produces(MediaType.TEXT_PLAIN) <add> public String delete(@PathParam("inum") String inum) { <ide> //TODO <add> return OxTrustConstants.RESULT_SUCCESS; <ide> } <ide> <del> public void list() { <add> @GET <add> @Path("/list/") <add> @Produces(MediaType.APPLICATION_JSON) <add> public String list() { <add> String list = null; <ide> //TODO <add> return list; <ide> } <ide> <ide>
Java
apache-2.0
7eadcd597f2b7be526f55a897152e6375aa8db82
0
Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.editors.sql; import org.eclipse.jface.action.*; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.*; import org.eclipse.jface.text.rules.FastPartitioner; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.source.*; import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; import org.eclipse.jface.text.source.projection.ProjectionSupport; import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.internal.editors.text.EditorsPlugin; import org.eclipse.ui.texteditor.*; import org.eclipse.ui.texteditor.templates.ITemplatesPage; import org.eclipse.ui.themes.IThemeManager; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.core.CoreCommands; import org.jkiss.dbeaver.core.DBeaverActivator; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.*; import org.jkiss.dbeaver.ui.ActionUtils; import org.jkiss.dbeaver.ui.ICommentsSupport; import org.jkiss.dbeaver.ui.IErrorVisualizer; import org.jkiss.dbeaver.ui.TextUtils; import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner; import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLRuleManager; import org.jkiss.dbeaver.ui.editors.sql.syntax.tokens.SQLToken; import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesPage; import org.jkiss.dbeaver.ui.editors.sql.util.SQLSymbolInserter; import org.jkiss.dbeaver.ui.editors.text.BaseTextEditor; import org.jkiss.dbeaver.ui.preferences.*; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.Pair; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; /** * SQL Executor */ public abstract class SQLEditorBase extends BaseTextEditor implements IErrorVisualizer { static protected final Log log = Log.getLog(SQLEditorBase.class); public static final String SQL_EDITOR_CONTEXT = "org.jkiss.dbeaver.ui.editors.sql"; static { // SQL editor preferences. Do this here because it initializes display // (that's why we can't run it in prefs initializer classes which run before workbench creation) { IPreferenceStore editorStore = EditorsPlugin.getDefault().getPreferenceStore(); editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS, true); editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS_COLOR, "128,128,128"); } } @NotNull private final SQLSyntaxManager syntaxManager; @NotNull private final SQLRuleManager ruleManager; private ProjectionSupport projectionSupport; private ProjectionAnnotationModel annotationModel; //private Map<Annotation, Position> curAnnotations; private IAnnotationAccess annotationAccess; private boolean hasVerticalRuler = true; private SQLTemplatesPage templatesPage; private IPropertyChangeListener themeListener; public SQLEditorBase() { super(); syntaxManager = new SQLSyntaxManager(); ruleManager = new SQLRuleManager(syntaxManager); themeListener = new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME) || event.getProperty().startsWith("org.jkiss.dbeaver.sql.editor")) { reloadSyntaxRules(); // Reconfigure to let comments/strings colors to take effect getSourceViewer().configure(getSourceViewerConfiguration()); } } }; PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(themeListener); //setDocumentProvider(new SQLDocumentProvider()); setSourceViewerConfiguration(new SQLEditorSourceViewerConfiguration(this, getPreferenceStore())); setKeyBindingScopes(new String[]{TEXT_EDITOR_CONTEXT, SQL_EDITOR_CONTEXT}); //$NON-NLS-1$ } @Nullable public abstract DBCExecutionContext getExecutionContext(); public final DBPDataSource getDataSource() { DBCExecutionContext context = getExecutionContext(); return context == null ? null : context.getDataSource(); } public DBPPreferenceStore getActivePreferenceStore() { if (this instanceof IDataSourceContainerProvider) { DBPDataSourceContainer container = ((IDataSourceContainerProvider) this).getDataSourceContainer(); if (container != null) { return container.getPreferenceStore(); } } DBPDataSource dataSource = getDataSource(); return dataSource == null ? DBeaverCore.getGlobalPreferenceStore() : dataSource.getContainer().getPreferenceStore(); } @NotNull public SQLDialect getSQLDialect() { DBPDataSource dataSource = getDataSource(); // Refresh syntax if (dataSource instanceof SQLDataSource) { return ((SQLDataSource) dataSource).getSQLDialect(); } return BasicSQLDialect.INSTANCE; } public boolean hasAnnotations() { return false; } @NotNull public SQLSyntaxManager getSyntaxManager() { return syntaxManager; } @NotNull public SQLRuleManager getRuleManager() { return ruleManager; } public ProjectionAnnotationModel getAnnotationModel() { return annotationModel; } public SQLEditorSourceViewerConfiguration getViewerConfiguration() { return (SQLEditorSourceViewerConfiguration) super.getSourceViewerConfiguration(); } @Override public void createPartControl(Composite parent) { setRangeIndicator(new DefaultRangeIndicator()); super.createPartControl(new SQLEditorControl(parent, this)); ProjectionViewer viewer = (ProjectionViewer) getSourceViewer(); projectionSupport = new ProjectionSupport( viewer, getAnnotationAccess(), getSharedColors()); projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$ projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$ projectionSupport.install(); viewer.doOperation(ProjectionViewer.TOGGLE); annotationModel = viewer.getProjectionAnnotationModel(); // Symbol inserter { SQLSymbolInserter symbolInserter = new SQLSymbolInserter(this); DBPPreferenceStore preferenceStore = getActivePreferenceStore(); boolean closeSingleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_SINGLE_QUOTES); boolean closeDoubleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_DOUBLE_QUOTES); boolean closeBrackets = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_BRACKETS); symbolInserter.setCloseSingleQuotesEnabled(closeSingleQuotes); symbolInserter.setCloseDoubleQuotesEnabled(closeDoubleQuotes); symbolInserter.setCloseBracketsEnabled(closeBrackets); ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) { ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(symbolInserter); } } } @Override public void updatePartControl(IEditorInput input) { super.updatePartControl(input); } @Override protected IVerticalRuler createVerticalRuler() { return hasVerticalRuler ? super.createVerticalRuler() : new VerticalRuler(0); } public void setHasVerticalRuler(boolean hasVerticalRuler) { this.hasVerticalRuler = hasVerticalRuler; } protected ISharedTextColors getSharedColors() { return DBeaverUI.getSharedTextColors(); } @Override protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { fAnnotationAccess= getAnnotationAccess(); fOverviewRuler= createOverviewRuler(getSharedColors()); SQLEditorSourceViewer sourceViewer = createSourceViewer(parent, ruler, styles, fOverviewRuler); getSourceViewerDecorationSupport(sourceViewer); return sourceViewer; } protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { char[] matchChars = {'(', ')', '[', ']', '{', '}'}; //which brackets to match ICharacterPairMatcher matcher; try { matcher = new DefaultCharacterPairMatcher(matchChars, SQLPartitionScanner.SQL_PARTITIONING, true); } catch (Throwable e) { // If we below Eclipse 4.2.1 matcher = new DefaultCharacterPairMatcher(matchChars, SQLPartitionScanner.SQL_PARTITIONING); } support.setCharacterPairMatcher(matcher); support.setMatchingCharacterPainterPreferenceKeys(SQLPreferenceConstants.MATCHING_BRACKETS, SQLPreferenceConstants.MATCHING_BRACKETS_COLOR); super.configureSourceViewerDecorationSupport(support); } @NotNull protected SQLEditorSourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles, IOverviewRuler overviewRuler) { return new SQLEditorSourceViewer( parent, ruler, overviewRuler, true, styles); } @Override protected IAnnotationAccess createAnnotationAccess() { return new SQLMarkerAnnotationAccess(); } /* protected void adjustHighlightRange(int offset, int length) { ISourceViewer viewer = getSourceViewer(); if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; extension.exposeModelRange(new Region(offset, length)); } } */ @Override public Object getAdapter(Class required) { if (projectionSupport != null) { Object adapter = projectionSupport.getAdapter( getSourceViewer(), required); if (adapter != null) return adapter; } if (ITemplatesPage.class.equals(required)) { return getTemplatesPage(); } return super.getAdapter(required); } public SQLTemplatesPage getTemplatesPage() { if (templatesPage == null) templatesPage = new SQLTemplatesPage(this); return templatesPage; } @Override public void dispose() { if (themeListener != null) { PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(themeListener); themeListener = null; } super.dispose(); } @Override protected void createActions() { super.createActions(); ResourceBundle bundle = DBeaverActivator.getCoreResourceBundle(); IAction a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL), this, ISourceViewer.CONTENTASSIST_PROPOSALS); a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL, a); a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP), this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP, a); a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION), this, ISourceViewer.INFORMATION); a.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_INFORMATION); setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION, a); a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL), this, ISourceViewer.FORMAT); a.setActionDefinitionId(CoreCommands.CMD_CONTENT_FORMAT); setAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL, a); setAction(ITextEditorActionConstants.CONTEXT_PREFERENCES, new Action("Preferences...") { //$NON-NLS-1$ public void run() { Shell shell = getSourceViewer().getTextWidget().getShell(); String[] preferencePages = collectContextMenuPreferencePages(); if (preferencePages.length > 0 && (shell == null || !shell.isDisposed())) PreferencesUtil.createPreferenceDialogOn(shell, preferencePages[0], preferencePages, getEditorInput()).open(); } }); /* // Add the task action to the Edit pulldown menu (bookmark action is 'free') ResourceAction ra = new AddTaskAction(bundle, "AddTask.", this); ra.setHelpContextId(ITextEditorHelpContextIds.ADD_TASK_ACTION); ra.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(IDEActionFactory.ADD_TASK.getId(), ra); */ } @Override public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); menu.add(new Separator("content"));//$NON-NLS-1$ addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL); addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP); addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION); { MenuManager formatMenu = new MenuManager("Format", "format"); IAction formatAction = getAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL); if (formatAction != null) { formatMenu.add(formatAction); } formatMenu.add(getAction(ITextEditorActionConstants.UPPER_CASE)); formatMenu.add(getAction(ITextEditorActionConstants.LOWER_CASE)); formatMenu.add(new Separator()); formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.word.wrap")); formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.single")); formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.multi")); menu.insertAfter(GROUP_SQL_ADDITIONS, formatMenu); } } public void reloadSyntaxRules() { // Refresh syntax SQLDialect dialect = getSQLDialect(); syntaxManager.init(dialect, getActivePreferenceStore()); ruleManager.refreshRules(getDataSource(), getEditorInput()); Document document = getDocument(); if (document != null) { IDocumentPartitioner partitioner = new FastPartitioner( new SQLPartitionScanner(dialect), SQLPartitionScanner.SQL_CONTENT_TYPES); partitioner.connect(document); document.setDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING, partitioner); ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); if (projectionViewer != null && projectionViewer.getAnnotationModel() != null && document.getLength() > 0) { // Refresh viewer //projectionViewer.getTextWidget().redraw(); try { projectionViewer.reinitializeProjection(); } catch (Throwable ex) { // We can catch OutOfMemory here for too big/complex documents log.warn("Can't initialize SQL syntax projection", ex); //$NON-NLS-1$ } } } /* Color fgColor = ruleManager.getColor(SQLConstants.CONFIG_COLOR_TEXT); Color bgColor = ruleManager.getColor(getDataSource() == null ? SQLConstants.CONFIG_COLOR_DISABLED : SQLConstants.CONFIG_COLOR_BACKGROUND); final StyledText textWidget = getTextViewer().getTextWidget(); if (fgColor != null) { textWidget.setForeground(fgColor); } textWidget.setBackground(bgColor); */ // Update configuration if (getSourceViewerConfiguration() instanceof SQLEditorSourceViewerConfiguration) { ((SQLEditorSourceViewerConfiguration) getSourceViewerConfiguration()).onDataSourceChange(); } final IVerticalRuler verticalRuler = getVerticalRuler(); if (verticalRuler != null) { verticalRuler.update(); } } public boolean hasActiveQuery() { Document document = getDocument(); if (document == null) { return false; } ISelectionProvider selectionProvider = getSelectionProvider(); if (selectionProvider == null) { return false; } ITextSelection selection = (ITextSelection) selectionProvider.getSelection(); String selText = selection.getText(); if (CommonUtils.isEmpty(selText) && selection.getOffset() >= 0 && selection.getOffset() < document.getLength()) { try { IRegion lineRegion = document.getLineInformationOfOffset(selection.getOffset()); selText = document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException e) { log.warn(e); return false; } } return !CommonUtils.isEmptyTrimmed(selText); } @Nullable protected SQLScriptElement extractActiveQuery() { SQLScriptElement element; ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); String selText = selection.getText().trim(); selText = SQLUtils.trimQueryStatement(getSyntaxManager(), selText); if (!CommonUtils.isEmpty(selText)) { SQLScriptElement parsedElement = parseQuery(getDocument(), selection.getOffset(), selection.getOffset() + selection.getLength(), selection.getOffset(), false); if (parsedElement instanceof SQLControlCommand) { // This is a command element = parsedElement; } else { // Use selected query as is element = new SQLQuery(getDataSource(), selText, selection.getOffset(), selection.getLength()); } } else if (selection.getOffset() >= 0) { element = extractQueryAtPos(selection.getOffset()); } else { element = null; } // Check query do not ends with delimiter // (this may occur if user selected statement including delimiter) if (element == null || CommonUtils.isEmpty(element.getText())) { return null; } if (element instanceof SQLQuery && getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED)) { ((SQLQuery)element).setParameters(parseParameters(getDocument(), (SQLQuery)element)); } return element; } public SQLScriptElement extractQueryAtPos(int currentPos) { Document document = getDocument(); if (document == null || document.getLength() == 0) { return null; } final int docLength = document.getLength(); IDocumentPartitioner partitioner = document.getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING); if (partitioner != null) { // Move to default partition. We don't want to be in the middle of multi-line comment or string while (currentPos < docLength && isMultiCommentPartition(partitioner, currentPos)) { currentPos++; } } // Extract part of document between empty lines int startPos = 0; boolean useBlankLines = syntaxManager.isBlankLineDelimiter(); final String[] statementDelimiters = syntaxManager.getStatementDelimiters(); try { int currentLine = document.getLineOfOffset(currentPos); int lineOffset = document.getLineOffset(currentLine); if (TextUtils.isEmptyLine(document, currentLine)) { return null; } int firstLine = currentLine; while (firstLine > 0) { if (useBlankLines) { if (TextUtils.isEmptyLine(document, firstLine) && isDefaultPartition(partitioner, document.getLineOffset(firstLine))) { break; } } else { for (String delim : statementDelimiters) { final int offset = TextUtils.getOffsetOf(document, firstLine, delim); if (offset >= 0 && isDefaultPartition(partitioner, offset)) { break; } } } firstLine--; } startPos = document.getLineOffset(firstLine); // Move currentPos at line begin currentPos = lineOffset; } catch (BadLocationException e) { log.warn(e); } return parseQuery(document, startPos, document.getLength(), currentPos, false); } public SQLScriptElement extractNextQuery(boolean next) { ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); int offset = selection.getOffset(); SQLScriptElement curElement = extractQueryAtPos(offset); if (curElement == null) { return null; } Document document = getDocument(); if (document == null) { return null; } try { int docLength = document.getLength(); int curPos; if (next) { final String[] statementDelimiters = syntaxManager.getStatementDelimiters(); curPos = curElement.getOffset() + curElement.getLength(); while (curPos < docLength) { char c = document.getChar(curPos); if (!Character.isWhitespace(c)) { boolean isDelimiter = false; for (String delim : statementDelimiters) { if (delim.indexOf(c) != -1) { isDelimiter = true; } } if (!isDelimiter) { break; } } curPos++; } } else { curPos = curElement.getOffset() - 1; while (curPos >= 0) { char c = document.getChar(curPos); if (!Character.isWhitespace(c)) { break; } curPos--; } } if (curPos <= 0 || curPos >= docLength) { return null; } return extractQueryAtPos(curPos); } catch (BadLocationException e) { log.warn(e); return null; } } private static boolean isDefaultPartition(IDocumentPartitioner partitioner, int currentPos) { return partitioner == null || IDocument.DEFAULT_CONTENT_TYPE.equals(partitioner.getContentType(currentPos)); } private static boolean isMultiCommentPartition(IDocumentPartitioner partitioner, int currentPos) { return partitioner != null && SQLPartitionScanner.CONTENT_TYPE_SQL_MULTILINE_COMMENT.equals(partitioner.getContentType(currentPos)); } protected void startScriptEvaluation() { ruleManager.startEval(); } protected void endScriptEvaluation() { ruleManager.endEval(); } protected SQLScriptElement parseQuery(final IDocument document, final int startPos, final int endPos, final int currentPos, final boolean scriptMode) { if (endPos - startPos <= 0) { return null; } SQLDialect dialect = getSQLDialect(); // Parse range boolean useBlankLines = !scriptMode && syntaxManager.isBlankLineDelimiter(); ruleManager.setRange(document, startPos, endPos - startPos); int statementStart = startPos; int bracketDepth = 0; boolean hasBlocks = false; boolean hasValuableTokens = false; boolean hasBlockHeader = false; String blockTogglePattern = null; int lastTokenLineFeeds = 0; for (; ; ) { IToken token = ruleManager.nextToken(); int tokenOffset = ruleManager.getTokenOffset(); int tokenLength = ruleManager.getTokenLength(); int tokenType = token instanceof SQLToken ? ((SQLToken)token).getType() : SQLToken.T_UNKNOWN; boolean isDelimiter = tokenType == SQLToken.T_DELIMITER; boolean isControl = false; String delimiterText = null; if (isDelimiter) { // Save delimiter text try { delimiterText = document.get(tokenOffset, tokenLength); } catch (BadLocationException e) { log.debug(e); } } else if (useBlankLines && token.isWhitespace() && tokenLength >= 2) { // Check for blank line delimiter if (lastTokenLineFeeds + countLineFeeds(document, tokenOffset, tokenLength) >= 2) { isDelimiter = true; } } lastTokenLineFeeds = 0; if (tokenLength == 1) { // Check for bracket block begin/end try { char aChar = document.getChar(tokenOffset); if (aChar == '(' || aChar == '{' || aChar == '[') { bracketDepth++; } else if (aChar == ')' || aChar == '}' || aChar == ']') { bracketDepth--; } } catch (BadLocationException e) { log.warn(e); } } if (tokenType == SQLToken.T_BLOCK_HEADER) { bracketDepth++; hasBlocks = true; hasBlockHeader = true; } else if (tokenType == SQLToken.T_BLOCK_TOGGLE) { String togglePattern; try { togglePattern = document.get(tokenOffset, tokenLength); } catch (BadLocationException e) { log.warn(e); togglePattern = ""; } // Second toggle pattern must be the same as first one. // Toggles can be nested (PostgreSQL) and we need to count only outer if (bracketDepth == 1 && togglePattern.equals(blockTogglePattern)) { bracketDepth--; blockTogglePattern = null; } else if (bracketDepth == 0 && blockTogglePattern == null) { bracketDepth++; blockTogglePattern = togglePattern; } else { log.debug("Block toggle token inside another block. Can't process it"); } hasBlocks = true; } else if (tokenType == SQLToken.T_BLOCK_BEGIN) { if (!hasBlockHeader) { bracketDepth++; } hasBlocks = true; } else if (bracketDepth > 0 && tokenType == SQLToken.T_BLOCK_END) { // Sometimes query contains END clause without BEGIN. E.g. CASE, IF, etc. // This END doesn't mean block if (hasBlocks) { bracketDepth--; } hasBlockHeader = false; } else if (isDelimiter && bracketDepth > 0) { // Delimiter in some brackets - ignore it continue; } else if (tokenType == SQLToken.T_SET_DELIMITER || tokenType == SQLToken.T_CONTROL) { isDelimiter = true; isControl = true; } else if (tokenType == SQLToken.T_COMMENT) { lastTokenLineFeeds = tokenLength < 2 ? 0 : countLineFeeds(document, tokenOffset + tokenLength - 2, 2); } boolean cursorInsideToken = currentPos >= tokenOffset && currentPos < tokenOffset + tokenLength; if (isControl && cursorInsideToken) { // Control query try { String controlText = document.get(tokenOffset, tokenLength); return new SQLControlCommand( getDataSource(), syntaxManager, controlText.trim(), tokenOffset, tokenLength, tokenType == SQLToken.T_SET_DELIMITER); } catch (BadLocationException e) { log.warn("Can't extract control statement", e); //$NON-NLS-1$ return null; } } if (hasValuableTokens && (token.isEOF() || (isDelimiter && tokenOffset >= currentPos) || tokenOffset > endPos)) { if (tokenOffset > endPos) { tokenOffset = endPos; } if (tokenOffset >= document.getLength()) { // Sometimes (e.g. when comment finishing script text) // last token offset is beyond document range tokenOffset = document.getLength(); } assert (tokenOffset >= currentPos); try { // remove leading spaces while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(statementStart))) { statementStart++; } // remove trailing spaces while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(tokenOffset - 1))) { tokenOffset--; tokenLength++; } if (tokenOffset == statementStart) { // Empty statement if (token.isEOF()) { return null; } statementStart = tokenOffset + tokenLength; continue; } String queryText = document.get(statementStart, tokenOffset - statementStart); queryText = SQLUtils.fixLineFeeds(queryText); if (isDelimiter && hasBlocks && dialect.isDelimiterAfterBlock()) { if (delimiterText != null) { queryText += delimiterText; } } int queryEndPos = tokenOffset; if (tokenType == SQLToken.T_DELIMITER) { queryEndPos += tokenLength; } // make script line return new SQLQuery( getDataSource(), queryText.trim(), statementStart, queryEndPos - statementStart); } catch (BadLocationException ex) { log.warn("Can't extract query", ex); //$NON-NLS-1$ return null; } } if (isDelimiter) { statementStart = tokenOffset + tokenLength; } if (token.isEOF()) { return null; } if (!hasValuableTokens && !token.isWhitespace() && !isControl) { if (tokenType == SQLToken.T_COMMENT) { hasValuableTokens = dialect.supportsCommentQuery(); } else { hasValuableTokens = true; } } } } private static int countLineFeeds(final IDocument document, final int offset, final int length) { int lfCount = 0; try { for (int i = offset; i < offset + length; i++) { if (document.getChar(i) == '\n') { lfCount++; } } } catch (BadLocationException e) { log.error(e); } return lfCount; } protected List<SQLQueryParameter> parseParameters(IDocument document, SQLQuery query) { final SQLDialect sqlDialect = getSQLDialect(); boolean execQuery = false; List<SQLQueryParameter> parameters = null; ruleManager.setRange(document, query.getOffset(), query.getLength()); boolean firstKeyword = true; for (;;) { IToken token = ruleManager.nextToken(); int tokenOffset = ruleManager.getTokenOffset(); final int tokenLength = ruleManager.getTokenLength(); if (token.isEOF() || tokenOffset > query.getOffset() + query.getLength()) { break; } // Handle only parameters which are not in SQL blocks int tokenType = SQLToken.T_UNKNOWN; if (token instanceof SQLToken) { tokenType = ((SQLToken) token).getType(); } if (token.isWhitespace() || tokenType == SQLToken.T_COMMENT) { continue; } if (firstKeyword) { // Detect query type try { String tokenText = document.get(tokenOffset, tokenLength); if (ArrayUtils.containsIgnoreCase(sqlDialect.getDDLKeywords(), tokenText)) { // DDL doesn't support parameters return null; } execQuery = ArrayUtils.containsIgnoreCase(sqlDialect.getExecuteKeywords(), tokenText); } catch (BadLocationException e) { log.warn(e); } firstKeyword = false; } if (tokenType == SQLToken.T_PARAMETER && tokenLength > 0) { try { String paramName = document.get(tokenOffset, tokenLength); if (execQuery && paramName.equals("?")) { // Skip ? parameters for stored procedures (they have special meaning? [DB2]) continue; } if (parameters == null) { parameters = new ArrayList<>(); } SQLQueryParameter parameter = new SQLQueryParameter( parameters.size(), paramName, tokenOffset - query.getOffset(), tokenLength); SQLQueryParameter previous = null; if (parameter.isNamed()) { for (int i = parameters.size(); i > 0; i--) { if (parameters.get(i - 1).getName().equals(paramName)) { previous = parameters.get(i - 1); break; } } } parameter.setPrevious(previous); parameters.add(parameter); } catch (BadLocationException e) { log.warn("Can't extract query parameter", e); } } } return parameters; } public boolean isDisposed() { return getSourceViewer() != null && getSourceViewer().getTextWidget() != null && getSourceViewer().getTextWidget().isDisposed(); } @Nullable @Override public ICommentsSupport getCommentsSupport() { final SQLDialect dialect = getSQLDialect(); return new ICommentsSupport() { @Nullable @Override public Pair<String, String> getMultiLineComments() { return dialect.getMultiLineComments(); } @Override public String[] getSingleLineComments() { return dialect.getSingleLineComments(); } }; } protected String[] collectContextMenuPreferencePages() { String[] ids = super.collectContextMenuPreferencePages(); String[] more = new String[ids.length + 5]; more[ids.length] = PrefPageSQLEditor.PAGE_ID; more[ids.length + 1] = PrefPageSQLExecute.PAGE_ID; more[ids.length + 2] = PrefPageSQLCompletion.PAGE_ID; more[ids.length + 3] = PrefPageSQLFormat.PAGE_ID; more[ids.length + 4] = PrefPageSQLTemplates.PAGE_ID; System.arraycopy(ids, 0, more, 0, ids.length); return more; } @Override public boolean visualizeError(@NotNull DBRProgressMonitor monitor, @NotNull Throwable error) { Document document = getDocument(); SQLQuery query = new SQLQuery(getDataSource(), document.get(), 0, document.getLength()); return scrollCursorToError(monitor, query, error); } /** * Error handling */ protected boolean scrollCursorToError(@NotNull DBRProgressMonitor monitor, @NotNull SQLQuery query, @NotNull Throwable error) { try { DBCExecutionContext context = getExecutionContext(); boolean scrolled = false; DBPErrorAssistant errorAssistant = DBUtils.getAdapter(DBPErrorAssistant.class, context.getDataSource()); if (errorAssistant != null) { DBPErrorAssistant.ErrorPosition[] positions = errorAssistant.getErrorPosition( monitor, context, query.getText(), error); if (positions != null && positions.length > 0) { int queryStartOffset = query.getOffset(); int queryLength = query.getLength(); DBPErrorAssistant.ErrorPosition pos = positions[0]; if (pos.line < 0) { if (pos.position >= 0) { // Only position getSelectionProvider().setSelection(new TextSelection(queryStartOffset + pos.position, 1)); scrolled = true; } } else { // Line + position Document document = getDocument(); if (document != null) { int startLine = document.getLineOfOffset(queryStartOffset); int errorOffset = document.getLineOffset(startLine + pos.line); int errorLength; if (pos.position >= 0) { errorOffset += pos.position; errorLength = 1; } else { errorLength = document.getLineLength(startLine + pos.line); } if (errorOffset < queryStartOffset) errorOffset = queryStartOffset; if (errorLength > queryLength) errorLength = queryLength; getSelectionProvider().setSelection(new TextSelection(errorOffset, errorLength)); scrolled = true; } } } } return scrolled; // if (!scrolled) { // // Can't position on error - let's just select entire problem query // showStatementInEditor(result.getStatement(), true); // } } catch (Exception e) { log.warn("Error positioning on query error", e); return false; } } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditorBase.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ui.editors.sql; import org.eclipse.jface.action.*; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.*; import org.eclipse.jface.text.rules.FastPartitioner; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.source.*; import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; import org.eclipse.jface.text.source.projection.ProjectionSupport; import org.eclipse.jface.text.source.projection.ProjectionViewer; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.internal.editors.text.EditorsPlugin; import org.eclipse.ui.texteditor.*; import org.eclipse.ui.texteditor.templates.ITemplatesPage; import org.eclipse.ui.themes.IThemeManager; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.ModelPreferences; import org.jkiss.dbeaver.core.CoreCommands; import org.jkiss.dbeaver.core.DBeaverActivator; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.sql.BasicSQLDialect; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.*; import org.jkiss.dbeaver.ui.ActionUtils; import org.jkiss.dbeaver.ui.ICommentsSupport; import org.jkiss.dbeaver.ui.IErrorVisualizer; import org.jkiss.dbeaver.ui.TextUtils; import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLPartitionScanner; import org.jkiss.dbeaver.ui.editors.sql.syntax.SQLRuleManager; import org.jkiss.dbeaver.ui.editors.sql.syntax.tokens.SQLToken; import org.jkiss.dbeaver.ui.editors.sql.templates.SQLTemplatesPage; import org.jkiss.dbeaver.ui.editors.sql.util.SQLSymbolInserter; import org.jkiss.dbeaver.ui.editors.text.BaseTextEditor; import org.jkiss.dbeaver.ui.preferences.*; import org.jkiss.utils.ArrayUtils; import org.jkiss.utils.CommonUtils; import org.jkiss.utils.Pair; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; /** * SQL Executor */ public abstract class SQLEditorBase extends BaseTextEditor implements IErrorVisualizer { static protected final Log log = Log.getLog(SQLEditorBase.class); public static final String SQL_EDITOR_CONTEXT = "org.jkiss.dbeaver.ui.editors.sql"; static { // SQL editor preferences { IPreferenceStore editorStore = EditorsPlugin.getDefault().getPreferenceStore(); editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS, true); editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS_COLOR, "128,128,128"); } } @NotNull private final SQLSyntaxManager syntaxManager; @NotNull private final SQLRuleManager ruleManager; private ProjectionSupport projectionSupport; private ProjectionAnnotationModel annotationModel; //private Map<Annotation, Position> curAnnotations; private IAnnotationAccess annotationAccess; private boolean hasVerticalRuler = true; private SQLTemplatesPage templatesPage; private IPropertyChangeListener themeListener; public SQLEditorBase() { super(); syntaxManager = new SQLSyntaxManager(); ruleManager = new SQLRuleManager(syntaxManager); themeListener = new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME) || event.getProperty().startsWith("org.jkiss.dbeaver.sql.editor")) { reloadSyntaxRules(); // Reconfigure to let comments/strings colors to take effect getSourceViewer().configure(getSourceViewerConfiguration()); } } }; PlatformUI.getWorkbench().getThemeManager().addPropertyChangeListener(themeListener); //setDocumentProvider(new SQLDocumentProvider()); setSourceViewerConfiguration(new SQLEditorSourceViewerConfiguration(this, getPreferenceStore())); setKeyBindingScopes(new String[]{TEXT_EDITOR_CONTEXT, SQL_EDITOR_CONTEXT}); //$NON-NLS-1$ } @Nullable public abstract DBCExecutionContext getExecutionContext(); public final DBPDataSource getDataSource() { DBCExecutionContext context = getExecutionContext(); return context == null ? null : context.getDataSource(); } public DBPPreferenceStore getActivePreferenceStore() { if (this instanceof IDataSourceContainerProvider) { DBPDataSourceContainer container = ((IDataSourceContainerProvider) this).getDataSourceContainer(); if (container != null) { return container.getPreferenceStore(); } } DBPDataSource dataSource = getDataSource(); return dataSource == null ? DBeaverCore.getGlobalPreferenceStore() : dataSource.getContainer().getPreferenceStore(); } @NotNull public SQLDialect getSQLDialect() { DBPDataSource dataSource = getDataSource(); // Refresh syntax if (dataSource instanceof SQLDataSource) { return ((SQLDataSource) dataSource).getSQLDialect(); } return BasicSQLDialect.INSTANCE; } public boolean hasAnnotations() { return false; } @NotNull public SQLSyntaxManager getSyntaxManager() { return syntaxManager; } @NotNull public SQLRuleManager getRuleManager() { return ruleManager; } public ProjectionAnnotationModel getAnnotationModel() { return annotationModel; } public SQLEditorSourceViewerConfiguration getViewerConfiguration() { return (SQLEditorSourceViewerConfiguration) super.getSourceViewerConfiguration(); } @Override public void createPartControl(Composite parent) { setRangeIndicator(new DefaultRangeIndicator()); super.createPartControl(new SQLEditorControl(parent, this)); ProjectionViewer viewer = (ProjectionViewer) getSourceViewer(); projectionSupport = new ProjectionSupport( viewer, getAnnotationAccess(), getSharedColors()); projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$ projectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$ projectionSupport.install(); viewer.doOperation(ProjectionViewer.TOGGLE); annotationModel = viewer.getProjectionAnnotationModel(); // Symbol inserter { SQLSymbolInserter symbolInserter = new SQLSymbolInserter(this); DBPPreferenceStore preferenceStore = getActivePreferenceStore(); boolean closeSingleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_SINGLE_QUOTES); boolean closeDoubleQuotes = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_DOUBLE_QUOTES); boolean closeBrackets = preferenceStore.getBoolean(SQLPreferenceConstants.SQLEDITOR_CLOSE_BRACKETS); symbolInserter.setCloseSingleQuotesEnabled(closeSingleQuotes); symbolInserter.setCloseDoubleQuotesEnabled(closeDoubleQuotes); symbolInserter.setCloseBracketsEnabled(closeBrackets); ISourceViewer sourceViewer = getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) { ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(symbolInserter); } } } @Override public void updatePartControl(IEditorInput input) { super.updatePartControl(input); } @Override protected IVerticalRuler createVerticalRuler() { return hasVerticalRuler ? super.createVerticalRuler() : new VerticalRuler(0); } public void setHasVerticalRuler(boolean hasVerticalRuler) { this.hasVerticalRuler = hasVerticalRuler; } protected ISharedTextColors getSharedColors() { return DBeaverUI.getSharedTextColors(); } @Override protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { fAnnotationAccess= getAnnotationAccess(); fOverviewRuler= createOverviewRuler(getSharedColors()); SQLEditorSourceViewer sourceViewer = createSourceViewer(parent, ruler, styles, fOverviewRuler); getSourceViewerDecorationSupport(sourceViewer); return sourceViewer; } protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { char[] matchChars = {'(', ')', '[', ']', '{', '}'}; //which brackets to match ICharacterPairMatcher matcher; try { matcher = new DefaultCharacterPairMatcher(matchChars, SQLPartitionScanner.SQL_PARTITIONING, true); } catch (Throwable e) { // If we below Eclipse 4.2.1 matcher = new DefaultCharacterPairMatcher(matchChars, SQLPartitionScanner.SQL_PARTITIONING); } support.setCharacterPairMatcher(matcher); support.setMatchingCharacterPainterPreferenceKeys(SQLPreferenceConstants.MATCHING_BRACKETS, SQLPreferenceConstants.MATCHING_BRACKETS_COLOR); super.configureSourceViewerDecorationSupport(support); } @NotNull protected SQLEditorSourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles, IOverviewRuler overviewRuler) { return new SQLEditorSourceViewer( parent, ruler, overviewRuler, true, styles); } @Override protected IAnnotationAccess createAnnotationAccess() { return new SQLMarkerAnnotationAccess(); } /* protected void adjustHighlightRange(int offset, int length) { ISourceViewer viewer = getSourceViewer(); if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension = (ITextViewerExtension5) viewer; extension.exposeModelRange(new Region(offset, length)); } } */ @Override public Object getAdapter(Class required) { if (projectionSupport != null) { Object adapter = projectionSupport.getAdapter( getSourceViewer(), required); if (adapter != null) return adapter; } if (ITemplatesPage.class.equals(required)) { return getTemplatesPage(); } return super.getAdapter(required); } public SQLTemplatesPage getTemplatesPage() { if (templatesPage == null) templatesPage = new SQLTemplatesPage(this); return templatesPage; } @Override public void dispose() { if (themeListener != null) { PlatformUI.getWorkbench().getThemeManager().removePropertyChangeListener(themeListener); themeListener = null; } super.dispose(); } @Override protected void createActions() { super.createActions(); ResourceBundle bundle = DBeaverActivator.getCoreResourceBundle(); IAction a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL), this, ISourceViewer.CONTENTASSIST_PROPOSALS); a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL, a); a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP), this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); a.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP, a); a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION), this, ISourceViewer.INFORMATION); a.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_INFORMATION); setAction(SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION, a); a = new TextOperationAction( bundle, SQLEditorContributor.getActionResourcePrefix(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL), this, ISourceViewer.FORMAT); a.setActionDefinitionId(CoreCommands.CMD_CONTENT_FORMAT); setAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL, a); setAction(ITextEditorActionConstants.CONTEXT_PREFERENCES, new Action("Preferences...") { //$NON-NLS-1$ public void run() { Shell shell = getSourceViewer().getTextWidget().getShell(); String[] preferencePages = collectContextMenuPreferencePages(); if (preferencePages.length > 0 && (shell == null || !shell.isDisposed())) PreferencesUtil.createPreferenceDialogOn(shell, preferencePages[0], preferencePages, getEditorInput()).open(); } }); /* // Add the task action to the Edit pulldown menu (bookmark action is 'free') ResourceAction ra = new AddTaskAction(bundle, "AddTask.", this); ra.setHelpContextId(ITextEditorHelpContextIds.ADD_TASK_ACTION); ra.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(IDEActionFactory.ADD_TASK.getId(), ra); */ } @Override public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); menu.add(new Separator("content"));//$NON-NLS-1$ addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_PROPOSAL); addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_TIP); addAction(menu, GROUP_SQL_EXTRAS, SQLEditorContributor.ACTION_CONTENT_ASSIST_INFORMATION); { MenuManager formatMenu = new MenuManager("Format", "format"); IAction formatAction = getAction(SQLEditorContributor.ACTION_CONTENT_FORMAT_PROPOSAL); if (formatAction != null) { formatMenu.add(formatAction); } formatMenu.add(getAction(ITextEditorActionConstants.UPPER_CASE)); formatMenu.add(getAction(ITextEditorActionConstants.LOWER_CASE)); formatMenu.add(new Separator()); formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.word.wrap")); formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.single")); formatMenu.add(ActionUtils.makeCommandContribution(getSite(), "org.jkiss.dbeaver.ui.editors.sql.comment.multi")); menu.insertAfter(GROUP_SQL_ADDITIONS, formatMenu); } } public void reloadSyntaxRules() { // Refresh syntax SQLDialect dialect = getSQLDialect(); syntaxManager.init(dialect, getActivePreferenceStore()); ruleManager.refreshRules(getDataSource(), getEditorInput()); Document document = getDocument(); if (document != null) { IDocumentPartitioner partitioner = new FastPartitioner( new SQLPartitionScanner(dialect), SQLPartitionScanner.SQL_CONTENT_TYPES); partitioner.connect(document); document.setDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING, partitioner); ProjectionViewer projectionViewer = (ProjectionViewer) getSourceViewer(); if (projectionViewer != null && projectionViewer.getAnnotationModel() != null && document.getLength() > 0) { // Refresh viewer //projectionViewer.getTextWidget().redraw(); try { projectionViewer.reinitializeProjection(); } catch (Throwable ex) { // We can catch OutOfMemory here for too big/complex documents log.warn("Can't initialize SQL syntax projection", ex); //$NON-NLS-1$ } } } /* Color fgColor = ruleManager.getColor(SQLConstants.CONFIG_COLOR_TEXT); Color bgColor = ruleManager.getColor(getDataSource() == null ? SQLConstants.CONFIG_COLOR_DISABLED : SQLConstants.CONFIG_COLOR_BACKGROUND); final StyledText textWidget = getTextViewer().getTextWidget(); if (fgColor != null) { textWidget.setForeground(fgColor); } textWidget.setBackground(bgColor); */ // Update configuration if (getSourceViewerConfiguration() instanceof SQLEditorSourceViewerConfiguration) { ((SQLEditorSourceViewerConfiguration) getSourceViewerConfiguration()).onDataSourceChange(); } final IVerticalRuler verticalRuler = getVerticalRuler(); if (verticalRuler != null) { verticalRuler.update(); } } public boolean hasActiveQuery() { Document document = getDocument(); if (document == null) { return false; } ISelectionProvider selectionProvider = getSelectionProvider(); if (selectionProvider == null) { return false; } ITextSelection selection = (ITextSelection) selectionProvider.getSelection(); String selText = selection.getText(); if (CommonUtils.isEmpty(selText) && selection.getOffset() >= 0 && selection.getOffset() < document.getLength()) { try { IRegion lineRegion = document.getLineInformationOfOffset(selection.getOffset()); selText = document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException e) { log.warn(e); return false; } } return !CommonUtils.isEmptyTrimmed(selText); } @Nullable protected SQLScriptElement extractActiveQuery() { SQLScriptElement element; ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); String selText = selection.getText().trim(); selText = SQLUtils.trimQueryStatement(getSyntaxManager(), selText); if (!CommonUtils.isEmpty(selText)) { SQLScriptElement parsedElement = parseQuery(getDocument(), selection.getOffset(), selection.getOffset() + selection.getLength(), selection.getOffset(), false); if (parsedElement instanceof SQLControlCommand) { // This is a command element = parsedElement; } else { // Use selected query as is element = new SQLQuery(getDataSource(), selText, selection.getOffset(), selection.getLength()); } } else if (selection.getOffset() >= 0) { element = extractQueryAtPos(selection.getOffset()); } else { element = null; } // Check query do not ends with delimiter // (this may occur if user selected statement including delimiter) if (element == null || CommonUtils.isEmpty(element.getText())) { return null; } if (element instanceof SQLQuery && getActivePreferenceStore().getBoolean(ModelPreferences.SQL_PARAMETERS_ENABLED)) { ((SQLQuery)element).setParameters(parseParameters(getDocument(), (SQLQuery)element)); } return element; } public SQLScriptElement extractQueryAtPos(int currentPos) { Document document = getDocument(); if (document == null || document.getLength() == 0) { return null; } final int docLength = document.getLength(); IDocumentPartitioner partitioner = document.getDocumentPartitioner(SQLPartitionScanner.SQL_PARTITIONING); if (partitioner != null) { // Move to default partition. We don't want to be in the middle of multi-line comment or string while (currentPos < docLength && isMultiCommentPartition(partitioner, currentPos)) { currentPos++; } } // Extract part of document between empty lines int startPos = 0; boolean useBlankLines = syntaxManager.isBlankLineDelimiter(); final String[] statementDelimiters = syntaxManager.getStatementDelimiters(); try { int currentLine = document.getLineOfOffset(currentPos); int lineOffset = document.getLineOffset(currentLine); if (TextUtils.isEmptyLine(document, currentLine)) { return null; } int firstLine = currentLine; while (firstLine > 0) { if (useBlankLines) { if (TextUtils.isEmptyLine(document, firstLine) && isDefaultPartition(partitioner, document.getLineOffset(firstLine))) { break; } } else { for (String delim : statementDelimiters) { final int offset = TextUtils.getOffsetOf(document, firstLine, delim); if (offset >= 0 && isDefaultPartition(partitioner, offset)) { break; } } } firstLine--; } startPos = document.getLineOffset(firstLine); // Move currentPos at line begin currentPos = lineOffset; } catch (BadLocationException e) { log.warn(e); } return parseQuery(document, startPos, document.getLength(), currentPos, false); } public SQLScriptElement extractNextQuery(boolean next) { ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection(); int offset = selection.getOffset(); SQLScriptElement curElement = extractQueryAtPos(offset); if (curElement == null) { return null; } Document document = getDocument(); if (document == null) { return null; } try { int docLength = document.getLength(); int curPos; if (next) { final String[] statementDelimiters = syntaxManager.getStatementDelimiters(); curPos = curElement.getOffset() + curElement.getLength(); while (curPos < docLength) { char c = document.getChar(curPos); if (!Character.isWhitespace(c)) { boolean isDelimiter = false; for (String delim : statementDelimiters) { if (delim.indexOf(c) != -1) { isDelimiter = true; } } if (!isDelimiter) { break; } } curPos++; } } else { curPos = curElement.getOffset() - 1; while (curPos >= 0) { char c = document.getChar(curPos); if (!Character.isWhitespace(c)) { break; } curPos--; } } if (curPos <= 0 || curPos >= docLength) { return null; } return extractQueryAtPos(curPos); } catch (BadLocationException e) { log.warn(e); return null; } } private static boolean isDefaultPartition(IDocumentPartitioner partitioner, int currentPos) { return partitioner == null || IDocument.DEFAULT_CONTENT_TYPE.equals(partitioner.getContentType(currentPos)); } private static boolean isMultiCommentPartition(IDocumentPartitioner partitioner, int currentPos) { return partitioner != null && SQLPartitionScanner.CONTENT_TYPE_SQL_MULTILINE_COMMENT.equals(partitioner.getContentType(currentPos)); } protected void startScriptEvaluation() { ruleManager.startEval(); } protected void endScriptEvaluation() { ruleManager.endEval(); } protected SQLScriptElement parseQuery(final IDocument document, final int startPos, final int endPos, final int currentPos, final boolean scriptMode) { if (endPos - startPos <= 0) { return null; } SQLDialect dialect = getSQLDialect(); // Parse range boolean useBlankLines = !scriptMode && syntaxManager.isBlankLineDelimiter(); ruleManager.setRange(document, startPos, endPos - startPos); int statementStart = startPos; int bracketDepth = 0; boolean hasBlocks = false; boolean hasValuableTokens = false; boolean hasBlockHeader = false; String blockTogglePattern = null; int lastTokenLineFeeds = 0; for (; ; ) { IToken token = ruleManager.nextToken(); int tokenOffset = ruleManager.getTokenOffset(); int tokenLength = ruleManager.getTokenLength(); int tokenType = token instanceof SQLToken ? ((SQLToken)token).getType() : SQLToken.T_UNKNOWN; boolean isDelimiter = tokenType == SQLToken.T_DELIMITER; boolean isControl = false; String delimiterText = null; if (isDelimiter) { // Save delimiter text try { delimiterText = document.get(tokenOffset, tokenLength); } catch (BadLocationException e) { log.debug(e); } } else if (useBlankLines && token.isWhitespace() && tokenLength >= 2) { // Check for blank line delimiter if (lastTokenLineFeeds + countLineFeeds(document, tokenOffset, tokenLength) >= 2) { isDelimiter = true; } } lastTokenLineFeeds = 0; if (tokenLength == 1) { // Check for bracket block begin/end try { char aChar = document.getChar(tokenOffset); if (aChar == '(' || aChar == '{' || aChar == '[') { bracketDepth++; } else if (aChar == ')' || aChar == '}' || aChar == ']') { bracketDepth--; } } catch (BadLocationException e) { log.warn(e); } } if (tokenType == SQLToken.T_BLOCK_HEADER) { bracketDepth++; hasBlocks = true; hasBlockHeader = true; } else if (tokenType == SQLToken.T_BLOCK_TOGGLE) { String togglePattern; try { togglePattern = document.get(tokenOffset, tokenLength); } catch (BadLocationException e) { log.warn(e); togglePattern = ""; } // Second toggle pattern must be the same as first one. // Toggles can be nested (PostgreSQL) and we need to count only outer if (bracketDepth == 1 && togglePattern.equals(blockTogglePattern)) { bracketDepth--; blockTogglePattern = null; } else if (bracketDepth == 0 && blockTogglePattern == null) { bracketDepth++; blockTogglePattern = togglePattern; } else { log.debug("Block toggle token inside another block. Can't process it"); } hasBlocks = true; } else if (tokenType == SQLToken.T_BLOCK_BEGIN) { if (!hasBlockHeader) { bracketDepth++; } hasBlocks = true; } else if (bracketDepth > 0 && tokenType == SQLToken.T_BLOCK_END) { // Sometimes query contains END clause without BEGIN. E.g. CASE, IF, etc. // This END doesn't mean block if (hasBlocks) { bracketDepth--; } hasBlockHeader = false; } else if (isDelimiter && bracketDepth > 0) { // Delimiter in some brackets - ignore it continue; } else if (tokenType == SQLToken.T_SET_DELIMITER || tokenType == SQLToken.T_CONTROL) { isDelimiter = true; isControl = true; } else if (tokenType == SQLToken.T_COMMENT) { lastTokenLineFeeds = tokenLength < 2 ? 0 : countLineFeeds(document, tokenOffset + tokenLength - 2, 2); } boolean cursorInsideToken = currentPos >= tokenOffset && currentPos < tokenOffset + tokenLength; if (isControl && cursorInsideToken) { // Control query try { String controlText = document.get(tokenOffset, tokenLength); return new SQLControlCommand( getDataSource(), syntaxManager, controlText.trim(), tokenOffset, tokenLength, tokenType == SQLToken.T_SET_DELIMITER); } catch (BadLocationException e) { log.warn("Can't extract control statement", e); //$NON-NLS-1$ return null; } } if (hasValuableTokens && (token.isEOF() || (isDelimiter && tokenOffset >= currentPos) || tokenOffset > endPos)) { if (tokenOffset > endPos) { tokenOffset = endPos; } if (tokenOffset >= document.getLength()) { // Sometimes (e.g. when comment finishing script text) // last token offset is beyond document range tokenOffset = document.getLength(); } assert (tokenOffset >= currentPos); try { // remove leading spaces while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(statementStart))) { statementStart++; } // remove trailing spaces while (statementStart < tokenOffset && Character.isWhitespace(document.getChar(tokenOffset - 1))) { tokenOffset--; tokenLength++; } if (tokenOffset == statementStart) { // Empty statement if (token.isEOF()) { return null; } statementStart = tokenOffset + tokenLength; continue; } String queryText = document.get(statementStart, tokenOffset - statementStart); queryText = SQLUtils.fixLineFeeds(queryText); if (isDelimiter && hasBlocks && dialect.isDelimiterAfterBlock()) { if (delimiterText != null) { queryText += delimiterText; } } int queryEndPos = tokenOffset; if (tokenType == SQLToken.T_DELIMITER) { queryEndPos += tokenLength; } // make script line return new SQLQuery( getDataSource(), queryText.trim(), statementStart, queryEndPos - statementStart); } catch (BadLocationException ex) { log.warn("Can't extract query", ex); //$NON-NLS-1$ return null; } } if (isDelimiter) { statementStart = tokenOffset + tokenLength; } if (token.isEOF()) { return null; } if (!hasValuableTokens && !token.isWhitespace() && !isControl) { if (tokenType == SQLToken.T_COMMENT) { hasValuableTokens = dialect.supportsCommentQuery(); } else { hasValuableTokens = true; } } } } private static int countLineFeeds(final IDocument document, final int offset, final int length) { int lfCount = 0; try { for (int i = offset; i < offset + length; i++) { if (document.getChar(i) == '\n') { lfCount++; } } } catch (BadLocationException e) { log.error(e); } return lfCount; } protected List<SQLQueryParameter> parseParameters(IDocument document, SQLQuery query) { final SQLDialect sqlDialect = getSQLDialect(); boolean execQuery = false; List<SQLQueryParameter> parameters = null; ruleManager.setRange(document, query.getOffset(), query.getLength()); boolean firstKeyword = true; for (;;) { IToken token = ruleManager.nextToken(); int tokenOffset = ruleManager.getTokenOffset(); final int tokenLength = ruleManager.getTokenLength(); if (token.isEOF() || tokenOffset > query.getOffset() + query.getLength()) { break; } // Handle only parameters which are not in SQL blocks int tokenType = SQLToken.T_UNKNOWN; if (token instanceof SQLToken) { tokenType = ((SQLToken) token).getType(); } if (token.isWhitespace() || tokenType == SQLToken.T_COMMENT) { continue; } if (firstKeyword) { // Detect query type try { String tokenText = document.get(tokenOffset, tokenLength); if (ArrayUtils.containsIgnoreCase(sqlDialect.getDDLKeywords(), tokenText)) { // DDL doesn't support parameters return null; } execQuery = ArrayUtils.containsIgnoreCase(sqlDialect.getExecuteKeywords(), tokenText); } catch (BadLocationException e) { log.warn(e); } firstKeyword = false; } if (tokenType == SQLToken.T_PARAMETER && tokenLength > 0) { try { String paramName = document.get(tokenOffset, tokenLength); if (execQuery && paramName.equals("?")) { // Skip ? parameters for stored procedures (they have special meaning? [DB2]) continue; } if (parameters == null) { parameters = new ArrayList<>(); } SQLQueryParameter parameter = new SQLQueryParameter( parameters.size(), paramName, tokenOffset - query.getOffset(), tokenLength); SQLQueryParameter previous = null; if (parameter.isNamed()) { for (int i = parameters.size(); i > 0; i--) { if (parameters.get(i - 1).getName().equals(paramName)) { previous = parameters.get(i - 1); break; } } } parameter.setPrevious(previous); parameters.add(parameter); } catch (BadLocationException e) { log.warn("Can't extract query parameter", e); } } } return parameters; } public boolean isDisposed() { return getSourceViewer() != null && getSourceViewer().getTextWidget() != null && getSourceViewer().getTextWidget().isDisposed(); } @Nullable @Override public ICommentsSupport getCommentsSupport() { final SQLDialect dialect = getSQLDialect(); return new ICommentsSupport() { @Nullable @Override public Pair<String, String> getMultiLineComments() { return dialect.getMultiLineComments(); } @Override public String[] getSingleLineComments() { return dialect.getSingleLineComments(); } }; } protected String[] collectContextMenuPreferencePages() { String[] ids = super.collectContextMenuPreferencePages(); String[] more = new String[ids.length + 5]; more[ids.length] = PrefPageSQLEditor.PAGE_ID; more[ids.length + 1] = PrefPageSQLExecute.PAGE_ID; more[ids.length + 2] = PrefPageSQLCompletion.PAGE_ID; more[ids.length + 3] = PrefPageSQLFormat.PAGE_ID; more[ids.length + 4] = PrefPageSQLTemplates.PAGE_ID; System.arraycopy(ids, 0, more, 0, ids.length); return more; } @Override public boolean visualizeError(@NotNull DBRProgressMonitor monitor, @NotNull Throwable error) { Document document = getDocument(); SQLQuery query = new SQLQuery(getDataSource(), document.get(), 0, document.getLength()); return scrollCursorToError(monitor, query, error); } /** * Error handling */ protected boolean scrollCursorToError(@NotNull DBRProgressMonitor monitor, @NotNull SQLQuery query, @NotNull Throwable error) { try { DBCExecutionContext context = getExecutionContext(); boolean scrolled = false; DBPErrorAssistant errorAssistant = DBUtils.getAdapter(DBPErrorAssistant.class, context.getDataSource()); if (errorAssistant != null) { DBPErrorAssistant.ErrorPosition[] positions = errorAssistant.getErrorPosition( monitor, context, query.getText(), error); if (positions != null && positions.length > 0) { int queryStartOffset = query.getOffset(); int queryLength = query.getLength(); DBPErrorAssistant.ErrorPosition pos = positions[0]; if (pos.line < 0) { if (pos.position >= 0) { // Only position getSelectionProvider().setSelection(new TextSelection(queryStartOffset + pos.position, 1)); scrolled = true; } } else { // Line + position Document document = getDocument(); if (document != null) { int startLine = document.getLineOfOffset(queryStartOffset); int errorOffset = document.getLineOffset(startLine + pos.line); int errorLength; if (pos.position >= 0) { errorOffset += pos.position; errorLength = 1; } else { errorLength = document.getLineLength(startLine + pos.line); } if (errorOffset < queryStartOffset) errorOffset = queryStartOffset; if (errorLength > queryLength) errorLength = queryLength; getSelectionProvider().setSelection(new TextSelection(errorOffset, errorLength)); scrolled = true; } } } } return scrolled; // if (!scrolled) { // // Can't position on error - let's just select entire problem query // showStatementInEditor(result.getStatement(), true); // } } catch (Exception e) { log.warn("Error positioning on query error", e); return false; } } }
SQL editor prefs init comment Former-commit-id: 68e8a2b1950451cef0542566974d4b4a56a3d613
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditorBase.java
SQL editor prefs init comment
<ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditorBase.java <ide> public static final String SQL_EDITOR_CONTEXT = "org.jkiss.dbeaver.ui.editors.sql"; <ide> <ide> static { <del> // SQL editor preferences <add> // SQL editor preferences. Do this here because it initializes display <add> // (that's why we can't run it in prefs initializer classes which run before workbench creation) <ide> { <ide> IPreferenceStore editorStore = EditorsPlugin.getDefault().getPreferenceStore(); <ide> editorStore.setDefault(SQLPreferenceConstants.MATCHING_BRACKETS, true);
Java
apache-2.0
bc5a3cf74268cb3b04baab4de464a0a747e433b5
0
xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.impl; import com.intellij.application.options.EditorFontsConstants; import com.intellij.codeInsight.hint.DocumentFragmentTooltipRenderer; import com.intellij.codeInsight.hint.EditorFragmentComponent; import com.intellij.codeInsight.hint.TooltipController; import com.intellij.codeInsight.hint.TooltipGroup; import com.intellij.concurrency.JobScheduler; import com.intellij.diagnostic.Dumpable; import com.intellij.ide.*; import com.intellij.ide.dnd.DnDManager; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.TransactionGuardImpl; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.*; import com.intellij.openapi.editor.colors.*; import com.intellij.openapi.editor.colors.impl.DelegateColorScheme; import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.*; import com.intellij.openapi.editor.ex.util.EditorUIUtil; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterClient; import com.intellij.openapi.editor.impl.event.MarkupModelListener; import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces; import com.intellij.openapi.editor.impl.view.EditorView; import com.intellij.openapi.editor.markup.GutterDraggableObject; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.fileEditor.impl.EditorsSplitters; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.AbstractPainter; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.openapi.wm.IdeGlassPaneUtil; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.impl.IdeBackgroundUtil; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.psi.PsiDocumentManager; import com.intellij.ui.*; import com.intellij.ui.components.JBLayeredPane; import com.intellij.ui.components.JBScrollBar; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.mac.MacGestureSupportForEditor; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.IJSwingUtilities; import com.intellij.util.ReflectionUtil; import com.intellij.util.concurrency.EdtExecutorService; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.ui.*; import com.intellij.util.ui.update.Activatable; import com.intellij.util.ui.update.UiNotifyConnector; import org.intellij.lang.annotations.JdkConstants; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.plaf.ScrollBarUI; import javax.swing.plaf.ScrollPaneUI; import javax.swing.plaf.basic.BasicScrollBarUI; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.*; import java.awt.font.TextHitInfo; import java.awt.geom.Point2D; import java.awt.im.InputMethodRequests; import java.awt.image.BufferedImage; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.lang.reflect.Field; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.*; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public final class EditorImpl extends UserDataHolderBase implements EditorEx, HighlighterClient, Queryable, Dumpable { public static final int TEXT_ALIGNMENT_LEFT = 0; public static final int TEXT_ALIGNMENT_RIGHT = 1; private static final int MIN_FONT_SIZE = 8; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorImpl"); private static final Key DND_COMMAND_KEY = Key.create("DndCommand"); @NonNls public static final Object IGNORE_MOUSE_TRACKING = "ignore_mouse_tracking"; private static final Key<JComponent> PERMANENT_HEADER = Key.create("PERMANENT_HEADER"); public static final Key<Boolean> DO_DOCUMENT_UPDATE_TEST = Key.create("DoDocumentUpdateTest"); public static final Key<Boolean> FORCED_SOFT_WRAPS = Key.create("forced.soft.wraps"); public static final Key<Boolean> SOFT_WRAPS_EXIST = Key.create("soft.wraps.exist"); private static final Key<Boolean> DISABLE_CARET_POSITION_KEEPING = Key.create("editor.disable.caret.position.keeping"); static final Key<Boolean> DISABLE_CARET_SHIFT_ON_WHITESPACE_INSERTION = Key.create("editor.disable.caret.shift.on.whitespace.insertion"); private static final boolean HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK = Boolean.parseBoolean(System.getProperty("idea.honor.camel.humps.on.triple.click")); private static final Key<BufferedImage> BUFFER = Key.create("buffer"); @NotNull private final DocumentEx myDocument; private final JPanel myPanel; @NotNull private final JScrollPane myScrollPane; @NotNull private final EditorComponentImpl myEditorComponent; @NotNull private final EditorGutterComponentImpl myGutterComponent; private final TraceableDisposable myTraceableDisposable = new TraceableDisposable(true); private static final Cursor EMPTY_CURSOR; static { Cursor emptyCursor = null; if (!GraphicsEnvironment.isHeadless()) { try { emptyCursor = Toolkit.getDefaultToolkit().createCustomCursor(UIUtil.createImage(1, 1, BufferedImage.TYPE_INT_ARGB), new Point(), "Empty cursor"); } catch (Exception e){ LOG.warn("Couldn't create an empty cursor", e); } } EMPTY_CURSOR = emptyCursor; } private final CommandProcessor myCommandProcessor; @NotNull private final MyScrollBar myVerticalScrollBar; private final List<EditorMouseListener> myMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList(); @NotNull private final List<EditorMouseMotionListener> myMouseMotionListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private boolean myIsInsertMode = true; @NotNull private final CaretCursor myCaretCursor; private final ScrollingTimer myScrollingTimer = new ScrollingTimer(); @SuppressWarnings("RedundantStringConstructorCall") private final Object MOUSE_DRAGGED_GROUP = new String("MouseDraggedGroup"); @NotNull private final SettingsImpl mySettings; private boolean isReleased; @Nullable private MouseEvent myMousePressedEvent; @Nullable private MouseEvent myMouseMovedEvent; private final MouseListener myMouseListener = new MyMouseAdapter(); private final MouseMotionListener myMouseMotionListener = new MyMouseMotionListener(); /** * Holds information about area where mouse was pressed. */ @Nullable private EditorMouseEventArea myMousePressArea; private int mySavedSelectionStart = -1; private int mySavedSelectionEnd = -1; private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this); private MyEditable myEditable; @NotNull private EditorColorsScheme myScheme; private boolean myIsViewer; @NotNull private final SelectionModelImpl mySelectionModel; @NotNull private final EditorMarkupModelImpl myMarkupModel; @NotNull private final EditorFilteringMarkupModelEx myDocumentMarkupModel; @NotNull private final MarkupModelListener myMarkupModelListener; @NotNull private final FoldingModelImpl myFoldingModel; @NotNull private final ScrollingModelImpl myScrollingModel; @NotNull private final CaretModelImpl myCaretModel; @NotNull private final SoftWrapModelImpl mySoftWrapModel; @NotNull private final InlayModelImpl myInlayModel; @NotNull private static final RepaintCursorCommand ourCaretBlinkingCommand = new RepaintCursorCommand(); private final DocumentBulkUpdateListener myBulkUpdateListener; @MouseSelectionState private int myMouseSelectionState; @Nullable private FoldRegion myMouseSelectedRegion; private int myHorizontalTextAlignment = TEXT_ALIGNMENT_LEFT; @MagicConstant(intValues = {MOUSE_SELECTION_STATE_NONE, MOUSE_SELECTION_STATE_LINE_SELECTED, MOUSE_SELECTION_STATE_WORD_SELECTED}) private @interface MouseSelectionState {} private static final int MOUSE_SELECTION_STATE_NONE = 0; private static final int MOUSE_SELECTION_STATE_WORD_SELECTED = 1; private static final int MOUSE_SELECTION_STATE_LINE_SELECTED = 2; private volatile EditorHighlighter myHighlighter; // updated in EDT, but can be accessed from other threads (under read action) private Disposable myHighlighterDisposable = Disposer.newDisposable(); private final TextDrawingCallback myTextDrawingCallback = new MyTextDrawingCallback(); @MagicConstant(intValues = {VERTICAL_SCROLLBAR_LEFT, VERTICAL_SCROLLBAR_RIGHT}) private int myScrollBarOrientation; private boolean myMousePressedInsideSelection; private boolean myUpdateCursor; private int myCaretUpdateVShift; @Nullable private final Project myProject; private long myMouseSelectionChangeTimestamp; private int mySavedCaretOffsetForDNDUndoHack; private final List<FocusChangeListener> myFocusListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private MyInputMethodHandler myInputMethodRequestsHandler; private InputMethodRequests myInputMethodRequestsSwingWrapper; private boolean myIsOneLineMode; private boolean myIsRendererMode; private VirtualFile myVirtualFile; private boolean myIsColumnMode; @Nullable private Color myForcedBackground; @Nullable private Dimension myPreferredSize; private final Alarm myMouseSelectionStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private Runnable myMouseSelectionStateResetRunnable; private boolean myEmbeddedIntoDialogWrapper; private int myDragOnGutterSelectionStartLine = -1; private RangeMarker myDraggedRange; @NotNull private final JPanel myHeaderPanel; @Nullable private MouseEvent myInitialMouseEvent; private boolean myIgnoreMouseEventsConsecutiveToInitial; private EditorDropHandler myDropHandler; private Condition<RangeHighlighter> myHighlightingFilter; @NotNull private final IndentsModel myIndentsModel; @Nullable private CharSequence myPlaceholderText; @Nullable private TextAttributes myPlaceholderAttributes; private boolean myShowPlaceholderWhenFocused; private boolean myStickySelection; private int myStickySelectionStart; private boolean myScrollToCaret = true; private boolean myPurePaintingMode; private boolean myPaintSelection; private final EditorSizeAdjustmentStrategy mySizeAdjustmentStrategy = new EditorSizeAdjustmentStrategy(); private final Disposable myDisposable = Disposer.newDisposable(); private List<CaretState> myCaretStateBeforeLastPress; LogicalPosition myLastMousePressedLocation; private VisualPosition myTargetMultiSelectionPosition; private boolean myMultiSelectionInProgress; private boolean myRectangularSelectionInProgress; private boolean myLastPressCreatedCaret; // Set when the selection (normal or block one) initiated by mouse drag becomes noticeable (at least one character is selected). // Reset on mouse press event. private boolean myCurrentDragIsSubstantial; private CaretImpl myPrimaryCaret; public final boolean myDisableRtl = Registry.is("editor.disable.rtl"); final EditorView myView; private boolean myCharKeyPressed; private boolean myNeedToSelectPreviousChar; private boolean myDocumentChangeInProgress; private boolean myErrorStripeNeedsRepaint; private String myContextMenuGroupId = IdeActions.GROUP_BASIC_EDITOR_POPUP; private boolean myUseEditorAntialiasing = true; private final ImmediatePainter myImmediatePainter; static { ourCaretBlinkingCommand.start(); } private volatile int myExpectedCaretOffset = -1; private boolean myBackgroundImageSet; private final EditorKind myKind; private boolean myScrollingToCaret; EditorImpl(@NotNull Document document, boolean viewer, @Nullable Project project, @NotNull EditorKind kind) { assertIsDispatchThread(); myProject = project; myDocument = (DocumentEx)document; myScheme = createBoundColorSchemeDelegate(null); myScrollPane = new MyScrollPane(); // create UI after scheme initialization myIsViewer = viewer; myKind = kind; mySettings = new SettingsImpl(this, project, kind); if (!mySettings.isUseSoftWraps() && shouldSoftWrapsBeForced()) { mySettings.setUseSoftWrapsQuiet(); putUserData(FORCED_SOFT_WRAPS, Boolean.TRUE); } MarkupModelEx documentMarkup = (MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true); mySelectionModel = new SelectionModelImpl(this); myMarkupModel = new EditorMarkupModelImpl(this); myDocumentMarkupModel = new EditorFilteringMarkupModelEx(this, documentMarkup); myFoldingModel = new FoldingModelImpl(this); myCaretModel = new CaretModelImpl(this); myCaretModel.initCarets(); myScrollingModel = new ScrollingModelImpl(this); myInlayModel = new InlayModelImpl(this); Disposer.register(myCaretModel, myInlayModel); mySoftWrapModel = new SoftWrapModelImpl(this); myCommandProcessor = CommandProcessor.getInstance(); myImmediatePainter = new ImmediatePainter(this); if (myDocument instanceof DocumentImpl) { myBulkUpdateListener = new EditorDocumentBulkUpdateAdapter(); ((DocumentImpl)myDocument).addInternalBulkModeListener(myBulkUpdateListener); } else { myBulkUpdateListener = null; } myMarkupModelListener = new MarkupModelListener() { private boolean areRenderersInvolved(@NotNull RangeHighlighterEx highlighter) { return highlighter.getCustomRenderer() != null || highlighter.getGutterIconRenderer() != null || highlighter.getLineMarkerRenderer() != null || highlighter.getLineSeparatorRenderer() != null; } @Override public void afterAdded(@NotNull RangeHighlighterEx highlighter) { attributesChanged(highlighter, areRenderersInvolved(highlighter), EditorUtil.attributesImpactFontStyleOrColor(highlighter.getTextAttributes())); } @Override public void beforeRemoved(@NotNull RangeHighlighterEx highlighter) { attributesChanged(highlighter, areRenderersInvolved(highlighter), EditorUtil.attributesImpactFontStyleOrColor(highlighter.getTextAttributes())); } @Override public void attributesChanged(@NotNull RangeHighlighterEx highlighter, boolean renderersChanged, boolean fontStyleOrColorChanged) { if (myDocument.isInBulkUpdate()) return; // bulkUpdateFinished() will repaint anything if (renderersChanged) { updateGutterSize(); } boolean errorStripeNeedsRepaint = renderersChanged || highlighter.getErrorStripeMarkColor() != null; if (myDocumentChangeInProgress) { // postpone repaint request, as folding model can be in inconsistent state and so coordinate // conversions might give incorrect results myErrorStripeNeedsRepaint |= errorStripeNeedsRepaint; return; } int textLength = myDocument.getTextLength(); int start = Math.min(Math.max(highlighter.getAffectedAreaStartOffset(), 0), textLength); int end = Math.min(Math.max(highlighter.getAffectedAreaEndOffset(), 0), textLength); int startLine = start == -1 ? 0 : myDocument.getLineNumber(start); int endLine = end == -1 ? myDocument.getLineCount() : myDocument.getLineNumber(end); if (start != end && fontStyleOrColorChanged) { myView.invalidateRange(start, end); } if (!myFoldingModel.isInBatchFoldingOperation()) { // at the end of batch folding operation everything is repainted repaintLines(Math.max(0, startLine - 1), Math.min(endLine + 1, getDocument().getLineCount())); } // optimization: there is no need to repaint error stripe if the highlighter is invisible on it if (errorStripeNeedsRepaint) { if (myFoldingModel.isInBatchFoldingOperation()) { myErrorStripeNeedsRepaint = true; } else { myMarkupModel.repaint(start, end); } } updateCaretCursor(); } }; getFilteredDocumentMarkupModel().addMarkupModelListener(myCaretModel, myMarkupModelListener); getMarkupModel().addMarkupModelListener(myCaretModel, myMarkupModelListener); myDocument.addDocumentListener(myFoldingModel, myCaretModel); myDocument.addDocumentListener(myCaretModel, myCaretModel); myDocument.addDocumentListener(new EditorDocumentAdapter(), myCaretModel); myDocument.addDocumentListener(mySoftWrapModel, myCaretModel); myFoldingModel.addListener(mySoftWrapModel, myCaretModel); myInlayModel.addListener(myCaretModel, myCaretModel); myIndentsModel = new IndentsModelImpl(this); myCaretModel.addCaretListener(new CaretListener() { @Nullable private LightweightHint myCurrentHint; @Nullable private IndentGuideDescriptor myCurrentCaretGuide; @Override public void caretPositionChanged(CaretEvent e) { if (myStickySelection) { int selectionStart = Math.min(myStickySelectionStart, getDocument().getTextLength()); mySelectionModel.setSelection(selectionStart, myCaretModel.getVisualPosition(), myCaretModel.getOffset()); } final IndentGuideDescriptor newGuide = myIndentsModel.getCaretIndentGuide(); if (!Comparing.equal(myCurrentCaretGuide, newGuide)) { repaintGuide(newGuide); repaintGuide(myCurrentCaretGuide); myCurrentCaretGuide = newGuide; if (myCurrentHint != null) { myCurrentHint.hide(); myCurrentHint = null; } if (newGuide != null) { final Rectangle visibleArea = getScrollingModel().getVisibleArea(); final int line = newGuide.startLine; if (logicalLineToY(line) < visibleArea.y) { TextRange textRange = new TextRange(myDocument.getLineStartOffset(line), myDocument.getLineEndOffset(line)); myCurrentHint = EditorFragmentComponent.showEditorFragmentHint(EditorImpl.this, textRange, false, false); } } } } @Override public void caretAdded(CaretEvent e) { if (myPrimaryCaret != null) { myPrimaryCaret.updateVisualPosition(); // repainting old primary caret's row background } repaintCaretRegion(e); myPrimaryCaret = myCaretModel.getPrimaryCaret(); } @Override public void caretRemoved(CaretEvent e) { repaintCaretRegion(e); myPrimaryCaret = myCaretModel.getPrimaryCaret(); // repainting new primary caret's row background myPrimaryCaret.updateVisualPosition(); } }); myCaretCursor = new CaretCursor(); myFoldingModel.flushCaretShift(); myScrollBarOrientation = VERTICAL_SCROLLBAR_RIGHT; mySoftWrapModel.addSoftWrapChangeListener(new SoftWrapChangeListenerAdapter() { @Override public void recalculationEnds() { if (myCaretModel.isUpToDate()) { myCaretModel.updateVisualPosition(); } } }); EditorHighlighter highlighter = new NullEditorHighlighter(); setHighlighter(highlighter); myEditorComponent = new EditorComponentImpl(this); myScrollPane.putClientProperty(JBScrollPane.BRIGHTNESS_FROM_VIEW, true); myVerticalScrollBar = (MyScrollBar)myScrollPane.getVerticalScrollBar(); myVerticalScrollBar.setOpaque(false); myPanel = new JPanel(); UIUtil.putClientProperty( myPanel, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, (Iterable<JComponent>)() -> { JComponent component = getPermanentHeaderComponent(); if (component != null && component.getParent() == null) { return Collections.singleton(component).iterator(); } return ContainerUtil.emptyIterator(); }); myHeaderPanel = new MyHeaderPanel(); myGutterComponent = new EditorGutterComponentImpl(this); initComponent(); myView = new EditorView(this); myView.reinitSettings(); myInlayModel.addListener(new InlayModel.SimpleAdapter() { @Override public void onUpdated(@NotNull Inlay inlay) { if (myDocument.isInEventsHandling() || myDocument.isInBulkUpdate()) return; validateSize(); repaint(inlay.getOffset(), inlay.getOffset(), false); } }, myCaretModel); if (UISettings.getInstance().getPresentationMode()) { setFontSize(UISettings.getInstance().getPresentationModeFontSize()); } myGutterComponent.updateSize(); Dimension preferredSize = getPreferredSize(); myEditorComponent.setSize(preferredSize); updateCaretCursor(); if (SystemInfo.isJavaVersionAtLeast("1.8") && SystemInfo.isMacIntel64 && SystemInfo.isJetBrainsJvm && Registry.is("ide.mac.forceTouch")) { new MacGestureSupportForEditor(getComponent()); } myScrollingModel.addVisibleAreaListener(this::moveCaretIntoViewIfCoveredByToolWindowBelow); } private void moveCaretIntoViewIfCoveredByToolWindowBelow(VisibleAreaEvent e) { Rectangle oldRectangle = e.getOldRectangle(); Rectangle newRectangle = e.getNewRectangle(); if (!myScrollingToCaret && oldRectangle != null && oldRectangle.height != newRectangle.height && oldRectangle.y == newRectangle.y && newRectangle.height > 0) { int caretY = myView.visualLineToY(myCaretModel.getVisualPosition().line); if (caretY < oldRectangle.getMaxY() && caretY > newRectangle.getMaxY()) { myScrollingToCaret = true; ApplicationManager.getApplication().invokeLater(() -> { myScrollingToCaret = false; if (!isReleased) EditorUtil.runWithAnimationDisabled(this, () -> myScrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)); }, ModalityState.any()); } } } /** * This method is intended to control a blit-accelerated scrolling, because transparent scrollbars suppress it. * Blit-acceleration copies as much of the rendered area as possible and then repaints only newly exposed region. * It is possible to disable blit-acceleration using by the registry key {@code editor.transparent.scrollbar=true}. * Also, when there's a background image, blit-acceleration cannot be used (because of the static overlay). * In such cases this method returns {@code false} to use transparent scrollbars as designed. * Enabled blit-acceleration improves scrolling performance and reduces CPU usage * (especially if drawing is compute-intensive). * <p> * To have both the hardware acceleration and the background image * we need to completely redesign JViewport machinery to support independent layers, * which is (probably) possible, but it's a rather cumbersome task. * Smooth scrolling still works event without the blit-acceleration, * but with suboptimal performance and CPU usage. * * @return {@code true} if a scrollbar should be opaque, {@code false} otherwise */ boolean shouldScrollBarBeOpaque() { return !myBackgroundImageSet && !Registry.is("editor.transparent.scrollbar"); } public boolean shouldSoftWrapsBeForced() { if (myProject != null && PsiDocumentManager.getInstance(myProject).isDocumentBlockedByPsi(myDocument)) { // Disable checking for files in intermediate states - e.g. for files during refactoring. return false; } int lineWidthLimit = Registry.intValue("editor.soft.wrap.force.limit"); for (int i = 0; i < myDocument.getLineCount(); i++) { if (myDocument.getLineEndOffset(i) - myDocument.getLineStartOffset(i) > lineWidthLimit) { return true; } } return false; } @NotNull static Color adjustThumbColor(@NotNull Color base, boolean dark) { return dark ? ColorUtil.withAlpha(ColorUtil.shift(base, 1.35), 0.5) : ColorUtil.withAlpha(ColorUtil.shift(base, 0.68), 0.4); } boolean isDarkEnough() { return ColorUtil.isDark(getBackgroundColor()); } private void repaintCaretRegion(CaretEvent e) { CaretImpl caretImpl = (CaretImpl)e.getCaret(); if (caretImpl != null) { caretImpl.updateVisualPosition(); if (caretImpl.hasSelection()) { repaint(caretImpl.getSelectionStart(), caretImpl.getSelectionEnd(), false); } } } @NotNull @Override public EditorColorsScheme createBoundColorSchemeDelegate(@Nullable final EditorColorsScheme customGlobalScheme) { return new MyColorSchemeDelegate(customGlobalScheme); } private void repaintGuide(@Nullable IndentGuideDescriptor guide) { if (guide != null) { repaintLines(guide.startLine, guide.endLine); } } @Override public int getPrefixTextWidthInPixels() { return (int)myView.getPrefixTextWidthInPixels(); } @Override public void setPrefixTextAndAttributes(@Nullable String prefixText, @Nullable TextAttributes attributes) { mySoftWrapModel.recalculate(); myView.setPrefix(prefixText, attributes); } @Override public boolean isPurePaintingMode() { return myPurePaintingMode; } @Override public void setPurePaintingMode(boolean enabled) { myPurePaintingMode = enabled; } @Override public void registerScrollBarRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) { myVerticalScrollBar.registerRepaintCallback(callback); } @Override public int getExpectedCaretOffset() { int expectedCaretOffset = myExpectedCaretOffset; return expectedCaretOffset == -1 ? getCaretModel().getOffset() : expectedCaretOffset; } @Override public void setContextMenuGroupId(@Nullable String groupId) { myContextMenuGroupId = groupId; } @Nullable @Override public String getContextMenuGroupId() { return myContextMenuGroupId; } @Override public void setViewer(boolean isViewer) { myIsViewer = isViewer; } @Override public boolean isViewer() { return myIsViewer || myIsRendererMode; } @Override public boolean isRendererMode() { return myIsRendererMode; } @Override public void setRendererMode(boolean isRendererMode) { myIsRendererMode = isRendererMode; } @Override public void setFile(VirtualFile vFile) { myVirtualFile = vFile; reinitSettings(); } @Override public VirtualFile getVirtualFile() { return myVirtualFile; } @Override public void setSoftWrapAppliancePlace(@NotNull SoftWrapAppliancePlaces place) { mySettings.setSoftWrapAppliancePlace(place); } @Override @NotNull public SelectionModelImpl getSelectionModel() { return mySelectionModel; } @Override @NotNull public MarkupModelEx getMarkupModel() { return myMarkupModel; } @Override @NotNull public MarkupModelEx getFilteredDocumentMarkupModel() { return myDocumentMarkupModel; } @Override @NotNull public FoldingModelImpl getFoldingModel() { return myFoldingModel; } @Override @NotNull public CaretModelImpl getCaretModel() { return myCaretModel; } @Override @NotNull public ScrollingModelEx getScrollingModel() { return myScrollingModel; } @Override @NotNull public SoftWrapModelImpl getSoftWrapModel() { return mySoftWrapModel; } @NotNull @Override public InlayModelImpl getInlayModel() { return myInlayModel; } @NotNull @Override public EditorKind getEditorKind() { return myKind; } @Override @NotNull public EditorSettings getSettings() { assertReadAccess(); return mySettings; } public void resetSizes() { myView.reset(); } @Override public void reinitSettings() { assertIsDispatchThread(); for (EditorColorsScheme scheme = myScheme; scheme instanceof DelegateColorScheme; scheme = ((DelegateColorScheme)scheme).getDelegate()) { if (scheme instanceof MyColorSchemeDelegate) { ((MyColorSchemeDelegate)scheme).updateGlobalScheme(); break; } } boolean softWrapsUsedBefore = mySoftWrapModel.isSoftWrappingEnabled(); mySettings.reinitSettings(); mySoftWrapModel.reinitSettings(); myCaretModel.reinitSettings(); mySelectionModel.reinitSettings(); ourCaretBlinkingCommand.setBlinkCaret(mySettings.isBlinkCaret()); ourCaretBlinkingCommand.setBlinkPeriod(mySettings.getCaretBlinkPeriod()); myView.reinitSettings(); myFoldingModel.rebuild(); myInlayModel.reinitSettings(); if (softWrapsUsedBefore ^ mySoftWrapModel.isSoftWrappingEnabled()) { validateSize(); } myHighlighter.setColorScheme(myScheme); myFoldingModel.refreshSettings(); myGutterComponent.reinitSettings(); myGutterComponent.revalidate(); myEditorComponent.repaint(); updateCaretCursor(); if (myInitialMouseEvent != null) { myIgnoreMouseEventsConsecutiveToInitial = true; } myCaretModel.updateVisualPosition(); // make sure carets won't appear at invalid positions (e.g. on Tab width change) for (Caret caret : getCaretModel().getAllCarets()) { caret.moveToOffset(caret.getOffset()); } if (myVirtualFile != null && myProject != null) { final EditorNotifications editorNotifications = EditorNotifications.getInstance(myProject); if (editorNotifications != null) { editorNotifications.updateNotifications(myVirtualFile); } } } /** * To be called when editor was not disposed while it should */ void throwEditorNotDisposedError(@NonNls @NotNull final String msg) { myTraceableDisposable.throwObjectNotDisposedError(msg); } /** * In case of "editor not disposed error" use {@link #throwEditorNotDisposedError(String)} */ public void throwDisposalError(@NonNls @NotNull String msg) { myTraceableDisposable.throwDisposalError(msg); } // EditorFactory.releaseEditor should be used to release editor void release() { assertIsDispatchThread(); if (isReleased) { throwDisposalError("Double release of editor:"); } myTraceableDisposable.kill(null); isReleased = true; mySizeAdjustmentStrategy.cancelAllRequests(); myFoldingModel.dispose(); mySoftWrapModel.release(); myMarkupModel.dispose(); myScrollingModel.dispose(); myGutterComponent.dispose(); myMousePressedEvent = null; myMouseMovedEvent = null; Disposer.dispose(myCaretModel); Disposer.dispose(mySoftWrapModel); Disposer.dispose(myView); clearCaretThread(); myFocusListeners.clear(); myMouseListeners.clear(); myMouseMotionListeners.clear(); myEditorComponent.removeMouseListener(myMouseListener); myGutterComponent.removeMouseListener(myMouseListener); myEditorComponent.removeMouseMotionListener(myMouseMotionListener); myGutterComponent.removeMouseMotionListener(myMouseMotionListener); if (myBulkUpdateListener != null) { ((DocumentImpl)myDocument).removeInternalBulkModeListener(myBulkUpdateListener); } Disposer.dispose(myDisposable); myVerticalScrollBar.setUI(null); // clear error panel's cached image } private void clearCaretThread() { synchronized (ourCaretBlinkingCommand) { if (ourCaretBlinkingCommand.myEditor == this) { ourCaretBlinkingCommand.myEditor = null; } } } private void initComponent() { myPanel.setLayout(new BorderLayout()); myPanel.add(myHeaderPanel, BorderLayout.NORTH); myGutterComponent.setOpaque(true); myScrollPane.setViewportView(myEditorComponent); //myScrollPane.setBorder(null); myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); myScrollPane.setRowHeaderView(myGutterComponent); myEditorComponent.setTransferHandler(new MyTransferHandler()); myEditorComponent.setAutoscrolls(true); if (mayShowToolbar()) { JLayeredPane layeredPane = new JBLayeredPane() { @Override public void doLayout() { final Component[] components = getComponents(); final Rectangle r = getBounds(); for (Component c : components) { if (c instanceof JScrollPane) { c.setBounds(0, 0, r.width, r.height); } else { final Dimension d = c.getPreferredSize(); int rightInsets = getVerticalScrollBar().getWidth() + (isMirrored() ? myGutterComponent.getWidth() : 0); c.setBounds(r.width - d.width - rightInsets - 20, 20, d.width, d.height); } } } @Override public Dimension getPreferredSize() { return myScrollPane.getPreferredSize(); } }; layeredPane.add(myScrollPane, JLayeredPane.DEFAULT_LAYER); myPanel.add(layeredPane); new ContextMenuImpl(layeredPane, myScrollPane, this); } else { myPanel.add(myScrollPane); } myEditorComponent.addKeyListener(new KeyListener() { @Override public void keyPressed(@NotNull KeyEvent e) { if (e.getKeyCode() >= KeyEvent.VK_A && e.getKeyCode() <= KeyEvent.VK_Z) { myCharKeyPressed = true; } } @Override public void keyTyped(@NotNull KeyEvent event) { myNeedToSelectPreviousChar = false; if (event.isConsumed()) { return; } if (processKeyTyped(event)) { event.consume(); } } @Override public void keyReleased(KeyEvent e) { myCharKeyPressed = false; } }); myEditorComponent.addMouseListener(myMouseListener); myGutterComponent.addMouseListener(myMouseListener); myEditorComponent.addMouseMotionListener(myMouseMotionListener); myGutterComponent.addMouseMotionListener(myMouseMotionListener); myEditorComponent.addFocusListener(new FocusAdapter() { @Override public void focusGained(@NotNull FocusEvent e) { myCaretCursor.activate(); for (Caret caret : myCaretModel.getAllCarets()) { int caretLine = caret.getLogicalPosition().line; repaintLines(caretLine, caretLine); } fireFocusGained(); } @Override public void focusLost(@NotNull FocusEvent e) { clearCaretThread(); for (Caret caret : myCaretModel.getAllCarets()) { int caretLine = caret.getLogicalPosition().line; repaintLines(caretLine, caretLine); } fireFocusLost(); } }); UiNotifyConnector connector = new UiNotifyConnector(myEditorComponent, new Activatable.Adapter() { @Override public void showNotify() { myGutterComponent.updateSizeOnShowNotify(); } }); Disposer.register(getDisposable(), connector); try { final DropTarget dropTarget = myEditorComponent.getDropTarget(); if (dropTarget != null) { // might be null in headless environment dropTarget.addDropTargetListener(new DropTargetAdapter() { @Override public void drop(@NotNull DropTargetDropEvent e) { } @Override public void dragOver(@NotNull DropTargetDragEvent e) { Point location = e.getLocation(); getCaretModel().moveToVisualPosition(getTargetPosition(location.x, location.y, true)); getScrollingModel().scrollToCaret(ScrollType.RELATIVE); requestFocus(); } }); } } catch (TooManyListenersException e) { LOG.error(e); } // update area available for soft wrapping on component shown/hidden myPanel.addHierarchyListener(e -> mySoftWrapModel.getApplianceManager().updateAvailableArea()); myPanel.addComponentListener(new ComponentAdapter() { @Override public void componentResized(@NotNull ComponentEvent e) { myMarkupModel.recalcEditorDimensions(); myMarkupModel.repaint(-1, -1); if (!isRightAligned()) return; updateCaretCursor(); myCaretCursor.repaint(); } }); } private boolean mayShowToolbar() { return !isEmbeddedIntoDialogWrapper() && !isOneLineMode() && ContextMenuImpl.mayShowToolbar(myDocument); } @Override public void setFontSize(final int fontSize) { setFontSize(fontSize, null); } /** * Changes editor font size, attempting to keep a given point unmoved. If point is not given, top left screen corner is assumed. * * @param fontSize new font size * @param zoomCenter zoom point, relative to viewport */ private void setFontSize(int fontSize, @Nullable Point zoomCenter) { int oldFontSize = myScheme.getEditorFontSize(); Rectangle visibleArea = myScrollingModel.getVisibleArea(); Point zoomCenterRelative = zoomCenter == null ? new Point() : zoomCenter; Point zoomCenterAbsolute = new Point(visibleArea.x + zoomCenterRelative.x, visibleArea.y + zoomCenterRelative.y); LogicalPosition zoomCenterLogical = xyToLogicalPosition(zoomCenterAbsolute).withoutVisualPositionInfo(); int oldLineHeight = getLineHeight(); int intraLineOffset = zoomCenterAbsolute.y % oldLineHeight; myScheme.setEditorFontSize(fontSize); fontSize = myScheme.getEditorFontSize(); // resulting font size might be different due to applied min/max limits myPropertyChangeSupport.firePropertyChange(PROP_FONT_SIZE, oldFontSize, fontSize); // Update vertical scroll bar bounds if necessary (we had a problem that use increased editor font size and it was not possible // to scroll to the bottom of the document). myScrollPane.getViewport().invalidate(); Point shiftedZoomCenterAbsolute = logicalPositionToXY(zoomCenterLogical); myScrollingModel.disableAnimation(); try { myScrollingModel.scroll(visibleArea.x == 0 ? 0 : shiftedZoomCenterAbsolute.x - zoomCenterRelative.x, // stick to left border if it's visible shiftedZoomCenterAbsolute.y - zoomCenterRelative.y + (intraLineOffset * getLineHeight() + oldLineHeight / 2) / oldLineHeight); } finally { myScrollingModel.enableAnimation(); } } public int getFontSize() { return myScheme.getEditorFontSize(); } @NotNull public ActionCallback type(@NotNull final String text) { final ActionCallback result = new ActionCallback(); for (int i = 0; i < text.length(); i++) { if (!processKeyTyped(text.charAt(i))) { result.setRejected(); return result; } } result.setDone(); return result; } private boolean processKeyTyped(char c) { // [vova] This is patch for Mac OS X. Under Mac "input methods" // is handled before our EventQueue consume upcoming KeyEvents. IdeEventQueue queue = IdeEventQueue.getInstance(); if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) { return false; } FileDocumentManager manager = FileDocumentManager.getInstance(); final VirtualFile file = manager.getFile(myDocument); if (file != null && !file.isValid()) { return false; } DataContext context = getDataContext(); Graphics graphics = GraphicsUtil.safelyGetGraphics(myEditorComponent); if (graphics != null) { // editor component is not showing processKeyTypedImmediately(c, graphics, context); graphics.dispose(); } ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, context); EditorUIUtil.hideCursorInEditor(this); processKeyTypedNormally(c, context); return true; } void processKeyTypedImmediately(char c, Graphics graphics, DataContext dataContext) { EditorActionPlan plan = new EditorActionPlan(this); EditorActionManager.getInstance().getTypedAction().beforeActionPerformed(this, c, dataContext, plan); myImmediatePainter.paint(graphics, plan); } void processKeyTypedNormally(char c, DataContext dataContext) { EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext); } private void fireFocusLost() { for (FocusChangeListener listener : myFocusListeners) { listener.focusLost(this); } } private void fireFocusGained() { for (FocusChangeListener listener : myFocusListeners) { listener.focusGained(this); } } @Override public void setHighlighter(@NotNull final EditorHighlighter highlighter) { if (isReleased) return; // do not set highlighter to the released editor assertIsDispatchThread(); final Document document = getDocument(); Disposer.dispose(myHighlighterDisposable); document.addDocumentListener(highlighter); myHighlighterDisposable = () -> document.removeDocumentListener(highlighter); Disposer.register(myDisposable, myHighlighterDisposable); highlighter.setEditor(this); highlighter.setText(document.getImmutableCharSequence()); if (!(highlighter instanceof EmptyEditorHighlighter)) { EditorHighlighterCache.rememberEditorHighlighterForCachesOptimization(document, highlighter); } myHighlighter = highlighter; if (myPanel != null) { reinitSettings(); } } @NotNull @Override public EditorHighlighter getHighlighter() { assertReadAccess(); return myHighlighter; } @Override @NotNull public EditorComponentImpl getContentComponent() { return myEditorComponent; } @NotNull @Override public EditorGutterComponentImpl getGutterComponentEx() { return myGutterComponent; } @Override public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) { myPropertyChangeSupport.addPropertyChangeListener(listener); } @Override public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener, @NotNull Disposable parentDisposable) { addPropertyChangeListener(listener); Disposer.register(parentDisposable, () -> removePropertyChangeListener(listener)); } @Override public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) { myPropertyChangeSupport.removePropertyChangeListener(listener); } @Override public void setInsertMode(boolean mode) { assertIsDispatchThread(); boolean oldValue = myIsInsertMode; myIsInsertMode = mode; myPropertyChangeSupport.firePropertyChange(PROP_INSERT_MODE, oldValue, mode); myCaretCursor.repaint(); } @Override public boolean isInsertMode() { return myIsInsertMode; } @Override public void setColumnMode(boolean mode) { assertIsDispatchThread(); boolean oldValue = myIsColumnMode; myIsColumnMode = mode; myPropertyChangeSupport.firePropertyChange(PROP_COLUMN_MODE, oldValue, mode); } @Override public boolean isColumnMode() { return myIsColumnMode; } public int yToVisibleLine(int y) { return myView.yToVisualLine(y); } @Override @NotNull public VisualPosition xyToVisualPosition(@NotNull Point p) { return myView.xyToVisualPosition(p); } @Override @NotNull public VisualPosition xyToVisualPosition(@NotNull Point2D p) { return myView.xyToVisualPosition(p); } @Override @NotNull public Point2D offsetToPoint2D(int offset, boolean leanTowardsLargerOffsets, boolean beforeSoftWrap) { return myView.offsetToXY(offset, leanTowardsLargerOffsets, beforeSoftWrap); } @Override @NotNull public Point offsetToXY(int offset, boolean leanForward, boolean beforeSoftWrap) { Point2D point2D = offsetToPoint2D(offset, leanForward, beforeSoftWrap); return new Point((int)point2D.getX(), (int)point2D.getY()); } @Override @NotNull public VisualPosition offsetToVisualPosition(int offset) { return offsetToVisualPosition(offset, false, false); } @Override @NotNull public VisualPosition offsetToVisualPosition(int offset, boolean leanForward, boolean beforeSoftWrap) { return myView.offsetToVisualPosition(offset, leanForward, beforeSoftWrap); } @Override @NotNull public LogicalPosition offsetToLogicalPosition(int offset) { return myView.offsetToLogicalPosition(offset); } @TestOnly public void setCaretActive() { synchronized (ourCaretBlinkingCommand) { ourCaretBlinkingCommand.myEditor = this; } } // optimization: do not do column calculations here since we are interested in line number only int offsetToVisualLine(int offset) { return myView.offsetToVisualLine(offset, false); } public int visualLineStartOffset(int visualLine) { return myView.visualLineToOffset(visualLine); } @Override @NotNull public LogicalPosition xyToLogicalPosition(@NotNull Point p) { Point pp = p.x >= 0 && p.y >= 0 ? p : new Point(Math.max(p.x, 0), Math.max(p.y, 0)); return visualToLogicalPosition(xyToVisualPosition(pp)); } private int logicalLineToY(int line) { int visualLine = line < myDocument.getLineCount() ? offsetToVisualLine(myDocument.getLineStartOffset(line)) : logicalToVisualPosition(new LogicalPosition(line, 0)).line; return visibleLineToY(visualLine); } @Override @NotNull public Point logicalPositionToXY(@NotNull LogicalPosition pos) { VisualPosition visible = logicalToVisualPosition(pos); return visualPositionToXY(visible); } @Override @NotNull public Point visualPositionToXY(@NotNull VisualPosition visible) { Point2D point2D = myView.visualPositionToXY(visible); return new Point((int)point2D.getX(), (int)point2D.getY()); } @Override @NotNull public Point2D visualPositionToPoint2D(@NotNull VisualPosition visible) { return myView.visualPositionToXY(visible); } /** * Returns how much current line height bigger than the normal (16px) * This method is used to scale editors elements such as gutter icons, folding elements, and others */ public float getScale() { if (!Registry.is("editor.scale.gutter.icons")) return 1f; float normLineHeight = getLineHeight() / myScheme.getLineSpacing(); // normalized, as for 1.0f line spacing return normLineHeight / JBUI.scale(16f); } public int findNearestDirectionBoundary(int offset, boolean lookForward) { return myView.findNearestDirectionBoundary(offset, lookForward); } public int visibleLineToY(int line) { return myView.visualLineToY(line); } @Override public void repaint(int startOffset, int endOffset) { repaint(startOffset, endOffset, true); } void repaint(int startOffset, int endOffset, boolean invalidateTextLayout) { if (myDocument.isInBulkUpdate()) { return; } assertIsDispatchThread(); endOffset = Math.min(endOffset, myDocument.getTextLength()); if (invalidateTextLayout) { myView.invalidateRange(startOffset, endOffset); } if (!isShowing()) { return; } // We do repaint in case of equal offsets because there is a possible case that there is a soft wrap at the same offset and // it does occupy particular amount of visual space that may be necessary to repaint. if (startOffset <= endOffset) { int startLine = myDocument.getLineNumber(startOffset); int endLine = myDocument.getLineNumber(endOffset); repaintLines(startLine, endLine); } } private boolean isShowing() { return myGutterComponent.isShowing(); } private void repaintToScreenBottom(int startLine) { Rectangle visibleArea = getScrollingModel().getVisibleArea(); int yStartLine = logicalLineToY(startLine); int yEndLine = visibleArea.y + visibleArea.height; myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, yEndLine - yStartLine); myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), yEndLine - yStartLine); ((EditorMarkupModelImpl)getMarkupModel()).repaint(-1, -1); } /** * Asks to repaint all logical lines from the given {@code [start; end]} range. * * @param startLine start logical line to repaint (inclusive) * @param endLine end logical line to repaint (inclusive) */ private void repaintLines(int startLine, int endLine) { if (!isShowing()) return; Rectangle visibleArea = getScrollingModel().getVisibleArea(); int yStartLine = logicalLineToY(startLine); int endVisLine = myDocument.getTextLength() <= 0 ? 0 : offsetToVisualLine(myDocument.getLineEndOffset(Math.min(myDocument.getLineCount() - 1, endLine))); int height = endVisLine * getLineHeight() - yStartLine + getLineHeight() + 2; myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, height); myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), height); } private void bulkUpdateStarted() { myView.getPreferredSize(); // make sure size is calculated (in case it will be required while bulk mode is active) myScrollingModel.onBulkDocumentUpdateStarted(); saveCaretRelativePosition(); myCaretModel.onBulkDocumentUpdateStarted(); mySoftWrapModel.onBulkDocumentUpdateStarted(); myFoldingModel.onBulkDocumentUpdateStarted(); } private void bulkUpdateFinished() { myFoldingModel.onBulkDocumentUpdateFinished(); mySoftWrapModel.onBulkDocumentUpdateFinished(); myView.reset(); myCaretModel.onBulkDocumentUpdateFinished(); setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); validateSize(); updateGutterSize(); repaintToScreenBottom(0); updateCaretCursor(); if (!Boolean.TRUE.equals(getUserData(DISABLE_CARET_POSITION_KEEPING))) { restoreCaretRelativePosition(); } } private void beforeChangedUpdate() { ApplicationManager.getApplication().assertIsDispatchThread(); myDocumentChangeInProgress = true; if (isStickySelection()) { setStickySelection(false); } if (myDocument.isInBulkUpdate()) { // Assuming that the job is done at bulk listener callback methods. return; } saveCaretRelativePosition(); } void invokeDelayedErrorStripeRepaint() { if (myErrorStripeNeedsRepaint) { myMarkupModel.repaint(-1, -1); myErrorStripeNeedsRepaint = false; } } private void changedUpdate(DocumentEvent e) { myDocumentChangeInProgress = false; if (myDocument.isInBulkUpdate()) return; if (myErrorStripeNeedsRepaint) { myMarkupModel.repaint(e.getOffset(), e.getOffset() + e.getNewLength()); myErrorStripeNeedsRepaint = false; } setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); validateSize(); int startLine = offsetToLogicalLine(e.getOffset()); int endLine = offsetToLogicalLine(e.getOffset() + e.getNewLength()); boolean painted = false; if (myDocument.getTextLength() > 0) { if (startLine != endLine || StringUtil.indexOf(e.getOldFragment(), '\n') != -1) { myGutterComponent.clearLineToGutterRenderersCache(); } if (countLineFeeds(e.getOldFragment()) != countLineFeeds(e.getNewFragment())) { // Lines removed. Need to repaint till the end of the screen repaintToScreenBottom(startLine); painted = true; } } updateCaretCursor(); if (!painted) { repaintLines(startLine, endLine); } if (!Boolean.TRUE.equals(getUserData(DISABLE_CARET_POSITION_KEEPING)) && (getCaretModel().getOffset() < e.getOffset() || getCaretModel().getOffset() > e.getOffset() + e.getNewLength())) { restoreCaretRelativePosition(); } } public void hideCursor() { if (!myIsViewer && Registry.is("ide.hide.cursor.when.typing") && EMPTY_CURSOR != null && EMPTY_CURSOR != myEditorComponent.getCursor()) { myEditorComponent.setCursor(EMPTY_CURSOR); } } private void saveCaretRelativePosition() { Rectangle visibleArea = getScrollingModel().getVisibleArea(); Point pos = visualPositionToXY(getCaretModel().getVisualPosition()); myCaretUpdateVShift = pos.y - visibleArea.y; } private void restoreCaretRelativePosition() { Point caretLocation = visualPositionToXY(getCaretModel().getVisualPosition()); int scrollOffset = caretLocation.y - myCaretUpdateVShift; getScrollingModel().disableAnimation(); getScrollingModel().scrollVertically(scrollOffset); getScrollingModel().enableAnimation(); } public boolean isScrollToCaret() { return myScrollToCaret; } public void setScrollToCaret(boolean scrollToCaret) { myScrollToCaret = scrollToCaret; } @NotNull public Disposable getDisposable() { return myDisposable; } private static int countLineFeeds(@NotNull CharSequence c) { return StringUtil.countNewLines(c); } private boolean updatingSize; // accessed from EDT only private void updateGutterSize() { assertIsDispatchThread(); if (!updatingSize) { updatingSize = true; ApplicationManager.getApplication().invokeLater(() -> { try { if (!isDisposed()) { myGutterComponent.updateSize(); } } finally { updatingSize = false; } }, ModalityState.any(), __->isDisposed()); } } void validateSize() { if (isReleased) return; Dimension dim = getPreferredSize(); if (!dim.equals(myPreferredSize) && !myDocument.isInBulkUpdate()) { dim = mySizeAdjustmentStrategy.adjust(dim, myPreferredSize, this); if (!dim.equals(myPreferredSize)) { myPreferredSize = dim; updateGutterSize(); myEditorComponent.setSize(dim); myEditorComponent.fireResized(); myMarkupModel.recalcEditorDimensions(); myMarkupModel.repaint(-1, -1); } } } void recalculateSizeAndRepaint() { validateSize(); myEditorComponent.repaintEditorComponent(); } @Override @NotNull public DocumentEx getDocument() { return myDocument; } @Override @NotNull public JComponent getComponent() { return myPanel; } @Override public void addEditorMouseListener(@NotNull EditorMouseListener listener) { myMouseListeners.add(listener); } @Override public void removeEditorMouseListener(@NotNull EditorMouseListener listener) { boolean success = myMouseListeners.remove(listener); LOG.assertTrue(success || isReleased); } @Override public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { myMouseMotionListeners.add(listener); } @Override public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { boolean success = myMouseMotionListeners.remove(listener); LOG.assertTrue(success || isReleased); } @Override public boolean isStickySelection() { return myStickySelection; } @Override public void setStickySelection(boolean enable) { myStickySelection = enable; if (enable) { myStickySelectionStart = getCaretModel().getOffset(); } else { mySelectionModel.removeSelection(); } } public void setHorizontalTextAlignment(@MagicConstant(intValues = {TEXT_ALIGNMENT_LEFT, TEXT_ALIGNMENT_RIGHT}) int alignment) { myHorizontalTextAlignment = alignment; } public boolean isRightAligned() { return myHorizontalTextAlignment == TEXT_ALIGNMENT_RIGHT; } @Override public boolean isDisposed() { return isReleased; } public void stopDumbLater() { if (ApplicationManager.getApplication().isUnitTestMode()) return; ApplicationManager.getApplication().invokeLater(this::stopDumb, ModalityState.current(), __ -> isDisposed()); } private void stopDumb() { putUserData(BUFFER, null); } /** * {@link #stopDumbLater} or {@link #stopDumb} must be performed in finally */ public void startDumb() { if (ApplicationManager.getApplication().isUnitTestMode()) return; if (!Registry.is("editor.dumb.mode.available")) return; putUserData(BUFFER, null); Rectangle rect = ((JViewport)myEditorComponent.getParent()).getViewRect(); // The LCD text loop is enabled only for opaque images BufferedImage image = UIUtil.createImage(myEditorComponent, rect.width, rect.height, BufferedImage.TYPE_INT_RGB); Graphics imageGraphics = image.createGraphics(); imageGraphics.translate(-rect.x, -rect.y); Graphics2D graphics = JBSwingUtilities.runGlobalCGTransform(myEditorComponent, imageGraphics); graphics.setClip(rect.x, rect.y, rect.width, rect.height); myEditorComponent.paintComponent(graphics); graphics.dispose(); putUserData(BUFFER, image); } public boolean isDumb() { return getUserData(BUFFER) != null; } void paint(@NotNull Graphics2D g) { Rectangle clip = g.getClipBounds(); if (clip == null) { return; } BufferedImage buffer = Registry.is("editor.dumb.mode.available") ? getUserData(BUFFER) : null; if (buffer != null) { Rectangle rect = getContentComponent().getVisibleRect(); UIUtil.drawImage(g, buffer, null, rect.x, rect.y); return; } if (isReleased) { g.setColor(getDisposedBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); return; } if (myUpdateCursor) { setCursorPosition(); myUpdateCursor = false; } if (myProject != null && myProject.isDisposed()) return; myView.paint(g); boolean isBackgroundImageSet = IdeBackgroundUtil.isEditorBackgroundImageSet(myProject); if (myBackgroundImageSet != isBackgroundImageSet) { myBackgroundImageSet = isBackgroundImageSet; updateOpaque(myScrollPane.getHorizontalScrollBar()); updateOpaque(myScrollPane.getVerticalScrollBar()); } } Color getDisposedBackground() { return new JBColor(new Color(128, 255, 128), new Color(128, 255, 128)); } @NotNull @Override public IndentsModel getIndentsModel() { return myIndentsModel; } @Override public void setHeaderComponent(JComponent header) { myHeaderPanel.removeAll(); header = header == null ? getPermanentHeaderComponent() : header; if (header != null) { myHeaderPanel.add(header); } myHeaderPanel.revalidate(); myHeaderPanel.repaint(); } @Override public boolean hasHeaderComponent() { JComponent header = getHeaderComponent(); return header != null && header != getPermanentHeaderComponent(); } @Override @Nullable public JComponent getPermanentHeaderComponent() { return getUserData(PERMANENT_HEADER); } @Override public void setPermanentHeaderComponent(@Nullable JComponent component) { putUserData(PERMANENT_HEADER, component); } @Override @Nullable public JComponent getHeaderComponent() { if (myHeaderPanel.getComponentCount() > 0) { return (JComponent)myHeaderPanel.getComponent(0); } return null; } @Override public void setBackgroundColor(Color color) { myScrollPane.setBackground(color); if (getBackgroundIgnoreForced().equals(color)) { myForcedBackground = null; return; } myForcedBackground = color; } @NotNull Color getForegroundColor() { return myScheme.getDefaultForeground(); } @NotNull @Override public Color getBackgroundColor() { if (myForcedBackground != null) return myForcedBackground; return getBackgroundIgnoreForced(); } @NotNull @Override public TextDrawingCallback getTextDrawingCallback() { return myTextDrawingCallback; } @Override public void setPlaceholder(@Nullable CharSequence text) { myPlaceholderText = text; } @Override public void setPlaceholderAttributes(@Nullable TextAttributes attributes) { myPlaceholderAttributes = attributes; } public TextAttributes getPlaceholderAttributes() { return myPlaceholderAttributes; } public CharSequence getPlaceholder() { return myPlaceholderText; } @Override public void setShowPlaceholderWhenFocused(boolean show) { myShowPlaceholderWhenFocused = show; } public boolean getShowPlaceholderWhenFocused() { return myShowPlaceholderWhenFocused; } Color getBackgroundColor(@NotNull final TextAttributes attributes) { final Color attrColor = attributes.getBackgroundColor(); return Comparing.equal(attrColor, myScheme.getDefaultBackground()) ? getBackgroundColor() : attrColor; } @NotNull private Color getBackgroundIgnoreForced() { Color color = myScheme.getDefaultBackground(); if (myDocument.isWritable()) { return color; } Color readOnlyColor = myScheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR); return readOnlyColor != null ? readOnlyColor : color; } @Nullable public TextRange getComposedTextRange() { return myInputMethodRequestsHandler == null || myInputMethodRequestsHandler.composedText == null ? null : myInputMethodRequestsHandler.composedTextRange; } @Override public int getMaxWidthInRange(int startOffset, int endOffset) { return myView.getMaxWidthInRange(startOffset, endOffset); } public boolean isPaintSelection() { return myPaintSelection || !isOneLineMode() || IJSwingUtilities.hasFocus(getContentComponent()); } public void setPaintSelection(boolean paintSelection) { myPaintSelection = paintSelection; } @Override @NotNull @NonNls public String dumpState() { return "allow caret inside tab: " + mySettings.isCaretInsideTabs() + ", allow caret after line end: " + mySettings.isVirtualSpace() + ", soft wraps: " + (mySoftWrapModel.isSoftWrappingEnabled() ? "on" : "off") + ", caret model: " + getCaretModel().dumpState() + ", soft wraps data: " + getSoftWrapModel().dumpState() + "\n\nfolding data: " + getFoldingModel().dumpState() + (myDocument instanceof DocumentImpl ? "\n\ndocument info: " + ((DocumentImpl)myDocument).dumpState() : "") + "\nfont preferences: " + myScheme.getFontPreferences() + "\npure painting mode: " + myPurePaintingMode + "\ninsets: " + myEditorComponent.getInsets() + (myView == null ? "" : "\nview: " + myView.dumpState()); } @Nullable public CaretRectangle[] getCaretLocations(boolean onlyIfShown) { return myCaretCursor.getCaretLocations(onlyIfShown); } public int getAscent() { return myView.getAscent(); } @Override public int getLineHeight() { return myView.getLineHeight(); } public int getDescent() { return myView.getDescent(); } public int getCharHeight() { return myView.getCharHeight(); } @NotNull public FontMetrics getFontMetrics(@JdkConstants.FontStyle int fontType) { EditorFontType ft; if (fontType == Font.PLAIN) ft = EditorFontType.PLAIN; else if (fontType == Font.BOLD) ft = EditorFontType.BOLD; else if (fontType == Font.ITALIC) ft = EditorFontType.ITALIC; else if (fontType == (Font.BOLD | Font.ITALIC)) ft = EditorFontType.BOLD_ITALIC; else { LOG.error("Unknown font type: " + fontType); ft = EditorFontType.PLAIN; } return myEditorComponent.getFontMetrics(myScheme.getFont(ft)); } public int getPreferredHeight() { return isReleased ? 0 : myView.getPreferredHeight(); } public Dimension getPreferredSize() { return isReleased ? new Dimension() : Registry.is("idea.true.smooth.scrolling.dynamic.scrollbars") ? new Dimension(getPreferredWidthOfVisibleLines(), myView.getPreferredHeight()) : myView.getPreferredSize(); } /* When idea.true.smooth.scrolling=true, this method is used to compute width of currently visible line range rather than width of the whole document. As transparent scrollbars, by definition, prevent blit-acceleration of scrolling, and we really need blit-acceleration because not all hardware can render pixel-by-pixel scrolling with acceptable FPS without it (we now have 4K-5K displays, you know). To have both the hardware acceleration and the transparent scrollbars we need to completely redesign JViewport machinery to support independent layers, which is (probably) possible, but it's a rather cumbersome task. Another approach is to make scrollbars opaque, but only in the editor (as editor is a slow-to-draw component with large screen area). This is what "true smooth scrolling" option currently does. Interestingly, making the vertical scrollbar opaque might actually be a good thing because on modern displays (size, aspect ratio) code rarely extends beyond the right screen edge, and even when it does, its mixing with the navigation bar only reduces intelligibility of both the navigation bar and the code itself. Horizontal scrollbar is another story - a single long line of text forces horizontal scrollbar in the whole document, and in that case "transparent" scrollbar has some merits. However, instead of using transparency, we can hide horizontal scrollbar altogether when it's not needed for currently visible content. In a sense, this approach is superior, as even "transparent" scrollbar is only semi-transparent (thus we may prefer "on-demand" scrollbar in the general case). Hiding the horizontal scrollbar also solves another issue - when both scrollbars are visible, vertical scrolling with a high-precision touchpad can result in unintentional horizontal shifts (because of the touchpad sensitivity). When visible content fully fits horizontally (i.e. in most cases), hiding the unneeded scrollbar reliably prevents the horizontal "jitter". Keep in mind that this functionality is experimental and may need more polishing. In principle, we can apply this method to other components by defining, for example, VariableWidth interface and supporting it in JBScrollPane. */ private int getPreferredWidthOfVisibleLines() { Rectangle area = getScrollingModel().getVisibleArea(); VisualPosition begin = xyToVisualPosition(area.getLocation()); VisualPosition end = xyToVisualPosition(new Point(area.x + area.width, area.y + area.height)); return Math.max(myView.getPreferredWidth(begin.line, end.line), getScrollingWidth()); } /* Returns the width of current horizontal scrolling state. Complements the getPreferredWidthOfVisibleLines() method to allows to retain horizontal scrolling position that is beyond the width of currently visible lines. */ private int getScrollingWidth() { JScrollBar scrollbar = myScrollPane.getHorizontalScrollBar(); if (scrollbar != null) { BoundedRangeModel model = scrollbar.getModel(); if (model != null) { return model.getValue() + model.getExtent(); } } return 0; } @NotNull @Override public Dimension getContentSize() { return myView.getPreferredSize(); } @NotNull @Override public JScrollPane getScrollPane() { return myScrollPane; } @Override public void setBorder(Border border) { myScrollPane.setBorder(border); } @Override public Insets getInsets() { return myScrollPane.getInsets(); } @Override public int logicalPositionToOffset(@NotNull LogicalPosition pos) { return myView.logicalPositionToOffset(pos); } /** * @return information about total number of lines that can be viewed by user. I.e. this is a number of all document * lines (considering that single logical document line may be represented on multiple visual lines because of * soft wraps appliance) minus number of folded lines */ public int getVisibleLineCount() { return getVisibleLogicalLinesCount() + getSoftWrapModel().getSoftWrapsIntroducedLinesNumber(); } /** * @return number of visible logical lines. Generally, that is a total logical lines number minus number of folded lines */ private int getVisibleLogicalLinesCount() { return getDocument().getLineCount() - myFoldingModel.getTotalNumberOfFoldedLines(); } @Override @NotNull public VisualPosition logicalToVisualPosition(@NotNull LogicalPosition logicalPos) { return myView.logicalToVisualPosition(logicalPos, false); } @Override @NotNull public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visiblePos) { return myView.visualToLogicalPosition(visiblePos); } private int offsetToLogicalLine(int offset) { int textLength = myDocument.getTextLength(); if (textLength == 0) return 0; if (offset > textLength || offset < 0) { throw new IndexOutOfBoundsException("Wrong offset: " + offset + " textLength: " + textLength); } int lineIndex = myDocument.getLineNumber(offset); LOG.assertTrue(lineIndex >= 0 && lineIndex < myDocument.getLineCount()); return lineIndex; } @Override public int calcColumnNumber(int offset, int lineIndex) { return myView.offsetToLogicalPosition(offset).column; } private VisualPosition getTargetPosition(int x, int y, boolean trimToLineWidth) { if (myDocument.getLineCount() == 0) { return new VisualPosition(0, 0); } if (x < 0) { x = 0; } if (y < 0) { y = 0; } int visualLineCount = getVisibleLineCount(); if (yToVisibleLine(y) >= visualLineCount) { y = visibleLineToY(Math.max(0, visualLineCount - 1)); } VisualPosition visualPosition = xyToVisualPosition(new Point(x, y)); if (trimToLineWidth && !mySettings.isVirtualSpace()) { LogicalPosition logicalPosition = visualToLogicalPosition(visualPosition); LogicalPosition lineEndPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logicalPosition.line)); if (logicalPosition.column > lineEndPosition.column) { visualPosition = logicalToVisualPosition(lineEndPosition.leanForward(true)); } else if (mySoftWrapModel.isInsideSoftWrap(visualPosition)) { VisualPosition beforeSoftWrapPosition = myView.logicalToVisualPosition(logicalPosition, true); if (visualPosition.line == beforeSoftWrapPosition.line) { visualPosition = beforeSoftWrapPosition; } else { visualPosition = myView.logicalToVisualPosition(logicalPosition, false); } } } return visualPosition; } private boolean checkIgnore(@NotNull MouseEvent e) { if (!myIgnoreMouseEventsConsecutiveToInitial) { myInitialMouseEvent = null; return false; } if (myInitialMouseEvent!= null && (e.getComponent() != myInitialMouseEvent.getComponent() || !e.getPoint().equals(myInitialMouseEvent.getPoint()))) { myIgnoreMouseEventsConsecutiveToInitial = false; myInitialMouseEvent = null; return false; } myIgnoreMouseEventsConsecutiveToInitial = false; myInitialMouseEvent = null; e.consume(); return true; } private void processMouseReleased(@NotNull MouseEvent e) { if (checkIgnore(e)) return; if (e.getSource() == myGutterComponent && !(myMousePressedEvent != null && myMousePressedEvent.isConsumed())) { myGutterComponent.mouseReleased(e); } if (getMouseEventArea(e) != EditorMouseEventArea.EDITING_AREA || e.getY() < 0 || e.getX() < 0) { return; } // if (myMousePressedInsideSelection) getSelectionModel().removeSelection(); final FoldRegion region = getFoldingModel().getFoldingPlaceholderAt(e.getPoint()); if (e.getX() >= 0 && e.getY() >= 0 && region != null && region == myMouseSelectedRegion) { getFoldingModel().runBatchFoldingOperation(() -> { myFoldingModel.flushCaretShift(); region.setExpanded(true); }); // The call below is performed because gutter's height is not updated sometimes, i.e. it sticks to the value that corresponds // to the situation when fold region is collapsed. That causes bottom of the gutter to not be repainted and that looks really ugly. myGutterComponent.updateSize(); } // The general idea is to check if the user performed 'caret position change click' (left click most of the time) inside selection // and, in the case of the positive answer, clear selection. Please note that there is a possible case that mouse click // is performed inside selection but it triggers context menu. We don't want to drop the selection then. if (myMousePressedEvent != null && myMousePressedEvent.getClickCount() == 1 && myMousePressedInsideSelection && !myMousePressedEvent.isShiftDown() && !myMousePressedEvent.isPopupTrigger() && !isToggleCaretEvent(myMousePressedEvent) && !isCreateRectangularSelectionEvent(myMousePressedEvent)) { getSelectionModel().removeSelection(); } } @NotNull @Override public DataContext getDataContext() { return getProjectAwareDataContext(DataManager.getInstance().getDataContext(getContentComponent())); } @NotNull private DataContext getProjectAwareDataContext(@NotNull final DataContext original) { if (CommonDataKeys.PROJECT.getData(original) == myProject) return original; return dataId -> { if (CommonDataKeys.PROJECT.is(dataId)) { return myProject; } return original.getData(dataId); }; } private boolean isInsideGutterWhitespaceArea(@NotNull MouseEvent e) { EditorMouseEventArea area = getMouseEventArea(e); return area == EditorMouseEventArea.FOLDING_OUTLINE_AREA && myGutterComponent.convertX(e.getX()) > myGutterComponent.getWhitespaceSeparatorOffset(); } @Override public EditorMouseEventArea getMouseEventArea(@NotNull MouseEvent e) { if (myGutterComponent != e.getSource()) return EditorMouseEventArea.EDITING_AREA; int x = myGutterComponent.convertX(e.getX()); return myGutterComponent.getEditorMouseAreaByOffset(x); } private void requestFocus() { final IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); if (focusManager.getFocusOwner() != myEditorComponent) { //IDEA-64501 focusManager.requestFocus(myEditorComponent, true); } } private void validateMousePointer(@NotNull MouseEvent e) { if (e.getSource() == myGutterComponent) { myGutterComponent.validateMousePointer(e); } else { myGutterComponent.setActiveFoldRegion(null); if (getSelectionModel().hasSelection() && (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK)) == 0) { int offset = logicalPositionToOffset(xyToLogicalPosition(e.getPoint())); if (getSelectionModel().getSelectionStart() <= offset && offset < getSelectionModel().getSelectionEnd()) { UIUtil.setCursor(myEditorComponent, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return; } } if (!IdeGlassPaneImpl.hasPreProcessedCursor(myEditorComponent)) { UIUtil.setCursor(myEditorComponent, UIUtil.getTextCursor(getBackgroundColor())); } } } private void runMouseDraggedCommand(@NotNull final MouseEvent e) { if (myCommandProcessor == null || myMousePressedEvent != null && myMousePressedEvent.isConsumed()) { return; } myCommandProcessor.executeCommand(myProject, () -> processMouseDragged(e), "", MOUSE_DRAGGED_GROUP, UndoConfirmationPolicy.DEFAULT, getDocument()); } private void processMouseDragged(@NotNull MouseEvent e) { if (!JBSwingUtilities.isLeftMouseButton(e) && !JBSwingUtilities.isMiddleMouseButton(e)) { return; } EditorMouseEventArea eventArea = getMouseEventArea(e); if (eventArea == EditorMouseEventArea.ANNOTATIONS_AREA) return; if (eventArea == EditorMouseEventArea.LINE_MARKERS_AREA || eventArea == EditorMouseEventArea.FOLDING_OUTLINE_AREA && !isInsideGutterWhitespaceArea(e)) { // The general idea is that we don't want to change caret position on gutter marker area click (e.g. on setting a breakpoint) // but do want to allow bulk selection on gutter marker mouse drag. However, when a drag is performed, the first event is // a 'mouse pressed' event, that's why we remember target line on 'mouse pressed' processing and use that information on // further dragging (if any). if (myDragOnGutterSelectionStartLine >= 0) { mySelectionModel.removeSelection(); myCaretModel.moveToOffset(myDragOnGutterSelectionStartLine < myDocument.getLineCount() ? myDocument.getLineStartOffset(myDragOnGutterSelectionStartLine) : myDocument.getTextLength()); } myDragOnGutterSelectionStartLine = - 1; } boolean columnSelectionDragEvent = isColumnSelectionDragEvent(e); boolean toggleCaretEvent = isToggleCaretEvent(e); boolean addRectangularSelectionEvent = isAddRectangularSelectionEvent(e); boolean columnSelectionDrag = isColumnMode() && !myLastPressCreatedCaret || columnSelectionDragEvent; if (!columnSelectionDragEvent && toggleCaretEvent && !myLastPressCreatedCaret) { return; // ignoring drag after removing a caret } Rectangle visibleArea = getScrollingModel().getVisibleArea(); int x = e.getX(); if (e.getSource() == myGutterComponent) { x = 0; } int dx = 0; if (x < visibleArea.x && visibleArea.x > 0) { dx = x - visibleArea.x; } else { if (x > visibleArea.x + visibleArea.width) { dx = x - visibleArea.x - visibleArea.width; } } int dy = 0; int y = e.getY(); if (y < visibleArea.y && visibleArea.y > 0) { dy = y - visibleArea.y; } else { if (y > visibleArea.y + visibleArea.height) { dy = y - visibleArea.y - visibleArea.height; } } if (dx == 0 && dy == 0) { myScrollingTimer.stop(); SelectionModel selectionModel = getSelectionModel(); Caret leadCaret = getLeadCaret(); int oldSelectionStart = leadCaret.getLeadSelectionOffset(); VisualPosition oldVisLeadSelectionStart = leadCaret.getLeadSelectionPosition(); int oldCaretOffset = getCaretModel().getOffset(); boolean multiCaretSelection = columnSelectionDrag || toggleCaretEvent; VisualPosition newVisualCaret = getTargetPosition(x, y, !multiCaretSelection); LogicalPosition newLogicalCaret = visualToLogicalPosition(newVisualCaret); if (multiCaretSelection) { myMultiSelectionInProgress = true; myRectangularSelectionInProgress = columnSelectionDrag || addRectangularSelectionEvent; myTargetMultiSelectionPosition = xyToVisualPosition(new Point(Math.max(x, 0), Math.max(y, 0))); } else { getCaretModel().moveToVisualPosition(newVisualCaret); } int newCaretOffset = getCaretModel().getOffset(); newVisualCaret = getCaretModel().getVisualPosition(); int caretShift = newCaretOffset - mySavedSelectionStart; if (myMousePressedEvent != null && getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.EDITING_AREA && getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.LINE_NUMBERS_AREA) { selectionModel.setSelection(oldSelectionStart, newCaretOffset); } else { if (multiCaretSelection) { if (myLastMousePressedLocation != null && (myCurrentDragIsSubstantial || !newLogicalCaret.equals(myLastMousePressedLocation))) { createSelectionTill(newLogicalCaret); blockActionsIfNeeded(e, myLastMousePressedLocation, newLogicalCaret); } } else { if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (caretShift < 0) { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretStart(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; selectionModel.setSelection(mySavedSelectionEnd, newSelection); getCaretModel().moveToOffset(newSelection); } else { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretEnd(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; selectionModel.setSelection(mySavedSelectionStart, newSelection); getCaretModel().moveToOffset(newSelection); } cancelAutoResetForMouseSelectionState(); return; } if (!myMousePressedInsideSelection) { // There is a possible case that lead selection position should be adjusted in accordance with the mouse move direction. // E.g. consider situation when user selects the whole line by clicking at 'line numbers' area. 'Line end' is considered // to be lead selection point then. However, when mouse is dragged down we want to consider 'line start' to be // lead selection point. if ((myMousePressArea == EditorMouseEventArea.LINE_NUMBERS_AREA || myMousePressArea == EditorMouseEventArea.LINE_MARKERS_AREA) && selectionModel.hasSelection()) { if (newCaretOffset >= selectionModel.getSelectionEnd()) { oldSelectionStart = selectionModel.getSelectionStart(); oldVisLeadSelectionStart = selectionModel.getSelectionStartPosition(); } else if (newCaretOffset <= selectionModel.getSelectionStart()) { oldSelectionStart = selectionModel.getSelectionEnd(); oldVisLeadSelectionStart = selectionModel.getSelectionEndPosition(); } } if (oldVisLeadSelectionStart != null) { setSelectionAndBlockActions(e, oldVisLeadSelectionStart, oldSelectionStart, newVisualCaret, newCaretOffset); } else { setSelectionAndBlockActions(e, oldSelectionStart, newCaretOffset); } cancelAutoResetForMouseSelectionState(); } else { if (caretShift != 0) { if (myMousePressedEvent != null) { if (mySettings.isDndEnabled()) { boolean isCopy = UIUtil.isControlKeyDown(e) || isViewer() || !getDocument().isWritable(); mySavedCaretOffsetForDNDUndoHack = oldCaretOffset; getContentComponent().getTransferHandler().exportAsDrag(getContentComponent(), e, isCopy ? TransferHandler.COPY : TransferHandler.MOVE); } else { selectionModel.removeSelection(); } } } } } } } else { myScrollingTimer.start(dx, dy); onSubstantialDrag(e); } } private void clearDnDContext() { if (myDraggedRange != null) { myDraggedRange.dispose(); myDraggedRange = null; } myGutterComponent.myDnDInProgress = false; } private void createSelectionTill(@NotNull LogicalPosition targetPosition) { List<CaretState> caretStates = new ArrayList<>(myCaretStateBeforeLastPress); if (myRectangularSelectionInProgress) { caretStates.addAll(EditorModificationUtil.calcBlockSelectionState(this, myLastMousePressedLocation, targetPosition)); } else { LogicalPosition selectionStart = myLastMousePressedLocation; LogicalPosition selectionEnd = targetPosition; if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { int newCaretOffset = logicalPositionToOffset(targetPosition); if (newCaretOffset < mySavedSelectionStart) { selectionStart = offsetToLogicalPosition(mySavedSelectionEnd); if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(newCaretOffset), 0)); } } else { selectionStart = offsetToLogicalPosition(mySavedSelectionStart); int selectionEndOffset = Math.max(newCaretOffset, mySavedSelectionEnd); if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { targetPosition = selectionEnd = offsetToLogicalPosition(selectionEndOffset); } else if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(selectionEndOffset) + 1, 0)); } } cancelAutoResetForMouseSelectionState(); } caretStates.add(new CaretState(targetPosition, selectionStart, selectionEnd)); } myCaretModel.setCaretsAndSelections(caretStates); } private Caret getLeadCaret() { List<Caret> allCarets = myCaretModel.getAllCarets(); Caret firstCaret = allCarets.get(0); if (firstCaret == myCaretModel.getPrimaryCaret()) { return allCarets.get(allCarets.size() - 1); } return firstCaret; } private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, int startOffset, int endOffset) { mySelectionModel.setSelection(startOffset, endOffset); if (myCurrentDragIsSubstantial || startOffset != endOffset) { onSubstantialDrag(mouseDragEvent); } } private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, VisualPosition startPosition, int startOffset, VisualPosition endPosition, int endOffset) { mySelectionModel.setSelection(startPosition, startOffset, endPosition, endOffset); if (myCurrentDragIsSubstantial || startOffset != endOffset || !Comparing.equal(startPosition, endPosition)) { onSubstantialDrag(mouseDragEvent); } } private void blockActionsIfNeeded(@NotNull MouseEvent mouseDragEvent, @NotNull LogicalPosition startPosition, @NotNull LogicalPosition endPosition) { if (myCurrentDragIsSubstantial || !startPosition.equals(endPosition)) { onSubstantialDrag(mouseDragEvent); } } private void onSubstantialDrag(@NotNull MouseEvent mouseDragEvent) { IdeEventQueue.getInstance().blockNextEvents(mouseDragEvent, IdeEventQueue.BlockMode.ACTIONS); myCurrentDragIsSubstantial = true; } private static class RepaintCursorCommand implements Runnable { private long mySleepTime = 500; private boolean myIsBlinkCaret = true; @Nullable private EditorImpl myEditor; private ScheduledFuture<?> mySchedulerHandle; public void start() { if (mySchedulerHandle != null) { mySchedulerHandle.cancel(false); } mySchedulerHandle = EdtExecutorService.getScheduledExecutorInstance().scheduleWithFixedDelay(this, mySleepTime, mySleepTime, TimeUnit.MILLISECONDS); } private void setBlinkPeriod(int blinkPeriod) { mySleepTime = blinkPeriod > 10 ? blinkPeriod : 10; start(); } private void setBlinkCaret(boolean value) { myIsBlinkCaret = value; } @Override public void run() { if (myEditor != null) { CaretCursor activeCursor = myEditor.myCaretCursor; long time = System.currentTimeMillis(); time -= activeCursor.myStartTime; if (time > mySleepTime) { boolean toRepaint = true; if (myIsBlinkCaret) { activeCursor.myIsShown = !activeCursor.myIsShown; } else { toRepaint = !activeCursor.myIsShown; activeCursor.myIsShown = true; } if (toRepaint) { activeCursor.repaint(); } } } } } void updateCaretCursor() { myUpdateCursor = true; } private void setCursorPosition() { final List<CaretRectangle> caretPoints = new ArrayList<>(); for (Caret caret : getCaretModel().getAllCarets()) { boolean isRtl = caret.isAtRtlLocation(); VisualPosition caretPosition = caret.getVisualPosition(); Point pos1 = visualPositionToXY(caretPosition.leanRight(!isRtl)); Point pos2 = visualPositionToXY(new VisualPosition(caretPosition.line, Math.max(0, caretPosition.column + (isRtl ? -1 : 1)), isRtl)); int width = Math.abs(pos2.x - pos1.x); if (!isRtl && myInlayModel.hasInlineElementAt(caretPosition)) { width = Math.min(width, myView.getPlainSpaceWidth()); } caretPoints.add(new CaretRectangle(pos1, width, caret, isRtl)); } myCaretCursor.setPositions(caretPoints.toArray(new CaretRectangle[caretPoints.size()])); } @Override public boolean setCaretVisible(boolean b) { boolean old = myCaretCursor.isActive(); if (b) { myCaretCursor.activate(); } else { myCaretCursor.passivate(); } return old; } @Override public boolean setCaretEnabled(boolean enabled) { boolean old = myCaretCursor.isEnabled(); myCaretCursor.setEnabled(enabled); return old; } @Override public void addFocusListener(@NotNull FocusChangeListener listener) { myFocusListeners.add(listener); } @Override public void addFocusListener(@NotNull FocusChangeListener listener, @NotNull Disposable parentDisposable) { ContainerUtil.add(listener, myFocusListeners, parentDisposable); } @Override @Nullable public Project getProject() { return myProject; } @Override public boolean isOneLineMode() { return myIsOneLineMode; } @Override public boolean isEmbeddedIntoDialogWrapper() { return myEmbeddedIntoDialogWrapper; } @Override public void setEmbeddedIntoDialogWrapper(boolean b) { assertIsDispatchThread(); myEmbeddedIntoDialogWrapper = b; myScrollPane.setFocusable(!b); myEditorComponent.setFocusCycleRoot(!b); myEditorComponent.setFocusable(b); } @Override public void setOneLineMode(boolean isOneLineMode) { myIsOneLineMode = isOneLineMode; getScrollPane().setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); reinitSettings(); } public static class CaretRectangle { public final Point myPoint; public final int myWidth; public final Caret myCaret; public final boolean myIsRtl; private CaretRectangle(Point point, int width, Caret caret, boolean isRtl) { myPoint = point; myWidth = Math.max(width, 2); myCaret = caret; myIsRtl = isRtl; } } class CaretCursor { private CaretRectangle[] myLocations; private boolean myEnabled; @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private boolean myIsShown; private long myStartTime; private CaretCursor() { myLocations = new CaretRectangle[] {new CaretRectangle(new Point(0, 0), 0, null, false)}; setEnabled(true); } public boolean isEnabled() { return myEnabled; } public void setEnabled(boolean enabled) { myEnabled = enabled; } private void activate() { final boolean blink = mySettings.isBlinkCaret(); final int blinkPeriod = mySettings.getCaretBlinkPeriod(); synchronized (ourCaretBlinkingCommand) { ourCaretBlinkingCommand.myEditor = EditorImpl.this; ourCaretBlinkingCommand.setBlinkCaret(blink); ourCaretBlinkingCommand.setBlinkPeriod(blinkPeriod); myIsShown = true; } } public boolean isActive() { synchronized (ourCaretBlinkingCommand) { return myIsShown; } } private void passivate() { synchronized (ourCaretBlinkingCommand) { myIsShown = false; } } private void setPositions(CaretRectangle[] locations) { myStartTime = System.currentTimeMillis(); myLocations = locations; myIsShown = true; } private void repaint() { myView.repaintCarets(); } @Nullable CaretRectangle[] getCaretLocations(boolean onlyIfShown) { if (onlyIfShown && (!isEnabled() || !myIsShown || isRendererMode() || !IJSwingUtilities.hasFocus(getContentComponent()))) return null; return myLocations; } } private class ScrollingTimer { private Timer myTimer; private static final int TIMER_PERIOD = 100; private static final int CYCLE_SIZE = 20; private int myXCycles; private int myYCycles; private int myDx; private int myDy; private int xPassedCycles; private int yPassedCycles; private void start(int dx, int dy) { myDx = 0; myDy = 0; if (dx > 0) { myXCycles = CYCLE_SIZE / dx + 1; myDx = 1 + dx / CYCLE_SIZE; } else { if (dx < 0) { myXCycles = -CYCLE_SIZE / dx + 1; myDx = -1 + dx / CYCLE_SIZE; } } if (dy > 0) { myYCycles = CYCLE_SIZE / dy + 1; myDy = 1 + dy / CYCLE_SIZE; } else { if (dy < 0) { myYCycles = -CYCLE_SIZE / dy + 1; myDy = -1 + dy / CYCLE_SIZE; } } if (myTimer != null) { return; } myTimer = UIUtil.createNamedTimer("Editor scroll timer", TIMER_PERIOD, e -> { if (isDisposed()) { stop(); return; } myCommandProcessor.executeCommand(myProject, new DocumentRunnable(myDocument, myProject) { @Override public void run() { int oldSelectionStart = mySelectionModel.getLeadSelectionOffset(); VisualPosition caretPosition = myMultiSelectionInProgress ? myTargetMultiSelectionPosition : getCaretModel().getVisualPosition(); int column = caretPosition.column; xPassedCycles++; if (xPassedCycles >= myXCycles) { xPassedCycles = 0; column += myDx; } int line = caretPosition.line; yPassedCycles++; if (yPassedCycles >= myYCycles) { yPassedCycles = 0; line += myDy; } line = Math.max(0, line); column = Math.max(0, column); VisualPosition pos = new VisualPosition(line, column); if (!myMultiSelectionInProgress) { getCaretModel().moveToVisualPosition(pos); getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } int newCaretOffset = getCaretModel().getOffset(); int caretShift = newCaretOffset - mySavedSelectionStart; if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (caretShift < 0) { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretStart(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; mySelectionModel.setSelection(validateOffset(mySavedSelectionEnd), newSelection); getCaretModel().moveToOffset(newSelection); } else { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretEnd(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset( visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; mySelectionModel.setSelection(validateOffset(mySavedSelectionStart), newSelection); getCaretModel().moveToOffset(newSelection); } return; } if (myMultiSelectionInProgress && myLastMousePressedLocation != null) { myTargetMultiSelectionPosition = pos; LogicalPosition newLogicalPosition = visualToLogicalPosition(pos); getScrollingModel().scrollTo(newLogicalPosition, ScrollType.RELATIVE); createSelectionTill(newLogicalPosition); } else { mySelectionModel.setSelection(oldSelectionStart, getCaretModel().getOffset()); } } }, EditorBundle.message("move.cursor.command.name"), DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); }); myTimer.start(); } private void stop() { if (myTimer != null) { myTimer.stop(); myTimer = null; } } private int validateOffset(int offset) { if (offset < 0) return 0; if (offset > myDocument.getTextLength()) return myDocument.getTextLength(); return offset; } } private static void updateOpaque(JScrollBar bar) { if (bar instanceof OpaqueAwareScrollBar) { bar.setOpaque(((OpaqueAwareScrollBar)bar).myOpaque); } } private class OpaqueAwareScrollBar extends JBScrollBar { private boolean myOpaque; private OpaqueAwareScrollBar(@JdkConstants.AdjustableOrientation int orientation) { super(orientation); addPropertyChangeListener("opaque", event -> { revalidate(); repaint(); }); } @Override public void setOpaque(boolean opaque) { myOpaque = opaque; super.setOpaque(opaque || shouldScrollBarBeOpaque()); } @Override public boolean isOptimizedDrawingEnabled() { return !myBackgroundImageSet; } } private static final Field decrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "decrButton"); private static final Field incrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "incrButton"); class MyScrollBar extends OpaqueAwareScrollBar { @NonNls private static final String APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS = "apple.laf.AquaScrollBarUI"; private ScrollBarUI myPersistentUI; private MyScrollBar(@JdkConstants.AdjustableOrientation int orientation) { super(orientation); } void setPersistentUI(ScrollBarUI ui) { myPersistentUI = ui; setUI(ui); } @Override public void setUI(ScrollBarUI ui) { if (myPersistentUI == null) myPersistentUI = ui; super.setUI(myPersistentUI); } /** * This is helper method. It returns height of the top (decrease) scroll bar * button. Please note, that it's possible to return real height only if scroll bar * is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) ) * value. */ int getDecScrollButtonHeight() { ScrollBarUI barUI = getUI(); Insets insets = getInsets(); int top = Math.max(0, insets.top); if (barUI instanceof ButtonlessScrollBarUI) { return top + ((ButtonlessScrollBarUI)barUI).getDecrementButtonHeight(); } if (barUI instanceof BasicScrollBarUI) { try { JButton decrButtonValue = (JButton)decrButtonField.get(barUI); LOG.assertTrue(decrButtonValue != null); return top + decrButtonValue.getHeight(); } catch (Exception exc) { throw new IllegalStateException(exc); } } return top + 15; } /** * This is helper method. It returns height of the bottom (increase) scroll bar * button. Please note, that it's possible to return real height only if scroll bar * is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) ) * value. */ int getIncScrollButtonHeight() { ScrollBarUI barUI = getUI(); Insets insets = getInsets(); if (barUI instanceof ButtonlessScrollBarUI) { return insets.top + ((ButtonlessScrollBarUI)barUI).getIncrementButtonHeight(); } if (barUI instanceof BasicScrollBarUI) { try { JButton incrButtonValue = (JButton)incrButtonField.get(barUI); LOG.assertTrue(incrButtonValue != null); return insets.bottom + incrButtonValue.getHeight(); } catch (Exception exc) { throw new IllegalStateException(exc); } } if (APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS.equals(barUI.getClass().getName())) { return insets.bottom + 30; } return insets.bottom + 15; } @Override public int getUnitIncrement(int direction) { JViewport vp = myScrollPane.getViewport(); Rectangle vr = vp.getViewRect(); return myEditorComponent.getScrollableUnitIncrement(vr, SwingConstants.VERTICAL, direction); } @Override public int getBlockIncrement(int direction) { JViewport vp = myScrollPane.getViewport(); Rectangle vr = vp.getViewRect(); return myEditorComponent.getScrollableBlockIncrement(vr, SwingConstants.VERTICAL, direction); } private void registerRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) { if (myPersistentUI instanceof ButtonlessScrollBarUI) { ((ButtonlessScrollBarUI)myPersistentUI).registerRepaintCallback(callback); } } } private MyEditable getViewer() { if (myEditable == null) { myEditable = new MyEditable(); } return myEditable; } @Override public CopyProvider getCopyProvider() { return getViewer(); } @Override public CutProvider getCutProvider() { return getViewer(); } @Override public PasteProvider getPasteProvider() { return getViewer(); } @Override public DeleteProvider getDeleteProvider() { return getViewer(); } private class MyEditable implements CutProvider, CopyProvider, PasteProvider, DeleteProvider, DumbAware { @Override public void performCopy(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_COPY, dataContext); } @Override public boolean isCopyEnabled(@NotNull DataContext dataContext) { return true; } @Override public boolean isCopyVisible(@NotNull DataContext dataContext) { return getSelectionModel().hasSelection(true); } @Override public void performCut(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_CUT, dataContext); } @Override public boolean isCutEnabled(@NotNull DataContext dataContext) { return !isViewer(); } @Override public boolean isCutVisible(@NotNull DataContext dataContext) { return isCutEnabled(dataContext) && getSelectionModel().hasSelection(true); } @Override public void performPaste(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_PASTE, dataContext); } @Override public boolean isPastePossible(@NotNull DataContext dataContext) { // Copy of isPasteEnabled. See interface method javadoc. return !isViewer(); } @Override public boolean isPasteEnabled(@NotNull DataContext dataContext) { return !isViewer(); } @Override public void deleteElement(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_DELETE, dataContext); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return !isViewer(); } private void executeAction(@NotNull String actionId, @NotNull DataContext dataContext) { EditorAction action = (EditorAction)ActionManager.getInstance().getAction(actionId); if (action != null) { action.actionPerformed(EditorImpl.this, dataContext); } } } @Override public void setColorsScheme(@NotNull EditorColorsScheme scheme) { assertIsDispatchThread(); myScheme = scheme; reinitSettings(); } @Override @NotNull public EditorColorsScheme getColorsScheme() { return myScheme; } static void assertIsDispatchThread() { ApplicationManager.getApplication().assertIsDispatchThread(); } private static void assertReadAccess() { ApplicationManager.getApplication().assertReadAccessAllowed(); } @Override public void setVerticalScrollbarOrientation(int type) { assertIsDispatchThread(); int currentHorOffset = myScrollingModel.getHorizontalScrollOffset(); myScrollBarOrientation = type; myScrollPane.putClientProperty(JBScrollPane.Flip.class, type == VERTICAL_SCROLLBAR_LEFT ? JBScrollPane.Flip.HORIZONTAL : null); myScrollingModel.scrollHorizontally(currentHorOffset); } @Override public void setVerticalScrollbarVisible(boolean b) { myScrollPane .setVerticalScrollBarPolicy(b ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); } @Override public void setHorizontalScrollbarVisible(boolean b) { myScrollPane.setHorizontalScrollBarPolicy( b ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); } @Override public int getVerticalScrollbarOrientation() { return myScrollBarOrientation; } public boolean isMirrored() { return myScrollBarOrientation != EditorEx.VERTICAL_SCROLLBAR_RIGHT; } @NotNull MyScrollBar getVerticalScrollBar() { return myVerticalScrollBar; } @MouseSelectionState private int getMouseSelectionState() { return myMouseSelectionState; } private void setMouseSelectionState(@MouseSelectionState int mouseSelectionState) { if (getMouseSelectionState() == mouseSelectionState) return; myMouseSelectionState = mouseSelectionState; myMouseSelectionChangeTimestamp = System.currentTimeMillis(); myMouseSelectionStateAlarm.cancelAllRequests(); if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE) { if (myMouseSelectionStateResetRunnable == null) { myMouseSelectionStateResetRunnable = () -> resetMouseSelectionState(null); } myMouseSelectionStateAlarm.addRequest(myMouseSelectionStateResetRunnable, Registry.intValue("editor.mouseSelectionStateResetTimeout"), ModalityState.stateForComponent(myEditorComponent)); } } private void resetMouseSelectionState(@Nullable MouseEvent event) { setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); MouseEvent e = event != null ? event : myMouseMovedEvent; if (e != null) { validateMousePointer(e); } } private void cancelAutoResetForMouseSelectionState() { myMouseSelectionStateAlarm.cancelAllRequests(); } void replaceInputMethodText(@NotNull InputMethodEvent e) { if (isReleased) return; getInputMethodRequests(); myInputMethodRequestsHandler.replaceInputMethodText(e); } void inputMethodCaretPositionChanged(@NotNull InputMethodEvent e) { if (isReleased) return; getInputMethodRequests(); myInputMethodRequestsHandler.setInputMethodCaretPosition(e); } @NotNull InputMethodRequests getInputMethodRequests() { if (myInputMethodRequestsHandler == null) { myInputMethodRequestsHandler = new MyInputMethodHandler(); myInputMethodRequestsSwingWrapper = new MyInputMethodHandleSwingThreadWrapper(myInputMethodRequestsHandler); } return myInputMethodRequestsSwingWrapper; } @Override public boolean processKeyTyped(@NotNull KeyEvent e) { if (e.getID() != KeyEvent.KEY_TYPED) return false; char c = e.getKeyChar(); if (UIUtil.isReallyTypedEvent(e)) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction processKeyTyped(c); return true; } else { return false; } } void beforeModalityStateChanged() { myScrollingModel.beforeModalityStateChanged(); } EditorDropHandler getDropHandler() { return myDropHandler; } public void setDropHandler(@NotNull EditorDropHandler dropHandler) { myDropHandler = dropHandler; } public void setHighlightingFilter(@Nullable Condition<RangeHighlighter> filter) { if (myHighlightingFilter == filter) return; Condition<RangeHighlighter> oldFilter = myHighlightingFilter; myHighlightingFilter = filter; for (RangeHighlighter highlighter : myDocumentMarkupModel.getDelegate().getAllHighlighters()) { boolean oldAvailable = oldFilter == null || oldFilter.value(highlighter); boolean newAvailable = filter == null || filter.value(highlighter); if (oldAvailable != newAvailable) { myMarkupModelListener.attributesChanged((RangeHighlighterEx)highlighter, true, EditorUtil.attributesImpactFontStyleOrColor(highlighter.getTextAttributes())); } } } boolean isHighlighterAvailable(@NotNull RangeHighlighter highlighter) { return myHighlightingFilter == null || myHighlightingFilter.value(highlighter); } private static class MyInputMethodHandleSwingThreadWrapper implements InputMethodRequests { private final InputMethodRequests myDelegate; private MyInputMethodHandleSwingThreadWrapper(InputMethodRequests delegate) { myDelegate = delegate; } @NotNull @Override public Rectangle getTextLocation(final TextHitInfo offset) { return execute(() -> myDelegate.getTextLocation(offset)); } @Override public TextHitInfo getLocationOffset(final int x, final int y) { return execute(() -> myDelegate.getLocationOffset(x, y)); } @Override public int getInsertPositionOffset() { return execute(myDelegate::getInsertPositionOffset); } @NotNull @Override public AttributedCharacterIterator getCommittedText(final int beginIndex, final int endIndex, final AttributedCharacterIterator.Attribute[] attributes) { return execute(() -> myDelegate.getCommittedText(beginIndex, endIndex, attributes)); } @Override public int getCommittedTextLength() { return execute(myDelegate::getCommittedTextLength); } @Override @Nullable public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) { return null; } @Override public AttributedCharacterIterator getSelectedText(final AttributedCharacterIterator.Attribute[] attributes) { return execute(() -> myDelegate.getSelectedText(attributes)); } private static <T> T execute(final Computable<T> computable) { return UIUtil.invokeAndWaitIfNeeded(computable); } } private class MyInputMethodHandler implements InputMethodRequests { private String composedText; private ProperTextRange composedTextRange; @NotNull @Override public Rectangle getTextLocation(TextHitInfo offset) { Point caret = logicalPositionToXY(getCaretModel().getLogicalPosition()); Rectangle r = new Rectangle(caret, new Dimension(1, getLineHeight())); Point p = getLocationOnScreen(getContentComponent()); r.translate(p.x, p.y); return r; } @Override @Nullable public TextHitInfo getLocationOffset(int x, int y) { if (composedText != null) { Point p = getLocationOnScreen(getContentComponent()); p.x = x - p.x; p.y = y - p.y; int pos = logicalPositionToOffset(xyToLogicalPosition(p)); if (composedTextRange.containsOffset(pos)) { return TextHitInfo.leading(pos - composedTextRange.getStartOffset()); } } return null; } private Point getLocationOnScreen(Component component) { Point location = new Point(); SwingUtilities.convertPointToScreen(location, component); if (LOG.isDebugEnabled() && !component.isShowing()) { Class<?> type = component.getClass(); Component parent = component.getParent(); while (parent != null && !parent.isShowing()) { type = parent.getClass(); parent = parent.getParent(); } String message = type.getName() + " is not showing"; if (parent != null) message += " on visible " + parent.getClass().getName(); LOG.debug(message); } return location; } @Override public int getInsertPositionOffset() { int composedStartIndex = 0; int composedEndIndex = 0; if (composedText != null) { composedStartIndex = composedTextRange.getStartOffset(); composedEndIndex = composedTextRange.getEndOffset(); } int caretIndex = getCaretModel().getOffset(); if (caretIndex < composedStartIndex) { return caretIndex; } if (caretIndex < composedEndIndex) { return composedStartIndex; } return caretIndex - (composedEndIndex - composedStartIndex); } private String getText(int startIdx, int endIdx) { if (startIdx >= 0 && endIdx > startIdx) { CharSequence chars = getDocument().getImmutableCharSequence(); return chars.subSequence(startIdx, endIdx).toString(); } return ""; } @NotNull @Override public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) { int composedStartIndex = 0; int composedEndIndex = 0; if (composedText != null) { composedStartIndex = composedTextRange.getStartOffset(); composedEndIndex = composedTextRange.getEndOffset(); } String committed; if (beginIndex < composedStartIndex) { if (endIndex <= composedStartIndex) { committed = getText(beginIndex, endIndex - beginIndex); } else { int firstPartLength = composedStartIndex - beginIndex; committed = getText(beginIndex, firstPartLength) + getText(composedEndIndex, endIndex - beginIndex - firstPartLength); } } else { committed = getText(beginIndex + composedEndIndex - composedStartIndex, endIndex - beginIndex); } return new AttributedString(committed).getIterator(); } @Override public int getCommittedTextLength() { int length = getDocument().getTextLength(); if (composedText != null) { length -= composedText.length(); } return length; } @Override @Nullable public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) { return null; } @Override @Nullable public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) { if (myCharKeyPressed) { myNeedToSelectPreviousChar = true; } String text = getSelectionModel().getSelectedText(); return text == null ? null : new AttributedString(text).getIterator(); } private void createComposedString(int composedIndex, @NotNull AttributedCharacterIterator text) { StringBuffer strBuf = new StringBuffer(); // create attributed string with no attributes for (char c = text.setIndex(composedIndex); c != CharacterIterator.DONE; c = text.next()) { strBuf.append(c); } composedText = new String(strBuf); } private void setInputMethodCaretPosition(@NotNull InputMethodEvent e) { if (composedText != null) { int dot = composedTextRange.getStartOffset(); TextHitInfo caretPos = e.getCaret(); if (caretPos != null) { dot += caretPos.getInsertionIndex(); } getCaretModel().moveToOffset(dot); getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } private void runUndoTransparent(@NotNull final Runnable runnable) { CommandProcessor.getInstance().runUndoTransparentAction( () -> CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(runnable), "", getDocument(), UndoConfirmationPolicy.DEFAULT, getDocument())); } private void replaceInputMethodText(@NotNull InputMethodEvent e) { if (myNeedToSelectPreviousChar && SystemInfo.isMac && (Registry.is("ide.mac.pressAndHold.brute.workaround") || Registry.is("ide.mac.pressAndHold.workaround") && (e.getCommittedCharacterCount() > 0 || e.getCaret() == null))) { // This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264). // JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants. // For our editor component we need this workaround. // After https://bugs.openjdk.java.net/browse/JDK-8074882 is fixed, this workaround should be replaced with a proper solution. myNeedToSelectPreviousChar = false; getCaretModel().runForEachCaret(caret -> { int caretOffset = caret.getOffset(); if (caretOffset > 0) { caret.setSelection(caretOffset - 1, caretOffset); } }); } int commitCount = e.getCommittedCharacterCount(); AttributedCharacterIterator text = e.getText(); // old composed text deletion final Document doc = getDocument(); if (composedText != null) { if (!isViewer() && doc.isWritable()) { runUndoTransparent(() -> { int docLength = doc.getTextLength(); ProperTextRange range = composedTextRange.intersection(new TextRange(0, docLength)); if (range != null) { doc.deleteString(range.getStartOffset(), range.getEndOffset()); } }); } composedText = null; } if (text != null) { text.first(); // committed text insertion if (commitCount > 0) { //noinspection ForLoopThatDoesntUseLoopVariable for (char c = text.current(); commitCount > 0; c = text.next(), commitCount--) { if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction processKeyTyped(c); } } } // new composed text insertion if (!isViewer() && doc.isWritable()) { int composedTextIndex = text.getIndex(); if (composedTextIndex < text.getEndIndex()) { createComposedString(composedTextIndex, text); runUndoTransparent(() -> EditorModificationUtil.insertStringAtCaret(EditorImpl.this, composedText, false, false)); composedTextRange = ProperTextRange.from(getCaretModel().getOffset(), composedText.length()); } } } } } private class MyMouseAdapter extends MouseAdapter { @Override public void mousePressed(@NotNull MouseEvent e) { requestFocus(); runMousePressedCommand(e); } @Override public void mouseReleased(@NotNull MouseEvent e) { myMousePressArea = null; myLastMousePressedLocation = null; runMouseReleasedCommand(e); if (!e.isConsumed() && myMousePressedEvent != null && !myMousePressedEvent.isConsumed() && Math.abs(e.getX() - myMousePressedEvent.getX()) < EditorUtil.getSpaceWidth(Font.PLAIN, EditorImpl.this) && Math.abs(e.getY() - myMousePressedEvent.getY()) < getLineHeight()) { runMouseClickedCommand(e); } } @Override public void mouseEntered(@NotNull MouseEvent e) { runMouseEnteredCommand(e); } @Override public void mouseExited(@NotNull MouseEvent e) { runMouseExitedCommand(e); EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) { myGutterComponent.mouseExited(e); } TooltipController.getInstance().cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true); } private void runMousePressedCommand(@NotNull final MouseEvent e) { myLastMousePressedLocation = xyToLogicalPosition(e.getPoint()); myCaretStateBeforeLastPress = isToggleCaretEvent(e) ? myCaretModel.getCaretsAndSelections() : Collections.emptyList(); myCurrentDragIsSubstantial = false; clearDnDContext(); myMousePressedEvent = e; EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); myExpectedCaretOffset = logicalPositionToOffset(myLastMousePressedLocation); try { for (EditorMouseListener mouseListener : myMouseListeners) { mouseListener.mousePressed(event); } } finally { myExpectedCaretOffset = -1; } if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA || event.getArea() == EditorMouseEventArea.FOLDING_OUTLINE_AREA && !isInsideGutterWhitespaceArea(e)) { myDragOnGutterSelectionStartLine = EditorUtil.yPositionToLogicalLine(EditorImpl.this, e); } // On some systems (for example on Linux) popup trigger is MOUSE_PRESSED event. // But this trigger is always consumed by popup handler. In that case we have to // also move caret. if (event.isConsumed() && !(event.getMouseEvent().isPopupTrigger() || event.getArea() == EditorMouseEventArea.EDITING_AREA)) { return; } if (myCommandProcessor != null) { Runnable runnable = () -> { if (processMousePressed(e) && myProject != null && !myProject.isDefault()) { IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); } }; myCommandProcessor .executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); } else { processMousePressed(e); } invokePopupIfNeeded(event); } private void runMouseClickedCommand(@NotNull final MouseEvent e) { EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); for (EditorMouseListener listener : myMouseListeners) { listener.mouseClicked(event); if (event.isConsumed()) { e.consume(); return; } } } private void runMouseReleasedCommand(@NotNull final MouseEvent e) { myMultiSelectionInProgress = false; myDragOnGutterSelectionStartLine = -1; myScrollingTimer.stop(); if (e.isConsumed()) { return; } EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); invokePopupIfNeeded(event); if (event.isConsumed()) { return; } for (EditorMouseListener listener : myMouseListeners) { listener.mouseReleased(event); if (event.isConsumed()) { e.consume(); return; } } if (myCommandProcessor != null) { Runnable runnable = () -> processMouseReleased(e); myCommandProcessor .executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); } else { processMouseReleased(e); } } private void runMouseEnteredCommand(@NotNull MouseEvent e) { EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); for (EditorMouseListener listener : myMouseListeners) { listener.mouseEntered(event); if (event.isConsumed()) { e.consume(); return; } } } private void runMouseExitedCommand(@NotNull MouseEvent e) { EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); for (EditorMouseListener listener : myMouseListeners) { listener.mouseExited(event); if (event.isConsumed()) { e.consume(); return; } } } private boolean processMousePressed(@NotNull final MouseEvent e) { myInitialMouseEvent = e; if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE && System.currentTimeMillis() - myMouseSelectionChangeTimestamp > Registry.intValue( "editor.mouseSelectionStateResetTimeout")) { resetMouseSelectionState(e); } int x = e.getX(); int y = e.getY(); if (x < 0) x = 0; if (y < 0) y = 0; final EditorMouseEventArea eventArea = getMouseEventArea(e); myMousePressArea = eventArea; if (eventArea == EditorMouseEventArea.FOLDING_OUTLINE_AREA) { final FoldRegion range = myGutterComponent.findFoldingAnchorAt(x, y); if (range != null) { final boolean expansion = !range.isExpanded(); int scrollShift = y - getScrollingModel().getVerticalScrollOffset(); Runnable processor = () -> { myFoldingModel.flushCaretShift(); range.setExpanded(expansion); if (e.isAltDown()) { for (FoldRegion region : myFoldingModel.getAllFoldRegions()) { if (region.getStartOffset() >= range.getStartOffset() && region.getEndOffset() <= range.getEndOffset()) { region.setExpanded(expansion); } } } }; getFoldingModel().runBatchFoldingOperation(processor); y = myGutterComponent.getHeadCenterY(range); getScrollingModel().scrollVertically(y - scrollShift); myGutterComponent.updateSize(); validateMousePointer(e); e.consume(); return false; } } if (e.getSource() == myGutterComponent) { if (eventArea == EditorMouseEventArea.LINE_MARKERS_AREA || eventArea == EditorMouseEventArea.ANNOTATIONS_AREA || eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA) { if (!tweakSelectionIfNecessary(e)) { myGutterComponent.mousePressed(e); } if (e.isConsumed()) return false; } x = 0; } int oldSelectionStart = mySelectionModel.getLeadSelectionOffset(); final int oldStart = mySelectionModel.getSelectionStart(); final int oldEnd = mySelectionModel.getSelectionEnd(); boolean toggleCaret = e.getSource() != myGutterComponent && isToggleCaretEvent(e); boolean lastPressCreatedCaret = myLastPressCreatedCaret; if (e.getClickCount() == 1) { myLastPressCreatedCaret = false; } // Don't move caret on mouse press above gutter line markers area (a place where break points, 'override', 'implements' etc icons // are drawn) and annotations area. E.g. we don't want to change caret position if a user sets new break point (clicks // at 'line markers' area). boolean insideEditorRelatedAreas = eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA || eventArea == EditorMouseEventArea.EDITING_AREA || isInsideGutterWhitespaceArea(e); if (insideEditorRelatedAreas) { VisualPosition visualPosition = getTargetPosition(x, y, true); LogicalPosition pos = visualToLogicalPosition(visualPosition); if (toggleCaret) { Caret caret = getCaretModel().getCaretAt(visualPosition); if (e.getClickCount() == 1) { if (caret == null) { myLastPressCreatedCaret = getCaretModel().addCaret(visualPosition) != null; } else { getCaretModel().removeCaret(caret); } } else if (e.getClickCount() == 3 && lastPressCreatedCaret) { getCaretModel().moveToVisualPosition(visualPosition); } } else if (e.getSource() != myGutterComponent && isCreateRectangularSelectionEvent(e)) { CaretState anchorCaretState = myCaretModel.getCaretsAndSelections().get(0); LogicalPosition anchor = Objects.equals(anchorCaretState.getCaretPosition(), anchorCaretState.getSelectionStart()) ? anchorCaretState.getSelectionEnd() : anchorCaretState.getSelectionStart(); if (anchor == null) anchor = myCaretModel.getLogicalPosition(); mySelectionModel.setBlockSelection(anchor, pos); } else { getCaretModel().removeSecondaryCarets(); getCaretModel().moveToVisualPosition(visualPosition); } } if (e.isPopupTrigger()) return false; requestFocus(); int caretOffset = getCaretModel().getOffset(); int newStart = mySelectionModel.getSelectionStart(); int newEnd = mySelectionModel.getSelectionEnd(); myMouseSelectedRegion = myFoldingModel.getFoldingPlaceholderAt(new Point(x, y)); myMousePressedInsideSelection = mySelectionModel.hasSelection() && caretOffset >= mySelectionModel.getSelectionStart() && caretOffset <= mySelectionModel.getSelectionEnd(); boolean isNavigation = oldStart == oldEnd && newStart == newEnd && oldStart != newStart; if (getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA && e.getClickCount() == 1) { mySelectionModel.selectLineAtCaret(); setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED); mySavedSelectionStart = mySelectionModel.getSelectionStart(); mySavedSelectionEnd = mySelectionModel.getSelectionEnd(); return isNavigation; } if (insideEditorRelatedAreas) { if (e.isShiftDown() && !e.isControlDown() && !e.isAltDown()) { if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (caretOffset < mySavedSelectionStart) { mySelectionModel.setSelection(mySavedSelectionEnd, caretOffset); } else { mySelectionModel.setSelection(mySavedSelectionStart, caretOffset); } } else { int startToUse = oldSelectionStart; if (mySelectionModel.isUnknownDirection() && caretOffset > startToUse) { startToUse = Math.min(oldStart, oldEnd); } mySelectionModel.setSelection(startToUse, caretOffset); } } else { if (!myMousePressedInsideSelection && getSelectionModel().hasSelection()) { setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); mySelectionModel.setSelection(caretOffset, caretOffset); } else { if (e.getButton() == MouseEvent.BUTTON1 && (eventArea == EditorMouseEventArea.EDITING_AREA || eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA) && (!toggleCaret || lastPressCreatedCaret)) { switch (e.getClickCount()) { case 2: selectWordAtCaret(mySettings.isMouseClickSelectionHonorsCamelWords() && mySettings.isCamelWords()); break; case 3: if (HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK && mySettings.isCamelWords()) { // We want to differentiate between triple and quadruple clicks when 'select by camel humps' is on. The former // is assumed to select 'hump' while the later points to the whole word. selectWordAtCaret(false); break; } //noinspection fallthrough case 4: mySelectionModel.selectLineAtCaret(); setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED); mySavedSelectionStart = mySelectionModel.getSelectionStart(); mySavedSelectionEnd = mySelectionModel.getSelectionEnd(); mySelectionModel.setUnknownDirection(true); break; } } } } } return isNavigation; } } private static boolean isColumnSelectionDragEvent(@NotNull MouseEvent e) { return e.isAltDown() && !e.isShiftDown() && !e.isControlDown() && !e.isMetaDown(); } private static boolean isToggleCaretEvent(@NotNull MouseEvent e) { return isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_OR_REMOVE_CARET) || isAddRectangularSelectionEvent(e); } private static boolean isAddRectangularSelectionEvent(@NotNull MouseEvent e) { return isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_RECTANGULAR_SELECTION_ON_MOUSE_DRAG); } private static boolean isCreateRectangularSelectionEvent(@NotNull MouseEvent e) { return isMouseActionEvent(e, IdeActions.ACTION_EDITOR_CREATE_RECTANGULAR_SELECTION); } private static boolean isMouseActionEvent(@NotNull MouseEvent e, String actionId) { KeymapManager keymapManager = KeymapManager.getInstance(); if (keymapManager == null) return false; Keymap keymap = keymapManager.getActiveKeymap(); if (keymap == null) return false; MouseShortcut mouseShortcut = KeymapUtil.createMouseShortcut(e); String[] mappedActions = keymap.getActionIds(mouseShortcut); if (!ArrayUtil.contains(actionId, mappedActions)) return false; if (mappedActions.length < 2) return true; ActionManager actionManager = ActionManager.getInstance(); for (String mappedActionId : mappedActions) { if (actionId.equals(mappedActionId)) continue; AnAction action = actionManager.getAction(mappedActionId); AnActionEvent actionEvent = AnActionEvent.createFromAnAction(action, e, ActionPlaces.MAIN_MENU, DataManager.getInstance().getDataContext(e.getComponent())); if (ActionUtil.lastUpdateAndCheckDumb(action, actionEvent, false)) return false; } return true; } private void selectWordAtCaret(boolean honorCamelCase) { mySelectionModel.selectWordAtCaret(honorCamelCase); setMouseSelectionState(MOUSE_SELECTION_STATE_WORD_SELECTED); mySavedSelectionStart = mySelectionModel.getSelectionStart(); mySavedSelectionEnd = mySelectionModel.getSelectionEnd(); getCaretModel().moveToOffset(mySavedSelectionEnd); } /** * Allows to answer if given event should tweak editor selection. * * @param e event for occurred mouse action * @return {@code true} if action that produces given event will trigger editor selection change; {@code false} otherwise */ private boolean tweakSelectionEvent(@NotNull MouseEvent e) { return getSelectionModel().hasSelection() && e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown() && getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA; } /** * Checks if editor selection should be changed because of click at the given point at gutter and proceeds if necessary. * <p/> * The main idea is that selection can be changed during left mouse clicks on the gutter line numbers area with hold * {@code Shift} button. The selection should be adjusted if necessary. * * @param e event for mouse click on gutter area * @return {@code true} if editor's selection is changed because of the click; {@code false} otherwise */ private boolean tweakSelectionIfNecessary(@NotNull MouseEvent e) { if (!tweakSelectionEvent(e)) { return false; } int startSelectionOffset = getSelectionModel().getSelectionStart(); int startVisLine = offsetToVisualLine(startSelectionOffset); int endSelectionOffset = getSelectionModel().getSelectionEnd(); int endVisLine = offsetToVisualLine(endSelectionOffset - 1); int clickVisLine = yToVisibleLine(e.getPoint().y); if (clickVisLine < startVisLine) { // Expand selection at backward direction. int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0))); getSelectionModel().setSelection(startOffset, endSelectionOffset); getCaretModel().moveToOffset(startOffset); } else if (clickVisLine > endVisLine) { // Expand selection at forward direction. int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine); getSelectionModel().setSelection(getSelectionModel().getSelectionStart(), endLineOffset); getCaretModel().moveToOffset(endLineOffset, true); } else if (startVisLine == endVisLine) { // Remove selection getSelectionModel().removeSelection(); } else { // Reduce selection in backward direction. if (getSelectionModel().getLeadSelectionOffset() == endSelectionOffset) { if (clickVisLine == startVisLine) { clickVisLine++; } int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0))); getSelectionModel().setSelection(startOffset, endSelectionOffset); getCaretModel().moveToOffset(startOffset); } else { // Reduce selection is forward direction. if (clickVisLine == endVisLine) { clickVisLine--; } int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine); getSelectionModel().setSelection(startSelectionOffset, endLineOffset); getCaretModel().moveToOffset(endLineOffset); } } e.consume(); return true; } boolean useEditorAntialiasing() { return myUseEditorAntialiasing; } public void setUseEditorAntialiasing(boolean value) { myUseEditorAntialiasing = value; } private static final TooltipGroup FOLDING_TOOLTIP_GROUP = new TooltipGroup("FOLDING_TOOLTIP_GROUP", 10); private class MyMouseMotionListener implements MouseMotionListener { @Override public void mouseDragged(@NotNull MouseEvent e) { if (myDraggedRange != null || myGutterComponent.myDnDInProgress) return; // on Mac we receive events even if drag-n-drop is in progress validateMousePointer(e); ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> runMouseDraggedCommand(e)); EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) { myGutterComponent.mouseDragged(e); } for (EditorMouseMotionListener listener : myMouseMotionListeners) { listener.mouseDragged(event); } } @Override public void mouseMoved(@NotNull MouseEvent e) { if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (myMousePressedEvent != null && myMousePressedEvent.getComponent() == e.getComponent()) { Point lastPoint = myMousePressedEvent.getPoint(); Point point = e.getPoint(); int deadZone = Registry.intValue("editor.mouseSelectionStateResetDeadZone"); if (Math.abs(lastPoint.x - point.x) >= deadZone || Math.abs(lastPoint.y - point.y) >= deadZone) { resetMouseSelectionState(e); } } else { validateMousePointer(e); } } else { validateMousePointer(e); } myMouseMovedEvent = e; EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (e.getSource() == myGutterComponent) { myGutterComponent.mouseMoved(e); } if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { FoldRegion fold = myFoldingModel.getFoldingPlaceholderAt(e.getPoint()); TooltipController controller = TooltipController.getInstance(); if (fold != null && !fold.shouldNeverExpand()) { DocumentFragment range = createDocumentFragment(fold); final Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getPoint(), getComponent().getRootPane().getLayeredPane()); controller.showTooltip(EditorImpl.this, p, new DocumentFragmentTooltipRenderer(range), false, FOLDING_TOOLTIP_GROUP); } else { controller.cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true); } } for (EditorMouseMotionListener listener : myMouseMotionListeners) { listener.mouseMoved(event); } } @NotNull private DocumentFragment createDocumentFragment(@NotNull FoldRegion fold) { final FoldingGroup group = fold.getGroup(); final int foldStart = fold.getStartOffset(); if (group != null) { final int endOffset = myFoldingModel.getEndOffset(group); if (offsetToVisualLine(endOffset) == offsetToVisualLine(foldStart)) { return new DocumentFragment(myDocument, foldStart, endOffset); } } final int oldEnd = fold.getEndOffset(); return new DocumentFragment(myDocument, foldStart, oldEnd); } } private class MyColorSchemeDelegate extends DelegateColorScheme { private final FontPreferencesImpl myFontPreferences = new FontPreferencesImpl(); private final FontPreferencesImpl myConsoleFontPreferences = new FontPreferencesImpl(); private final Map<TextAttributesKey, TextAttributes> myOwnAttributes = ContainerUtilRt.newHashMap(); private final Map<ColorKey, Color> myOwnColors = ContainerUtilRt.newHashMap(); private final EditorColorsScheme myCustomGlobalScheme; private Map<EditorFontType, Font> myFontsMap; private int myMaxFontSize = EditorFontsConstants.getMaxEditorFontSize(); private int myFontSize = -1; private int myConsoleFontSize = -1; private String myFaceName; private MyColorSchemeDelegate(@Nullable EditorColorsScheme globalScheme) { super(globalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : globalScheme); myCustomGlobalScheme = globalScheme; updateGlobalScheme(); } private void reinitFonts() { EditorColorsScheme delegate = getDelegate(); String editorFontName = getEditorFontName(); int editorFontSize = getEditorFontSize(); updatePreferences(myFontPreferences, editorFontName, editorFontSize, delegate == null ? null : delegate.getFontPreferences()); String consoleFontName = getConsoleFontName(); int consoleFontSize = getConsoleFontSize(); updatePreferences(myConsoleFontPreferences, consoleFontName, consoleFontSize, delegate == null ? null : delegate.getConsoleFontPreferences()); myFontsMap = new EnumMap<>(EditorFontType.class); myFontsMap.put(EditorFontType.PLAIN, new Font(editorFontName, Font.PLAIN, editorFontSize)); myFontsMap.put(EditorFontType.BOLD, new Font(editorFontName, Font.BOLD, editorFontSize)); myFontsMap.put(EditorFontType.ITALIC, new Font(editorFontName, Font.ITALIC, editorFontSize)); myFontsMap.put(EditorFontType.BOLD_ITALIC, new Font(editorFontName, Font.BOLD | Font.ITALIC, editorFontSize)); myFontsMap.put(EditorFontType.CONSOLE_PLAIN, new Font(consoleFontName, Font.PLAIN, consoleFontSize)); myFontsMap.put(EditorFontType.CONSOLE_BOLD, new Font(consoleFontName, Font.BOLD, consoleFontSize)); myFontsMap.put(EditorFontType.CONSOLE_ITALIC, new Font(consoleFontName, Font.ITALIC, consoleFontSize)); myFontsMap.put(EditorFontType.CONSOLE_BOLD_ITALIC, new Font(consoleFontName, Font.BOLD | Font.ITALIC, consoleFontSize)); } private void updatePreferences(FontPreferencesImpl preferences, String fontName, int fontSize, FontPreferences delegatePreferences) { preferences.clear(); preferences.register(fontName, fontSize); if (delegatePreferences != null) { boolean first = true; //skip delegate's primary font for (String font : delegatePreferences.getRealFontFamilies()) { if (!first) { preferences.register(font, fontSize); } first = false; } } preferences.setUseLigatures(delegatePreferences != null && delegatePreferences.useLigatures()); } private void reinitFontsAndSettings() { reinitFonts(); reinitSettings(); } @Override public TextAttributes getAttributes(TextAttributesKey key) { if (myOwnAttributes.containsKey(key)) return myOwnAttributes.get(key); return getDelegate().getAttributes(key); } @Override public void setAttributes(@NotNull TextAttributesKey key, TextAttributes attributes) { myOwnAttributes.put(key, attributes); } @Nullable @Override public Color getColor(ColorKey key) { if (myOwnColors.containsKey(key)) return myOwnColors.get(key); return getDelegate().getColor(key); } @Override public void setColor(ColorKey key, Color color) { myOwnColors.put(key, color); // These two are here because those attributes are cached and I do not whant the clients to call editor's reinit // settings in this case. myCaretModel.reinitSettings(); mySelectionModel.reinitSettings(); } @Override public int getEditorFontSize() { if (myFontSize == -1) { return getDelegate().getEditorFontSize(); } return myFontSize; } @Override public void setEditorFontSize(int fontSize) { if (fontSize < MIN_FONT_SIZE) fontSize = MIN_FONT_SIZE; if (fontSize > myMaxFontSize) fontSize = myMaxFontSize; if (fontSize == myFontSize) return; myFontSize = fontSize; reinitFontsAndSettings(); } @NotNull @Override public FontPreferences getFontPreferences() { return myFontPreferences.getEffectiveFontFamilies().isEmpty() ? getDelegate().getFontPreferences() : myFontPreferences; } @Override public void setFontPreferences(@NotNull FontPreferences preferences) { if (Comparing.equal(preferences, myFontPreferences)) return; preferences.copyTo(myFontPreferences); reinitFontsAndSettings(); } @NotNull @Override public FontPreferences getConsoleFontPreferences() { return myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty() ? getDelegate().getConsoleFontPreferences() : myConsoleFontPreferences; } @Override public void setConsoleFontPreferences(@NotNull FontPreferences preferences) { if (Comparing.equal(preferences, myConsoleFontPreferences)) return; preferences.copyTo(myConsoleFontPreferences); reinitFontsAndSettings(); } @Override public String getEditorFontName() { if (myFaceName == null) { return getDelegate().getEditorFontName(); } return myFaceName; } @Override public void setEditorFontName(String fontName) { if (Comparing.equal(fontName, myFaceName)) return; myFaceName = fontName; reinitFontsAndSettings(); } @NotNull @Override public Font getFont(EditorFontType key) { if (myFontsMap != null) { Font font = myFontsMap.get(key); if (font != null) return font; } return getDelegate().getFont(key); } @Override public void setFont(EditorFontType key, Font font) { if (myFontsMap == null) { reinitFontsAndSettings(); } myFontsMap.put(key, font); reinitSettings(); } @Override @Nullable public Object clone() { return null; } private void updateGlobalScheme() { setDelegate(myCustomGlobalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : myCustomGlobalScheme); } @Override public void setDelegate(@NotNull EditorColorsScheme delegate) { super.setDelegate(delegate); int globalFontSize = getDelegate().getEditorFontSize(); myMaxFontSize = Math.max(EditorFontsConstants.getMaxEditorFontSize(), globalFontSize); reinitFonts(); } @Override public void setConsoleFontSize(int fontSize) { myConsoleFontSize = fontSize; reinitFontsAndSettings(); } @Override public int getConsoleFontSize() { return myConsoleFontSize == -1 ? super.getConsoleFontSize() : myConsoleFontSize; } } private static class ExplosionPainter extends AbstractPainter { private final Point myExplosionLocation; private final Image myImage; private static final long TIME_PER_FRAME = 30; private final int myWidth; private final int myHeight; private long lastRepaintTime = System.currentTimeMillis(); private int frameIndex; private static final int TOTAL_FRAMES = 8; private final AtomicBoolean nrp = new AtomicBoolean(true); ExplosionPainter(final Point explosionLocation, Image image) { myExplosionLocation = new Point(explosionLocation.x, explosionLocation.y); myImage = image; myWidth = myImage.getWidth(null); myHeight = myImage.getHeight(null); } @Override public void executePaint(Component component, Graphics2D g) { if (!nrp.get()) return; long currentTimeMillis = System.currentTimeMillis(); float alpha = 1 - (float)frameIndex / TOTAL_FRAMES; g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); Image scaledImage = ImageUtil.scaleImage(myImage, alpha); int x = myExplosionLocation.x - scaledImage.getWidth(null) / 2; int y = myExplosionLocation.y - scaledImage.getHeight(null) / 2; if (currentTimeMillis - lastRepaintTime < TIME_PER_FRAME) { UIUtil.drawImage(g, scaledImage, x, y, null); JobScheduler.getScheduler().schedule(() -> component.repaint(x, y, myWidth, myHeight), TIME_PER_FRAME, TimeUnit.MILLISECONDS); return; } lastRepaintTime = currentTimeMillis; frameIndex++; UIUtil.drawImage(g, scaledImage, x, y, null); if (frameIndex == TOTAL_FRAMES) { nrp.set(false); IdeGlassPane glassPane = IdeGlassPaneUtil.find(component); ApplicationManager.getApplication().invokeLater(() -> glassPane.removePainter(this)); component.repaint(x, y, myWidth, myHeight); } component.repaint(x, y, myWidth, myHeight); } @Override public boolean needsRepaint() { return nrp.get(); } } static boolean handleDrop(@NotNull EditorImpl editor, @NotNull final Transferable t, int dropAction) { final EditorDropHandler dropHandler = editor.getDropHandler(); if (Registry.is("debugger.click.disable.breakpoints")) { try { if (t.isDataFlavorSupported(GutterDraggableObject.flavor)) { Object attachedObject = t.getTransferData(GutterDraggableObject.flavor); if (attachedObject instanceof GutterIconRenderer) { GutterDraggableObject object = ((GutterIconRenderer)attachedObject).getDraggableObject(); if (object != null) { object.remove(); Point mouseLocationOnScreen = MouseInfo.getPointerInfo().getLocation(); JComponent editorComponent = editor.getComponent(); Point editorComponentLocationOnScreen = editorComponent.getLocationOnScreen(); IdeGlassPaneUtil.installPainter( editorComponent, new ExplosionPainter( new Point( mouseLocationOnScreen.x - editorComponentLocationOnScreen.x, mouseLocationOnScreen.y - editorComponentLocationOnScreen.y ), editor.getGutterComponentEx().getDragImage((GutterIconRenderer)attachedObject) ), editor.getDisposable() ); return true; } } } } catch (UnsupportedFlavorException | IOException e) { LOG.warn(e); } } if (dropHandler != null && dropHandler.canHandleDrop(t.getTransferDataFlavors())) { dropHandler.handleDrop(t, editor.getProject(), null, dropAction); return true; } final int caretOffset = editor.getCaretModel().getOffset(); if (editor.myDraggedRange != null && editor.myDraggedRange.getStartOffset() <= caretOffset && caretOffset < editor.myDraggedRange.getEndOffset()) { return false; } if (editor.myDraggedRange != null) { editor.getCaretModel().moveToOffset(editor.mySavedCaretOffsetForDNDUndoHack); } CommandProcessor.getInstance().executeCommand(editor.myProject, () -> { try { editor.getSelectionModel().removeSelection(); final int offset; if (editor.myDraggedRange != null) { editor.getCaretModel().moveToOffset(caretOffset); offset = caretOffset; } else { offset = editor.getCaretModel().getOffset(); } if (editor.getDocument().getRangeGuard(offset, offset) != null) { return; } editor.putUserData(LAST_PASTED_REGION, null); EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE); LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler, String.valueOf(pasteHandler)); ((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), () -> t); TextRange range = editor.getUserData(LAST_PASTED_REGION); if (range != null) { editor.getCaretModel().moveToOffset(range.getStartOffset()); editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); } } catch (Exception exception) { LOG.error(exception); } }, EditorBundle.message("paste.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); return true; } private static class MyTransferHandler extends TransferHandler { private static EditorImpl getEditor(@NotNull JComponent comp) { EditorComponentImpl editorComponent = (EditorComponentImpl)comp; return editorComponent.getEditor(); } @Override public boolean importData(TransferSupport support) { Component comp = support.getComponent(); return comp instanceof JComponent && handleDrop(getEditor((JComponent)comp), support.getTransferable(), support.getDropAction()); } @Override public boolean canImport(@NotNull JComponent comp, @NotNull DataFlavor[] transferFlavors) { Editor editor = getEditor(comp); final EditorDropHandler dropHandler = ((EditorImpl)editor).getDropHandler(); if (dropHandler != null && dropHandler.canHandleDrop(transferFlavors)) { return true; } //should be used a better representation class if (Registry.is("debugger.click.disable.breakpoints") && ArrayUtil.contains(GutterDraggableObject.flavor, transferFlavors)) { return true; } if (editor.isViewer()) return false; int offset = editor.getCaretModel().getOffset(); if (editor.getDocument().getRangeGuard(offset, offset) != null) return false; return ArrayUtil.contains(DataFlavor.stringFlavor, transferFlavors); } @Override @Nullable protected Transferable createTransferable(JComponent c) { EditorImpl editor = getEditor(c); String s = editor.getSelectionModel().getSelectedText(); if (s == null) return null; int selectionStart = editor.getSelectionModel().getSelectionStart(); int selectionEnd = editor.getSelectionModel().getSelectionEnd(); editor.myDraggedRange = editor.getDocument().createRangeMarker(selectionStart, selectionEnd); return new StringSelection(s); } @Override public int getSourceActions(@NotNull JComponent c) { return COPY_OR_MOVE; } @Override protected void exportDone(@NotNull final JComponent source, @Nullable Transferable data, int action) { if (data == null) return; final Component last = DnDManager.getInstance().getLastDropHandler(); if (last != null && !(last instanceof EditorComponentImpl) && !(last instanceof EditorGutterComponentImpl)) return; final EditorImpl editor = getEditor(source); if (action == MOVE && !editor.isViewer() && editor.myDraggedRange != null) { ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> removeDraggedOutFragment(editor)); } editor.clearDnDContext(); } private static void removeDraggedOutFragment(EditorImpl editor) { if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), editor.getProject())) { return; } CommandProcessor.getInstance().executeCommand(editor.myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { Document doc = editor.getDocument(); doc.startGuardedBlockChecking(); try { doc.deleteString(editor.myDraggedRange.getStartOffset(), editor.myDraggedRange.getEndOffset()); } catch (ReadOnlyFragmentModificationException e) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e); } finally { doc.stopGuardedBlockChecking(); } }), EditorBundle.message("move.selection.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); } } private class EditorDocumentAdapter implements PrioritizedDocumentListener { @Override public void beforeDocumentChange(@NotNull DocumentEvent e) { beforeChangedUpdate(); } @Override public void documentChanged(@NotNull DocumentEvent e) { changedUpdate(e); } @Override public int getPriority() { return EditorDocumentPriorities.EDITOR_DOCUMENT_ADAPTER; } } private class EditorDocumentBulkUpdateAdapter implements DocumentBulkUpdateListener { @Override public void updateStarted(@NotNull Document doc) { if (doc != getDocument()) return; bulkUpdateStarted(); } @Override public void updateFinished(@NotNull Document doc) { if (doc != getDocument()) return; bulkUpdateFinished(); } } @Override @NotNull public EditorGutter getGutter() { return getGutterComponentEx(); } @Override public int calcColumnNumber(@NotNull CharSequence text, int start, int offset, int tabSize) { return myView.offsetToLogicalPosition(offset).column; } public boolean isInDistractionFreeMode() { return EditorUtil.isRealFileEditor(this) && (Registry.is("editor.distraction.free.mode") || isInPresentationMode()); } boolean isInPresentationMode() { return UISettings.getInstance().getPresentationMode() && EditorUtil.isRealFileEditor(this); } @Override public void putInfo(@NotNull Map<String, String> info) { final VisualPosition visual = getCaretModel().getVisualPosition(); info.put("caret", visual.getLine() + ":" + visual.getColumn()); } private void invokePopupIfNeeded(EditorMouseEvent event) { if (myContextMenuGroupId != null && event.getArea() == EditorMouseEventArea.EDITING_AREA && event.getMouseEvent().isPopupTrigger() && !event.isConsumed()) { String contextMenuGroupId = myContextMenuGroupId; Inlay inlay = myInlayModel.getElementAt(event.getMouseEvent().getPoint()); if (inlay != null) { String inlayContextMenuGroupId = inlay.getRenderer().getContextMenuGroupId(); if (inlayContextMenuGroupId != null) contextMenuGroupId = inlayContextMenuGroupId; } AnAction action = CustomActionsSchema.getInstance().getCorrectedAction(contextMenuGroupId); if (action instanceof ActionGroup) { ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.EDITOR_POPUP, (ActionGroup)action); MouseEvent e = event.getMouseEvent(); final Component c = e.getComponent(); if (c != null && c.isShowing()) { popupMenu.getComponent().show(c, e.getX(), e.getY()); } e.consume(); } } } @TestOnly void validateState() { myView.validateState(); mySoftWrapModel.validateState(); myFoldingModel.validateState(); myCaretModel.validateState(); myInlayModel.validateState(); } private class MyScrollPane extends JBScrollPane { private MyScrollPane() { super(0); setupCorners(); } @Override public void setUI(ScrollPaneUI ui) { super.setUI(ui); // disable standard Swing keybindings setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); } @Override public void layout() { if (isInDistractionFreeMode()) { // re-calc gutter extra size after editor size is set // & layout once again to avoid blinking myGutterComponent.updateSize(true, true); } super.layout(); } @Override protected void processMouseWheelEvent(@NotNull MouseWheelEvent e) { if (mySettings.isWheelFontChangeEnabled()) { if (EditorUtil.isChangeFontSize(e)) { int size = myScheme.getEditorFontSize() - e.getWheelRotation(); if (size >= MIN_FONT_SIZE) { setFontSize(size, SwingUtilities.convertPoint(this, e.getPoint(), getViewport())); } return; } } super.processMouseWheelEvent(e); } @NotNull @Override public JScrollBar createHorizontalScrollBar() { return new OpaqueAwareScrollBar(Adjustable.HORIZONTAL); } @NotNull @Override public JScrollBar createVerticalScrollBar() { return new MyScrollBar(Adjustable.VERTICAL); } @Override protected void setupCorners() { super.setupCorners(); setBorder(new TablessBorder()); } } private class TablessBorder extends SideBorder { private TablessBorder() { super(JBColor.border(), SideBorder.ALL); } @Override public void paintBorder(@NotNull Component c, @NotNull Graphics g, int x, int y, int width, int height) { if (c instanceof JComponent) { Insets insets = ((JComponent)c).getInsets(); if (insets.left > 0) { super.paintBorder(c, g, x, y, width, height); } else { g.setColor(UIUtil.getPanelBackground()); g.fillRect(x, y, width, 1); g.setColor(Gray._50.withAlpha(90)); g.fillRect(x, y, width, 1); } } } @NotNull @Override public Insets getBorderInsets(Component c) { Container splitters = SwingUtilities.getAncestorOfClass(EditorsSplitters.class, c); boolean thereIsSomethingAbove = !SystemInfo.isMac || UISettings.getInstance().getShowMainToolbar() || UISettings.getInstance().getShowNavigationBar() || toolWindowIsNotEmpty(); //noinspection ConstantConditions Component header = myHeaderPanel == null ? null : ArrayUtil.getFirstElement(myHeaderPanel.getComponents()); boolean paintTop = thereIsSomethingAbove && header == null && UISettings.getInstance().getEditorTabPlacement() != SwingConstants.TOP; return splitters == null ? super.getBorderInsets(c) : new Insets(paintTop ? 1 : 0, 0, 0, 0); } private boolean toolWindowIsNotEmpty() { if (myProject == null) return false; ToolWindowManagerEx m = ToolWindowManagerEx.getInstanceEx(myProject); return m != null && !m.getIdsOn(ToolWindowAnchor.TOP).isEmpty(); } @Override public boolean isBorderOpaque() { return true; } } private class MyHeaderPanel extends JPanel { private int myOldHeight; private MyHeaderPanel() { super(new BorderLayout()); } @Override public void revalidate() { myOldHeight = getHeight(); super.revalidate(); } @Override protected void validateTree() { int height = myOldHeight; super.validateTree(); height -= getHeight(); if (height != 0 && !(myOldHeight == 0 && getComponentCount() > 0 && getPermanentHeaderComponent() == getComponent(0))) { myVerticalScrollBar.setValue(myVerticalScrollBar.getValue() - height); } myOldHeight = getHeight(); } } private class MyTextDrawingCallback implements TextDrawingCallback { @Override public void drawChars(@NotNull Graphics g, @NotNull char[] data, int start, int end, int x, int y, Color color, @NotNull FontInfo fontInfo) { myView.drawChars(g, data, start, end, x, y, color, fontInfo); } } private static class NullEditorHighlighter extends EmptyEditorHighlighter { private static final TextAttributes NULL_ATTRIBUTES = new TextAttributes(); NullEditorHighlighter() { super(NULL_ATTRIBUTES); } @Override public void setAttributes(TextAttributes attributes) {} @Override public void setColorScheme(@NotNull EditorColorsScheme scheme) {} } }
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.editor.impl; import com.intellij.application.options.EditorFontsConstants; import com.intellij.codeInsight.hint.DocumentFragmentTooltipRenderer; import com.intellij.codeInsight.hint.EditorFragmentComponent; import com.intellij.codeInsight.hint.TooltipController; import com.intellij.codeInsight.hint.TooltipGroup; import com.intellij.concurrency.JobScheduler; import com.intellij.diagnostic.Dumpable; import com.intellij.ide.*; import com.intellij.ide.dnd.DnDManager; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.customization.CustomActionsSchema; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.TransactionGuardImpl; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.actionSystem.*; import com.intellij.openapi.editor.colors.*; import com.intellij.openapi.editor.colors.impl.DelegateColorScheme; import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.*; import com.intellij.openapi.editor.ex.util.EditorUIUtil; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterClient; import com.intellij.openapi.editor.impl.event.MarkupModelListener; import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces; import com.intellij.openapi.editor.impl.view.EditorView; import com.intellij.openapi.editor.markup.GutterDraggableObject; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.fileEditor.impl.EditorsSplitters; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.AbstractPainter; import com.intellij.openapi.ui.Queryable; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.openapi.wm.IdeGlassPaneUtil; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.impl.IdeBackgroundUtil; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.psi.PsiDocumentManager; import com.intellij.ui.*; import com.intellij.ui.components.JBLayeredPane; import com.intellij.ui.components.JBScrollBar; import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.mac.MacGestureSupportForEditor; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtil; import com.intellij.util.IJSwingUtilities; import com.intellij.util.ReflectionUtil; import com.intellij.util.concurrency.EdtExecutorService; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; import com.intellij.util.ui.*; import com.intellij.util.ui.update.Activatable; import com.intellij.util.ui.update.UiNotifyConnector; import org.intellij.lang.annotations.JdkConstants; import org.intellij.lang.annotations.MagicConstant; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.plaf.ScrollBarUI; import javax.swing.plaf.ScrollPaneUI; import javax.swing.plaf.basic.BasicScrollBarUI; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.event.*; import java.awt.font.TextHitInfo; import java.awt.geom.Point2D; import java.awt.im.InputMethodRequests; import java.awt.image.BufferedImage; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.lang.reflect.Field; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.*; import java.util.List; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public final class EditorImpl extends UserDataHolderBase implements EditorEx, HighlighterClient, Queryable, Dumpable { public static final int TEXT_ALIGNMENT_LEFT = 0; public static final int TEXT_ALIGNMENT_RIGHT = 1; private static final int MIN_FONT_SIZE = 8; private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorImpl"); private static final Key DND_COMMAND_KEY = Key.create("DndCommand"); @NonNls public static final Object IGNORE_MOUSE_TRACKING = "ignore_mouse_tracking"; private static final Key<JComponent> PERMANENT_HEADER = Key.create("PERMANENT_HEADER"); public static final Key<Boolean> DO_DOCUMENT_UPDATE_TEST = Key.create("DoDocumentUpdateTest"); public static final Key<Boolean> FORCED_SOFT_WRAPS = Key.create("forced.soft.wraps"); public static final Key<Boolean> SOFT_WRAPS_EXIST = Key.create("soft.wraps.exist"); private static final Key<Boolean> DISABLE_CARET_POSITION_KEEPING = Key.create("editor.disable.caret.position.keeping"); static final Key<Boolean> DISABLE_CARET_SHIFT_ON_WHITESPACE_INSERTION = Key.create("editor.disable.caret.shift.on.whitespace.insertion"); private static final boolean HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK = Boolean.parseBoolean(System.getProperty("idea.honor.camel.humps.on.triple.click")); private static final Key<BufferedImage> BUFFER = Key.create("buffer"); @NotNull private final DocumentEx myDocument; private final JPanel myPanel; @NotNull private final JScrollPane myScrollPane; @NotNull private final EditorComponentImpl myEditorComponent; @NotNull private final EditorGutterComponentImpl myGutterComponent; private final TraceableDisposable myTraceableDisposable = new TraceableDisposable(true); private static final Cursor EMPTY_CURSOR; static { Cursor emptyCursor = null; if (!GraphicsEnvironment.isHeadless()) { try { emptyCursor = Toolkit.getDefaultToolkit().createCustomCursor(UIUtil.createImage(1, 1, BufferedImage.TYPE_INT_ARGB), new Point(), "Empty cursor"); } catch (Exception e){ LOG.warn("Couldn't create an empty cursor", e); } } EMPTY_CURSOR = emptyCursor; } private final CommandProcessor myCommandProcessor; @NotNull private final MyScrollBar myVerticalScrollBar; private final List<EditorMouseListener> myMouseListeners = ContainerUtil.createLockFreeCopyOnWriteList(); @NotNull private final List<EditorMouseMotionListener> myMouseMotionListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private boolean myIsInsertMode = true; @NotNull private final CaretCursor myCaretCursor; private final ScrollingTimer myScrollingTimer = new ScrollingTimer(); @SuppressWarnings("RedundantStringConstructorCall") private final Object MOUSE_DRAGGED_GROUP = new String("MouseDraggedGroup"); @NotNull private final SettingsImpl mySettings; private boolean isReleased; @Nullable private MouseEvent myMousePressedEvent; @Nullable private MouseEvent myMouseMovedEvent; private final MouseListener myMouseListener = new MyMouseAdapter(); private final MouseMotionListener myMouseMotionListener = new MyMouseMotionListener(); /** * Holds information about area where mouse was pressed. */ @Nullable private EditorMouseEventArea myMousePressArea; private int mySavedSelectionStart = -1; private int mySavedSelectionEnd = -1; private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this); private MyEditable myEditable; @NotNull private EditorColorsScheme myScheme; private boolean myIsViewer; @NotNull private final SelectionModelImpl mySelectionModel; @NotNull private final EditorMarkupModelImpl myMarkupModel; @NotNull private final EditorFilteringMarkupModelEx myDocumentMarkupModel; @NotNull private final MarkupModelListener myMarkupModelListener; @NotNull private final FoldingModelImpl myFoldingModel; @NotNull private final ScrollingModelImpl myScrollingModel; @NotNull private final CaretModelImpl myCaretModel; @NotNull private final SoftWrapModelImpl mySoftWrapModel; @NotNull private final InlayModelImpl myInlayModel; @NotNull private static final RepaintCursorCommand ourCaretBlinkingCommand = new RepaintCursorCommand(); private final DocumentBulkUpdateListener myBulkUpdateListener; @MouseSelectionState private int myMouseSelectionState; @Nullable private FoldRegion myMouseSelectedRegion; private int myHorizontalTextAlignment = TEXT_ALIGNMENT_LEFT; @MagicConstant(intValues = {MOUSE_SELECTION_STATE_NONE, MOUSE_SELECTION_STATE_LINE_SELECTED, MOUSE_SELECTION_STATE_WORD_SELECTED}) private @interface MouseSelectionState {} private static final int MOUSE_SELECTION_STATE_NONE = 0; private static final int MOUSE_SELECTION_STATE_WORD_SELECTED = 1; private static final int MOUSE_SELECTION_STATE_LINE_SELECTED = 2; private volatile EditorHighlighter myHighlighter; // updated in EDT, but can be accessed from other threads (under read action) private Disposable myHighlighterDisposable = Disposer.newDisposable(); private final TextDrawingCallback myTextDrawingCallback = new MyTextDrawingCallback(); @MagicConstant(intValues = {VERTICAL_SCROLLBAR_LEFT, VERTICAL_SCROLLBAR_RIGHT}) private int myScrollBarOrientation; private boolean myMousePressedInsideSelection; private boolean myUpdateCursor; private int myCaretUpdateVShift; @Nullable private final Project myProject; private long myMouseSelectionChangeTimestamp; private int mySavedCaretOffsetForDNDUndoHack; private final List<FocusChangeListener> myFocusListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private MyInputMethodHandler myInputMethodRequestsHandler; private InputMethodRequests myInputMethodRequestsSwingWrapper; private boolean myIsOneLineMode; private boolean myIsRendererMode; private VirtualFile myVirtualFile; private boolean myIsColumnMode; @Nullable private Color myForcedBackground; @Nullable private Dimension myPreferredSize; private final Alarm myMouseSelectionStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private Runnable myMouseSelectionStateResetRunnable; private boolean myEmbeddedIntoDialogWrapper; private int myDragOnGutterSelectionStartLine = -1; private RangeMarker myDraggedRange; @NotNull private final JPanel myHeaderPanel; @Nullable private MouseEvent myInitialMouseEvent; private boolean myIgnoreMouseEventsConsecutiveToInitial; private EditorDropHandler myDropHandler; private Condition<RangeHighlighter> myHighlightingFilter; @NotNull private final IndentsModel myIndentsModel; @Nullable private CharSequence myPlaceholderText; @Nullable private TextAttributes myPlaceholderAttributes; private boolean myShowPlaceholderWhenFocused; private boolean myStickySelection; private int myStickySelectionStart; private boolean myScrollToCaret = true; private boolean myPurePaintingMode; private boolean myPaintSelection; private final EditorSizeAdjustmentStrategy mySizeAdjustmentStrategy = new EditorSizeAdjustmentStrategy(); private final Disposable myDisposable = Disposer.newDisposable(); private List<CaretState> myCaretStateBeforeLastPress; LogicalPosition myLastMousePressedLocation; private VisualPosition myTargetMultiSelectionPosition; private boolean myMultiSelectionInProgress; private boolean myRectangularSelectionInProgress; private boolean myLastPressCreatedCaret; // Set when the selection (normal or block one) initiated by mouse drag becomes noticeable (at least one character is selected). // Reset on mouse press event. private boolean myCurrentDragIsSubstantial; private CaretImpl myPrimaryCaret; public final boolean myDisableRtl = Registry.is("editor.disable.rtl"); final EditorView myView; private boolean myCharKeyPressed; private boolean myNeedToSelectPreviousChar; private boolean myDocumentChangeInProgress; private boolean myErrorStripeNeedsRepaint; private String myContextMenuGroupId = IdeActions.GROUP_BASIC_EDITOR_POPUP; private boolean myUseEditorAntialiasing = true; private final ImmediatePainter myImmediatePainter; static { ourCaretBlinkingCommand.start(); } private volatile int myExpectedCaretOffset = -1; private boolean myBackgroundImageSet; private final EditorKind myKind; private boolean myScrollingToCaret; EditorImpl(@NotNull Document document, boolean viewer, @Nullable Project project, @NotNull EditorKind kind) { assertIsDispatchThread(); myProject = project; myDocument = (DocumentEx)document; myScheme = createBoundColorSchemeDelegate(null); myScrollPane = new MyScrollPane(); // create UI after scheme initialization myIsViewer = viewer; myKind = kind; mySettings = new SettingsImpl(this, project, kind); if (!mySettings.isUseSoftWraps() && shouldSoftWrapsBeForced()) { mySettings.setUseSoftWrapsQuiet(); putUserData(FORCED_SOFT_WRAPS, Boolean.TRUE); } MarkupModelEx documentMarkup = (MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true); mySelectionModel = new SelectionModelImpl(this); myMarkupModel = new EditorMarkupModelImpl(this); myDocumentMarkupModel = new EditorFilteringMarkupModelEx(this, documentMarkup); myFoldingModel = new FoldingModelImpl(this); myCaretModel = new CaretModelImpl(this); myCaretModel.initCarets(); myScrollingModel = new ScrollingModelImpl(this); myInlayModel = new InlayModelImpl(this); Disposer.register(myCaretModel, myInlayModel); mySoftWrapModel = new SoftWrapModelImpl(this); myCommandProcessor = CommandProcessor.getInstance(); myImmediatePainter = new ImmediatePainter(this); if (myDocument instanceof DocumentImpl) { myBulkUpdateListener = new EditorDocumentBulkUpdateAdapter(); ((DocumentImpl)myDocument).addInternalBulkModeListener(myBulkUpdateListener); } else { myBulkUpdateListener = null; } myMarkupModelListener = new MarkupModelListener() { private boolean areRenderersInvolved(@NotNull RangeHighlighterEx highlighter) { return highlighter.getCustomRenderer() != null || highlighter.getGutterIconRenderer() != null || highlighter.getLineMarkerRenderer() != null || highlighter.getLineSeparatorRenderer() != null; } @Override public void afterAdded(@NotNull RangeHighlighterEx highlighter) { attributesChanged(highlighter, areRenderersInvolved(highlighter), EditorUtil.attributesImpactFontStyleOrColor(highlighter.getTextAttributes())); } @Override public void beforeRemoved(@NotNull RangeHighlighterEx highlighter) { attributesChanged(highlighter, areRenderersInvolved(highlighter), EditorUtil.attributesImpactFontStyleOrColor(highlighter.getTextAttributes())); } @Override public void attributesChanged(@NotNull RangeHighlighterEx highlighter, boolean renderersChanged, boolean fontStyleOrColorChanged) { if (myDocument.isInBulkUpdate()) return; // bulkUpdateFinished() will repaint anything if (renderersChanged) { updateGutterSize(); } boolean errorStripeNeedsRepaint = renderersChanged || highlighter.getErrorStripeMarkColor() != null; if (myDocumentChangeInProgress) { // postpone repaint request, as folding model can be in inconsistent state and so coordinate // conversions might give incorrect results myErrorStripeNeedsRepaint |= errorStripeNeedsRepaint; return; } int textLength = myDocument.getTextLength(); int start = Math.min(Math.max(highlighter.getAffectedAreaStartOffset(), 0), textLength); int end = Math.min(Math.max(highlighter.getAffectedAreaEndOffset(), 0), textLength); int startLine = start == -1 ? 0 : myDocument.getLineNumber(start); int endLine = end == -1 ? myDocument.getLineCount() : myDocument.getLineNumber(end); if (start != end && fontStyleOrColorChanged) { myView.invalidateRange(start, end); } if (!myFoldingModel.isInBatchFoldingOperation()) { // at the end of batch folding operation everything is repainted repaintLines(Math.max(0, startLine - 1), Math.min(endLine + 1, getDocument().getLineCount())); } // optimization: there is no need to repaint error stripe if the highlighter is invisible on it if (errorStripeNeedsRepaint) { if (myFoldingModel.isInBatchFoldingOperation()) { myErrorStripeNeedsRepaint = true; } else { myMarkupModel.repaint(start, end); } } updateCaretCursor(); } }; getFilteredDocumentMarkupModel().addMarkupModelListener(myCaretModel, myMarkupModelListener); getMarkupModel().addMarkupModelListener(myCaretModel, myMarkupModelListener); myDocument.addDocumentListener(myFoldingModel, myCaretModel); myDocument.addDocumentListener(myCaretModel, myCaretModel); myDocument.addDocumentListener(new EditorDocumentAdapter(), myCaretModel); myDocument.addDocumentListener(mySoftWrapModel, myCaretModel); myFoldingModel.addListener(mySoftWrapModel, myCaretModel); myInlayModel.addListener(myCaretModel, myCaretModel); myIndentsModel = new IndentsModelImpl(this); myCaretModel.addCaretListener(new CaretListener() { @Nullable private LightweightHint myCurrentHint; @Nullable private IndentGuideDescriptor myCurrentCaretGuide; @Override public void caretPositionChanged(CaretEvent e) { if (myStickySelection) { int selectionStart = Math.min(myStickySelectionStart, getDocument().getTextLength()); mySelectionModel.setSelection(selectionStart, myCaretModel.getVisualPosition(), myCaretModel.getOffset()); } final IndentGuideDescriptor newGuide = myIndentsModel.getCaretIndentGuide(); if (!Comparing.equal(myCurrentCaretGuide, newGuide)) { repaintGuide(newGuide); repaintGuide(myCurrentCaretGuide); myCurrentCaretGuide = newGuide; if (myCurrentHint != null) { myCurrentHint.hide(); myCurrentHint = null; } if (newGuide != null) { final Rectangle visibleArea = getScrollingModel().getVisibleArea(); final int line = newGuide.startLine; if (logicalLineToY(line) < visibleArea.y) { TextRange textRange = new TextRange(myDocument.getLineStartOffset(line), myDocument.getLineEndOffset(line)); myCurrentHint = EditorFragmentComponent.showEditorFragmentHint(EditorImpl.this, textRange, false, false); } } } } @Override public void caretAdded(CaretEvent e) { if (myPrimaryCaret != null) { myPrimaryCaret.updateVisualPosition(); // repainting old primary caret's row background } repaintCaretRegion(e); myPrimaryCaret = myCaretModel.getPrimaryCaret(); } @Override public void caretRemoved(CaretEvent e) { repaintCaretRegion(e); myPrimaryCaret = myCaretModel.getPrimaryCaret(); // repainting new primary caret's row background myPrimaryCaret.updateVisualPosition(); } }); myCaretCursor = new CaretCursor(); myFoldingModel.flushCaretShift(); myScrollBarOrientation = VERTICAL_SCROLLBAR_RIGHT; mySoftWrapModel.addSoftWrapChangeListener(new SoftWrapChangeListenerAdapter() { @Override public void recalculationEnds() { if (myCaretModel.isUpToDate()) { myCaretModel.updateVisualPosition(); } } }); EditorHighlighter highlighter = new NullEditorHighlighter(); setHighlighter(highlighter); myEditorComponent = new EditorComponentImpl(this); myScrollPane.putClientProperty(JBScrollPane.BRIGHTNESS_FROM_VIEW, true); myVerticalScrollBar = (MyScrollBar)myScrollPane.getVerticalScrollBar(); myVerticalScrollBar.setOpaque(false); myPanel = new JPanel(); UIUtil.putClientProperty( myPanel, UIUtil.NOT_IN_HIERARCHY_COMPONENTS, (Iterable<JComponent>)() -> { JComponent component = getPermanentHeaderComponent(); if (component != null && component.getParent() == null) { return Collections.singleton(component).iterator(); } return ContainerUtil.emptyIterator(); }); myHeaderPanel = new MyHeaderPanel(); myGutterComponent = new EditorGutterComponentImpl(this); initComponent(); myView = new EditorView(this); myView.reinitSettings(); myInlayModel.addListener(new InlayModel.SimpleAdapter() { @Override public void onUpdated(@NotNull Inlay inlay) { if (myDocument.isInEventsHandling() || myDocument.isInBulkUpdate()) return; validateSize(); repaint(inlay.getOffset(), inlay.getOffset(), false); } }, myCaretModel); if (UISettings.getInstance().getPresentationMode()) { setFontSize(UISettings.getInstance().getPresentationModeFontSize()); } myGutterComponent.updateSize(); Dimension preferredSize = getPreferredSize(); myEditorComponent.setSize(preferredSize); updateCaretCursor(); if (SystemInfo.isJavaVersionAtLeast("1.8") && SystemInfo.isMacIntel64 && SystemInfo.isJetBrainsJvm && Registry.is("ide.mac.forceTouch")) { new MacGestureSupportForEditor(getComponent()); } myScrollingModel.addVisibleAreaListener(this::moveCaretIntoViewIfCoveredByToolWindowBelow); } private void moveCaretIntoViewIfCoveredByToolWindowBelow(VisibleAreaEvent e) { Rectangle oldRectangle = e.getOldRectangle(); Rectangle newRectangle = e.getNewRectangle(); if (!myScrollingToCaret && oldRectangle != null && oldRectangle.height != newRectangle.height && oldRectangle.y == newRectangle.y && newRectangle.height > 0) { int caretY = myView.visualLineToY(myCaretModel.getVisualPosition().line); if (caretY < oldRectangle.getMaxY() && caretY > newRectangle.getMaxY()) { myScrollingToCaret = true; ApplicationManager.getApplication().invokeLater(() -> { myScrollingToCaret = false; if (!isReleased) EditorUtil.runWithAnimationDisabled(this, () -> myScrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE)); }, ModalityState.any()); } } } /** * This method is intended to control a blit-accelerated scrolling, because transparent scrollbars suppress it. * Blit-acceleration copies as much of the rendered area as possible and then repaints only newly exposed region. * It is possible to disable blit-acceleration using by the registry key {@code editor.transparent.scrollbar=true}. * Also, when there's a background image, blit-acceleration cannot be used (because of the static overlay). * In such cases this method returns {@code false} to use transparent scrollbars as designed. * Enabled blit-acceleration improves scrolling performance and reduces CPU usage * (especially if drawing is compute-intensive). * <p> * To have both the hardware acceleration and the background image * we need to completely redesign JViewport machinery to support independent layers, * which is (probably) possible, but it's a rather cumbersome task. * Smooth scrolling still works event without the blit-acceleration, * but with suboptimal performance and CPU usage. * * @return {@code true} if a scrollbar should be opaque, {@code false} otherwise */ boolean shouldScrollBarBeOpaque() { return !myBackgroundImageSet && !Registry.is("editor.transparent.scrollbar"); } public boolean shouldSoftWrapsBeForced() { if (myProject != null && PsiDocumentManager.getInstance(myProject).isDocumentBlockedByPsi(myDocument)) { // Disable checking for files in intermediate states - e.g. for files during refactoring. return false; } int lineWidthLimit = Registry.intValue("editor.soft.wrap.force.limit"); for (int i = 0; i < myDocument.getLineCount(); i++) { if (myDocument.getLineEndOffset(i) - myDocument.getLineStartOffset(i) > lineWidthLimit) { return true; } } return false; } @NotNull static Color adjustThumbColor(@NotNull Color base, boolean dark) { return dark ? ColorUtil.withAlpha(ColorUtil.shift(base, 1.35), 0.5) : ColorUtil.withAlpha(ColorUtil.shift(base, 0.68), 0.4); } boolean isDarkEnough() { return ColorUtil.isDark(getBackgroundColor()); } private void repaintCaretRegion(CaretEvent e) { CaretImpl caretImpl = (CaretImpl)e.getCaret(); if (caretImpl != null) { caretImpl.updateVisualPosition(); if (caretImpl.hasSelection()) { repaint(caretImpl.getSelectionStart(), caretImpl.getSelectionEnd(), false); } } } @NotNull @Override public EditorColorsScheme createBoundColorSchemeDelegate(@Nullable final EditorColorsScheme customGlobalScheme) { return new MyColorSchemeDelegate(customGlobalScheme); } private void repaintGuide(@Nullable IndentGuideDescriptor guide) { if (guide != null) { repaintLines(guide.startLine, guide.endLine); } } @Override public int getPrefixTextWidthInPixels() { return (int)myView.getPrefixTextWidthInPixels(); } @Override public void setPrefixTextAndAttributes(@Nullable String prefixText, @Nullable TextAttributes attributes) { mySoftWrapModel.recalculate(); myView.setPrefix(prefixText, attributes); } @Override public boolean isPurePaintingMode() { return myPurePaintingMode; } @Override public void setPurePaintingMode(boolean enabled) { myPurePaintingMode = enabled; } @Override public void registerScrollBarRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) { myVerticalScrollBar.registerRepaintCallback(callback); } @Override public int getExpectedCaretOffset() { int expectedCaretOffset = myExpectedCaretOffset; return expectedCaretOffset == -1 ? getCaretModel().getOffset() : expectedCaretOffset; } @Override public void setContextMenuGroupId(@Nullable String groupId) { myContextMenuGroupId = groupId; } @Nullable @Override public String getContextMenuGroupId() { return myContextMenuGroupId; } @Override public void setViewer(boolean isViewer) { myIsViewer = isViewer; } @Override public boolean isViewer() { return myIsViewer || myIsRendererMode; } @Override public boolean isRendererMode() { return myIsRendererMode; } @Override public void setRendererMode(boolean isRendererMode) { myIsRendererMode = isRendererMode; } @Override public void setFile(VirtualFile vFile) { myVirtualFile = vFile; reinitSettings(); } @Override public VirtualFile getVirtualFile() { return myVirtualFile; } @Override public void setSoftWrapAppliancePlace(@NotNull SoftWrapAppliancePlaces place) { mySettings.setSoftWrapAppliancePlace(place); } @Override @NotNull public SelectionModelImpl getSelectionModel() { return mySelectionModel; } @Override @NotNull public MarkupModelEx getMarkupModel() { return myMarkupModel; } @Override @NotNull public MarkupModelEx getFilteredDocumentMarkupModel() { return myDocumentMarkupModel; } @Override @NotNull public FoldingModelImpl getFoldingModel() { return myFoldingModel; } @Override @NotNull public CaretModelImpl getCaretModel() { return myCaretModel; } @Override @NotNull public ScrollingModelEx getScrollingModel() { return myScrollingModel; } @Override @NotNull public SoftWrapModelImpl getSoftWrapModel() { return mySoftWrapModel; } @NotNull @Override public InlayModelImpl getInlayModel() { return myInlayModel; } @NotNull @Override public EditorKind getEditorKind() { return myKind; } @Override @NotNull public EditorSettings getSettings() { assertReadAccess(); return mySettings; } public void resetSizes() { myView.reset(); } @Override public void reinitSettings() { assertIsDispatchThread(); for (EditorColorsScheme scheme = myScheme; scheme instanceof DelegateColorScheme; scheme = ((DelegateColorScheme)scheme).getDelegate()) { if (scheme instanceof MyColorSchemeDelegate) { ((MyColorSchemeDelegate)scheme).updateGlobalScheme(); break; } } boolean softWrapsUsedBefore = mySoftWrapModel.isSoftWrappingEnabled(); mySettings.reinitSettings(); mySoftWrapModel.reinitSettings(); myCaretModel.reinitSettings(); mySelectionModel.reinitSettings(); ourCaretBlinkingCommand.setBlinkCaret(mySettings.isBlinkCaret()); ourCaretBlinkingCommand.setBlinkPeriod(mySettings.getCaretBlinkPeriod()); myView.reinitSettings(); myFoldingModel.rebuild(); myInlayModel.reinitSettings(); if (softWrapsUsedBefore ^ mySoftWrapModel.isSoftWrappingEnabled()) { validateSize(); } myHighlighter.setColorScheme(myScheme); myFoldingModel.refreshSettings(); myGutterComponent.reinitSettings(); myGutterComponent.revalidate(); myEditorComponent.repaint(); updateCaretCursor(); if (myInitialMouseEvent != null) { myIgnoreMouseEventsConsecutiveToInitial = true; } myCaretModel.updateVisualPosition(); // make sure carets won't appear at invalid positions (e.g. on Tab width change) for (Caret caret : getCaretModel().getAllCarets()) { caret.moveToOffset(caret.getOffset()); } if (myVirtualFile != null && myProject != null) { final EditorNotifications editorNotifications = EditorNotifications.getInstance(myProject); if (editorNotifications != null) { editorNotifications.updateNotifications(myVirtualFile); } } } /** * To be called when editor was not disposed while it should */ void throwEditorNotDisposedError(@NonNls @NotNull final String msg) { myTraceableDisposable.throwObjectNotDisposedError(msg); } /** * In case of "editor not disposed error" use {@link #throwEditorNotDisposedError(String)} */ public void throwDisposalError(@NonNls @NotNull String msg) { myTraceableDisposable.throwDisposalError(msg); } // EditorFactory.releaseEditor should be used to release editor void release() { assertIsDispatchThread(); if (isReleased) { throwDisposalError("Double release of editor:"); } myTraceableDisposable.kill(null); isReleased = true; mySizeAdjustmentStrategy.cancelAllRequests(); myFoldingModel.dispose(); mySoftWrapModel.release(); myMarkupModel.dispose(); myScrollingModel.dispose(); myGutterComponent.dispose(); myMousePressedEvent = null; myMouseMovedEvent = null; Disposer.dispose(myCaretModel); Disposer.dispose(mySoftWrapModel); Disposer.dispose(myView); clearCaretThread(); myFocusListeners.clear(); myMouseListeners.clear(); myMouseMotionListeners.clear(); myEditorComponent.removeMouseListener(myMouseListener); myGutterComponent.removeMouseListener(myMouseListener); myEditorComponent.removeMouseMotionListener(myMouseMotionListener); myGutterComponent.removeMouseMotionListener(myMouseMotionListener); if (myBulkUpdateListener != null) { ((DocumentImpl)myDocument).removeInternalBulkModeListener(myBulkUpdateListener); } Disposer.dispose(myDisposable); myVerticalScrollBar.setUI(null); // clear error panel's cached image } private void clearCaretThread() { synchronized (ourCaretBlinkingCommand) { if (ourCaretBlinkingCommand.myEditor == this) { ourCaretBlinkingCommand.myEditor = null; } } } private void initComponent() { myPanel.setLayout(new BorderLayout()); myPanel.add(myHeaderPanel, BorderLayout.NORTH); myGutterComponent.setOpaque(true); myScrollPane.setViewportView(myEditorComponent); //myScrollPane.setBorder(null); myScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); myScrollPane.setRowHeaderView(myGutterComponent); myEditorComponent.setTransferHandler(new MyTransferHandler()); myEditorComponent.setAutoscrolls(true); if (mayShowToolbar()) { JLayeredPane layeredPane = new JBLayeredPane() { @Override public void doLayout() { final Component[] components = getComponents(); final Rectangle r = getBounds(); for (Component c : components) { if (c instanceof JScrollPane) { c.setBounds(0, 0, r.width, r.height); } else { final Dimension d = c.getPreferredSize(); int rightInsets = getVerticalScrollBar().getWidth() + (isMirrored() ? myGutterComponent.getWidth() : 0); c.setBounds(r.width - d.width - rightInsets - 20, 20, d.width, d.height); } } } @Override public Dimension getPreferredSize() { return myScrollPane.getPreferredSize(); } }; layeredPane.add(myScrollPane, JLayeredPane.DEFAULT_LAYER); myPanel.add(layeredPane); new ContextMenuImpl(layeredPane, myScrollPane, this); } else { myPanel.add(myScrollPane); } myEditorComponent.addKeyListener(new KeyListener() { @Override public void keyPressed(@NotNull KeyEvent e) { if (e.getKeyCode() >= KeyEvent.VK_A && e.getKeyCode() <= KeyEvent.VK_Z) { myCharKeyPressed = true; } } @Override public void keyTyped(@NotNull KeyEvent event) { myNeedToSelectPreviousChar = false; if (event.isConsumed()) { return; } if (processKeyTyped(event)) { event.consume(); } } @Override public void keyReleased(KeyEvent e) { myCharKeyPressed = false; } }); myEditorComponent.addMouseListener(myMouseListener); myGutterComponent.addMouseListener(myMouseListener); myEditorComponent.addMouseMotionListener(myMouseMotionListener); myGutterComponent.addMouseMotionListener(myMouseMotionListener); myEditorComponent.addFocusListener(new FocusAdapter() { @Override public void focusGained(@NotNull FocusEvent e) { myCaretCursor.activate(); for (Caret caret : myCaretModel.getAllCarets()) { int caretLine = caret.getLogicalPosition().line; repaintLines(caretLine, caretLine); } fireFocusGained(); } @Override public void focusLost(@NotNull FocusEvent e) { clearCaretThread(); for (Caret caret : myCaretModel.getAllCarets()) { int caretLine = caret.getLogicalPosition().line; repaintLines(caretLine, caretLine); } fireFocusLost(); } }); UiNotifyConnector connector = new UiNotifyConnector(myEditorComponent, new Activatable.Adapter() { @Override public void showNotify() { myGutterComponent.updateSizeOnShowNotify(); } }); Disposer.register(getDisposable(), connector); try { final DropTarget dropTarget = myEditorComponent.getDropTarget(); if (dropTarget != null) { // might be null in headless environment dropTarget.addDropTargetListener(new DropTargetAdapter() { @Override public void drop(@NotNull DropTargetDropEvent e) { } @Override public void dragOver(@NotNull DropTargetDragEvent e) { Point location = e.getLocation(); getCaretModel().moveToVisualPosition(getTargetPosition(location.x, location.y, true)); getScrollingModel().scrollToCaret(ScrollType.RELATIVE); requestFocus(); } }); } } catch (TooManyListenersException e) { LOG.error(e); } // update area available for soft wrapping on component shown/hidden myPanel.addHierarchyListener(e -> mySoftWrapModel.getApplianceManager().updateAvailableArea()); myPanel.addComponentListener(new ComponentAdapter() { @Override public void componentResized(@NotNull ComponentEvent e) { myMarkupModel.recalcEditorDimensions(); myMarkupModel.repaint(-1, -1); if (!isRightAligned()) return; updateCaretCursor(); myCaretCursor.repaint(); } }); } private boolean mayShowToolbar() { return !isEmbeddedIntoDialogWrapper() && !isOneLineMode() && ContextMenuImpl.mayShowToolbar(myDocument); } @Override public void setFontSize(final int fontSize) { setFontSize(fontSize, null); } /** * Changes editor font size, attempting to keep a given point unmoved. If point is not given, top left screen corner is assumed. * * @param fontSize new font size * @param zoomCenter zoom point, relative to viewport */ private void setFontSize(int fontSize, @Nullable Point zoomCenter) { int oldFontSize = myScheme.getEditorFontSize(); Rectangle visibleArea = myScrollingModel.getVisibleArea(); Point zoomCenterRelative = zoomCenter == null ? new Point() : zoomCenter; Point zoomCenterAbsolute = new Point(visibleArea.x + zoomCenterRelative.x, visibleArea.y + zoomCenterRelative.y); LogicalPosition zoomCenterLogical = xyToLogicalPosition(zoomCenterAbsolute).withoutVisualPositionInfo(); int oldLineHeight = getLineHeight(); int intraLineOffset = zoomCenterAbsolute.y % oldLineHeight; myScheme.setEditorFontSize(fontSize); fontSize = myScheme.getEditorFontSize(); // resulting font size might be different due to applied min/max limits myPropertyChangeSupport.firePropertyChange(PROP_FONT_SIZE, oldFontSize, fontSize); // Update vertical scroll bar bounds if necessary (we had a problem that use increased editor font size and it was not possible // to scroll to the bottom of the document). myScrollPane.getViewport().invalidate(); Point shiftedZoomCenterAbsolute = logicalPositionToXY(zoomCenterLogical); myScrollingModel.disableAnimation(); try { myScrollingModel.scroll(visibleArea.x == 0 ? 0 : shiftedZoomCenterAbsolute.x - zoomCenterRelative.x, // stick to left border if it's visible shiftedZoomCenterAbsolute.y - zoomCenterRelative.y + (intraLineOffset * getLineHeight() + oldLineHeight / 2) / oldLineHeight); } finally { myScrollingModel.enableAnimation(); } } public int getFontSize() { return myScheme.getEditorFontSize(); } @NotNull public ActionCallback type(@NotNull final String text) { final ActionCallback result = new ActionCallback(); for (int i = 0; i < text.length(); i++) { if (!processKeyTyped(text.charAt(i))) { result.setRejected(); return result; } } result.setDone(); return result; } private boolean processKeyTyped(char c) { // [vova] This is patch for Mac OS X. Under Mac "input methods" // is handled before our EventQueue consume upcoming KeyEvents. IdeEventQueue queue = IdeEventQueue.getInstance(); if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) { return false; } FileDocumentManager manager = FileDocumentManager.getInstance(); final VirtualFile file = manager.getFile(myDocument); if (file != null && !file.isValid()) { return false; } DataContext context = getDataContext(); Graphics graphics = GraphicsUtil.safelyGetGraphics(myEditorComponent); if (graphics != null) { // editor component is not showing processKeyTypedImmediately(c, graphics, context); graphics.dispose(); } ActionManagerEx.getInstanceEx().fireBeforeEditorTyping(c, context); EditorUIUtil.hideCursorInEditor(this); processKeyTypedNormally(c, context); return true; } void processKeyTypedImmediately(char c, Graphics graphics, DataContext dataContext) { EditorActionPlan plan = new EditorActionPlan(this); EditorActionManager.getInstance().getTypedAction().beforeActionPerformed(this, c, dataContext, plan); myImmediatePainter.paint(graphics, plan); } void processKeyTypedNormally(char c, DataContext dataContext) { EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext); } private void fireFocusLost() { for (FocusChangeListener listener : myFocusListeners) { listener.focusLost(this); } } private void fireFocusGained() { for (FocusChangeListener listener : myFocusListeners) { listener.focusGained(this); } } @Override public void setHighlighter(@NotNull final EditorHighlighter highlighter) { if (isReleased) return; // do not set highlighter to the released editor assertIsDispatchThread(); final Document document = getDocument(); Disposer.dispose(myHighlighterDisposable); document.addDocumentListener(highlighter); myHighlighterDisposable = () -> document.removeDocumentListener(highlighter); Disposer.register(myDisposable, myHighlighterDisposable); highlighter.setEditor(this); highlighter.setText(document.getImmutableCharSequence()); if (!(highlighter instanceof EmptyEditorHighlighter)) { EditorHighlighterCache.rememberEditorHighlighterForCachesOptimization(document, highlighter); } myHighlighter = highlighter; if (myPanel != null) { reinitSettings(); } } @NotNull @Override public EditorHighlighter getHighlighter() { assertReadAccess(); return myHighlighter; } @Override @NotNull public EditorComponentImpl getContentComponent() { return myEditorComponent; } @NotNull @Override public EditorGutterComponentImpl getGutterComponentEx() { return myGutterComponent; } @Override public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) { myPropertyChangeSupport.addPropertyChangeListener(listener); } @Override public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener, @NotNull Disposable parentDisposable) { addPropertyChangeListener(listener); Disposer.register(parentDisposable, () -> removePropertyChangeListener(listener)); } @Override public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) { myPropertyChangeSupport.removePropertyChangeListener(listener); } @Override public void setInsertMode(boolean mode) { assertIsDispatchThread(); boolean oldValue = myIsInsertMode; myIsInsertMode = mode; myPropertyChangeSupport.firePropertyChange(PROP_INSERT_MODE, oldValue, mode); myCaretCursor.repaint(); } @Override public boolean isInsertMode() { return myIsInsertMode; } @Override public void setColumnMode(boolean mode) { assertIsDispatchThread(); boolean oldValue = myIsColumnMode; myIsColumnMode = mode; myPropertyChangeSupport.firePropertyChange(PROP_COLUMN_MODE, oldValue, mode); } @Override public boolean isColumnMode() { return myIsColumnMode; } public int yToVisibleLine(int y) { return myView.yToVisualLine(y); } @Override @NotNull public VisualPosition xyToVisualPosition(@NotNull Point p) { return myView.xyToVisualPosition(p); } @Override @NotNull public VisualPosition xyToVisualPosition(@NotNull Point2D p) { return myView.xyToVisualPosition(p); } @Override @NotNull public Point2D offsetToPoint2D(int offset, boolean leanTowardsLargerOffsets, boolean beforeSoftWrap) { return myView.offsetToXY(offset, leanTowardsLargerOffsets, beforeSoftWrap); } @Override @NotNull public Point offsetToXY(int offset, boolean leanForward, boolean beforeSoftWrap) { Point2D point2D = offsetToPoint2D(offset, leanForward, beforeSoftWrap); return new Point((int)point2D.getX(), (int)point2D.getY()); } @Override @NotNull public VisualPosition offsetToVisualPosition(int offset) { return offsetToVisualPosition(offset, false, false); } @Override @NotNull public VisualPosition offsetToVisualPosition(int offset, boolean leanForward, boolean beforeSoftWrap) { return myView.offsetToVisualPosition(offset, leanForward, beforeSoftWrap); } @Override @NotNull public LogicalPosition offsetToLogicalPosition(int offset) { return myView.offsetToLogicalPosition(offset); } @TestOnly public void setCaretActive() { synchronized (ourCaretBlinkingCommand) { ourCaretBlinkingCommand.myEditor = this; } } // optimization: do not do column calculations here since we are interested in line number only int offsetToVisualLine(int offset) { return myView.offsetToVisualLine(offset, false); } public int visualLineStartOffset(int visualLine) { return myView.visualLineToOffset(visualLine); } @Override @NotNull public LogicalPosition xyToLogicalPosition(@NotNull Point p) { Point pp = p.x >= 0 && p.y >= 0 ? p : new Point(Math.max(p.x, 0), Math.max(p.y, 0)); return visualToLogicalPosition(xyToVisualPosition(pp)); } private int logicalLineToY(int line) { int visualLine = line < myDocument.getLineCount() ? offsetToVisualLine(myDocument.getLineStartOffset(line)) : logicalToVisualPosition(new LogicalPosition(line, 0)).line; return visibleLineToY(visualLine); } @Override @NotNull public Point logicalPositionToXY(@NotNull LogicalPosition pos) { VisualPosition visible = logicalToVisualPosition(pos); return visualPositionToXY(visible); } @Override @NotNull public Point visualPositionToXY(@NotNull VisualPosition visible) { Point2D point2D = myView.visualPositionToXY(visible); return new Point((int)point2D.getX(), (int)point2D.getY()); } @Override @NotNull public Point2D visualPositionToPoint2D(@NotNull VisualPosition visible) { return myView.visualPositionToXY(visible); } /** * Returns how much current line height bigger than the normal (16px) * This method is used to scale editors elements such as gutter icons, folding elements, and others */ public float getScale() { if (!Registry.is("editor.scale.gutter.icons")) return 1f; float normLineHeight = getLineHeight() / myScheme.getLineSpacing(); // normalized, as for 1.0f line spacing return normLineHeight / JBUI.scale(16f); } public int findNearestDirectionBoundary(int offset, boolean lookForward) { return myView.findNearestDirectionBoundary(offset, lookForward); } public int visibleLineToY(int line) { return myView.visualLineToY(line); } @Override public void repaint(int startOffset, int endOffset) { repaint(startOffset, endOffset, true); } void repaint(int startOffset, int endOffset, boolean invalidateTextLayout) { if (myDocument.isInBulkUpdate()) { return; } assertIsDispatchThread(); endOffset = Math.min(endOffset, myDocument.getTextLength()); if (invalidateTextLayout) { myView.invalidateRange(startOffset, endOffset); } if (!isShowing()) { return; } // We do repaint in case of equal offsets because there is a possible case that there is a soft wrap at the same offset and // it does occupy particular amount of visual space that may be necessary to repaint. if (startOffset <= endOffset) { int startLine = myDocument.getLineNumber(startOffset); int endLine = myDocument.getLineNumber(endOffset); repaintLines(startLine, endLine); } } private boolean isShowing() { return myGutterComponent.isShowing(); } private void repaintToScreenBottom(int startLine) { Rectangle visibleArea = getScrollingModel().getVisibleArea(); int yStartLine = logicalLineToY(startLine); int yEndLine = visibleArea.y + visibleArea.height; myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, yEndLine - yStartLine); myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), yEndLine - yStartLine); ((EditorMarkupModelImpl)getMarkupModel()).repaint(-1, -1); } /** * Asks to repaint all logical lines from the given {@code [start; end]} range. * * @param startLine start logical line to repaint (inclusive) * @param endLine end logical line to repaint (inclusive) */ private void repaintLines(int startLine, int endLine) { if (!isShowing()) return; Rectangle visibleArea = getScrollingModel().getVisibleArea(); int yStartLine = logicalLineToY(startLine); int endVisLine = myDocument.getTextLength() <= 0 ? 0 : offsetToVisualLine(myDocument.getLineEndOffset(Math.min(myDocument.getLineCount() - 1, endLine))); int height = endVisLine * getLineHeight() - yStartLine + getLineHeight() + 2; myEditorComponent.repaintEditorComponent(visibleArea.x, yStartLine, visibleArea.x + visibleArea.width, height); myGutterComponent.repaint(0, yStartLine, myGutterComponent.getWidth(), height); } private void bulkUpdateStarted() { myView.getPreferredSize(); // make sure size is calculated (in case it will be required while bulk mode is active) myScrollingModel.onBulkDocumentUpdateStarted(); saveCaretRelativePosition(); myCaretModel.onBulkDocumentUpdateStarted(); mySoftWrapModel.onBulkDocumentUpdateStarted(); myFoldingModel.onBulkDocumentUpdateStarted(); } private void bulkUpdateFinished() { myFoldingModel.onBulkDocumentUpdateFinished(); mySoftWrapModel.onBulkDocumentUpdateFinished(); myView.reset(); myCaretModel.onBulkDocumentUpdateFinished(); setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); validateSize(); updateGutterSize(); repaintToScreenBottom(0); updateCaretCursor(); if (!Boolean.TRUE.equals(getUserData(DISABLE_CARET_POSITION_KEEPING))) { restoreCaretRelativePosition(); } } private void beforeChangedUpdate() { ApplicationManager.getApplication().assertIsDispatchThread(); myDocumentChangeInProgress = true; if (isStickySelection()) { setStickySelection(false); } if (myDocument.isInBulkUpdate()) { // Assuming that the job is done at bulk listener callback methods. return; } saveCaretRelativePosition(); } void invokeDelayedErrorStripeRepaint() { if (myErrorStripeNeedsRepaint) { myMarkupModel.repaint(-1, -1); myErrorStripeNeedsRepaint = false; } } private void changedUpdate(DocumentEvent e) { myDocumentChangeInProgress = false; if (myDocument.isInBulkUpdate()) return; if (myErrorStripeNeedsRepaint) { myMarkupModel.repaint(e.getOffset(), e.getOffset() + e.getNewLength()); myErrorStripeNeedsRepaint = false; } setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); validateSize(); int startLine = offsetToLogicalLine(e.getOffset()); int endLine = offsetToLogicalLine(e.getOffset() + e.getNewLength()); boolean painted = false; if (myDocument.getTextLength() > 0) { if (startLine != endLine || StringUtil.indexOf(e.getOldFragment(), '\n') != -1) { myGutterComponent.clearLineToGutterRenderersCache(); } if (countLineFeeds(e.getOldFragment()) != countLineFeeds(e.getNewFragment())) { // Lines removed. Need to repaint till the end of the screen repaintToScreenBottom(startLine); painted = true; } } updateCaretCursor(); if (!painted) { repaintLines(startLine, endLine); } if (!Boolean.TRUE.equals(getUserData(DISABLE_CARET_POSITION_KEEPING)) && (getCaretModel().getOffset() < e.getOffset() || getCaretModel().getOffset() > e.getOffset() + e.getNewLength())) { restoreCaretRelativePosition(); } } public void hideCursor() { if (!myIsViewer && Registry.is("ide.hide.cursor.when.typing") && EMPTY_CURSOR != null && EMPTY_CURSOR != myEditorComponent.getCursor()) { myEditorComponent.setCursor(EMPTY_CURSOR); } } private void saveCaretRelativePosition() { Rectangle visibleArea = getScrollingModel().getVisibleArea(); Point pos = visualPositionToXY(getCaretModel().getVisualPosition()); myCaretUpdateVShift = pos.y - visibleArea.y; } private void restoreCaretRelativePosition() { Point caretLocation = visualPositionToXY(getCaretModel().getVisualPosition()); int scrollOffset = caretLocation.y - myCaretUpdateVShift; getScrollingModel().disableAnimation(); getScrollingModel().scrollVertically(scrollOffset); getScrollingModel().enableAnimation(); } public boolean isScrollToCaret() { return myScrollToCaret; } public void setScrollToCaret(boolean scrollToCaret) { myScrollToCaret = scrollToCaret; } @NotNull public Disposable getDisposable() { return myDisposable; } private static int countLineFeeds(@NotNull CharSequence c) { return StringUtil.countNewLines(c); } private boolean updatingSize; // accessed from EDT only private void updateGutterSize() { assertIsDispatchThread(); if (!updatingSize) { updatingSize = true; ApplicationManager.getApplication().invokeLater(() -> { try { if (!isDisposed()) { myGutterComponent.updateSize(); } } finally { updatingSize = false; } }, ModalityState.any(), __->isDisposed()); } } void validateSize() { if (isReleased) return; Dimension dim = getPreferredSize(); if (!dim.equals(myPreferredSize) && !myDocument.isInBulkUpdate()) { dim = mySizeAdjustmentStrategy.adjust(dim, myPreferredSize, this); if (!dim.equals(myPreferredSize)) { myPreferredSize = dim; updateGutterSize(); myEditorComponent.setSize(dim); myEditorComponent.fireResized(); myMarkupModel.recalcEditorDimensions(); myMarkupModel.repaint(-1, -1); } } } void recalculateSizeAndRepaint() { validateSize(); myEditorComponent.repaintEditorComponent(); } @Override @NotNull public DocumentEx getDocument() { return myDocument; } @Override @NotNull public JComponent getComponent() { return myPanel; } @Override public void addEditorMouseListener(@NotNull EditorMouseListener listener) { myMouseListeners.add(listener); } @Override public void removeEditorMouseListener(@NotNull EditorMouseListener listener) { boolean success = myMouseListeners.remove(listener); LOG.assertTrue(success || isReleased); } @Override public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { myMouseMotionListeners.add(listener); } @Override public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { boolean success = myMouseMotionListeners.remove(listener); LOG.assertTrue(success || isReleased); } @Override public boolean isStickySelection() { return myStickySelection; } @Override public void setStickySelection(boolean enable) { myStickySelection = enable; if (enable) { myStickySelectionStart = getCaretModel().getOffset(); } else { mySelectionModel.removeSelection(); } } public void setHorizontalTextAlignment(@MagicConstant(intValues = {TEXT_ALIGNMENT_LEFT, TEXT_ALIGNMENT_RIGHT}) int alignment) { myHorizontalTextAlignment = alignment; } public boolean isRightAligned() { return myHorizontalTextAlignment == TEXT_ALIGNMENT_RIGHT; } @Override public boolean isDisposed() { return isReleased; } public void stopDumbLater() { if (ApplicationManager.getApplication().isUnitTestMode()) return; ApplicationManager.getApplication().invokeLater(this::stopDumb, ModalityState.current(), __ -> isDisposed()); } private void stopDumb() { putUserData(BUFFER, null); } /** * {@link #stopDumbLater} or {@link #stopDumb} must be performed in finally */ public void startDumb() { if (ApplicationManager.getApplication().isUnitTestMode()) return; if (!Registry.is("editor.dumb.mode.available")) return; putUserData(BUFFER, null); Rectangle rect = ((JViewport)myEditorComponent.getParent()).getViewRect(); // The LCD text loop is enabled only for opaque images BufferedImage image = UIUtil.createImage(myEditorComponent, rect.width, rect.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = JBSwingUtilities.runGlobalCGTransform(myEditorComponent, image.createGraphics()); graphics.translate(-rect.x, -rect.y); graphics.setClip(rect.x, rect.y, rect.width, rect.height); myEditorComponent.paintComponent(graphics); graphics.dispose(); putUserData(BUFFER, image); } public boolean isDumb() { return getUserData(BUFFER) != null; } void paint(@NotNull Graphics2D g) { Rectangle clip = g.getClipBounds(); if (clip == null) { return; } BufferedImage buffer = Registry.is("editor.dumb.mode.available") ? getUserData(BUFFER) : null; if (buffer != null) { Rectangle rect = getContentComponent().getVisibleRect(); UIUtil.drawImage(g, buffer, null, rect.x, rect.y); return; } if (isReleased) { g.setColor(getDisposedBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); return; } if (myUpdateCursor) { setCursorPosition(); myUpdateCursor = false; } if (myProject != null && myProject.isDisposed()) return; myView.paint(g); boolean isBackgroundImageSet = IdeBackgroundUtil.isEditorBackgroundImageSet(myProject); if (myBackgroundImageSet != isBackgroundImageSet) { myBackgroundImageSet = isBackgroundImageSet; updateOpaque(myScrollPane.getHorizontalScrollBar()); updateOpaque(myScrollPane.getVerticalScrollBar()); } } Color getDisposedBackground() { return new JBColor(new Color(128, 255, 128), new Color(128, 255, 128)); } @NotNull @Override public IndentsModel getIndentsModel() { return myIndentsModel; } @Override public void setHeaderComponent(JComponent header) { myHeaderPanel.removeAll(); header = header == null ? getPermanentHeaderComponent() : header; if (header != null) { myHeaderPanel.add(header); } myHeaderPanel.revalidate(); myHeaderPanel.repaint(); } @Override public boolean hasHeaderComponent() { JComponent header = getHeaderComponent(); return header != null && header != getPermanentHeaderComponent(); } @Override @Nullable public JComponent getPermanentHeaderComponent() { return getUserData(PERMANENT_HEADER); } @Override public void setPermanentHeaderComponent(@Nullable JComponent component) { putUserData(PERMANENT_HEADER, component); } @Override @Nullable public JComponent getHeaderComponent() { if (myHeaderPanel.getComponentCount() > 0) { return (JComponent)myHeaderPanel.getComponent(0); } return null; } @Override public void setBackgroundColor(Color color) { myScrollPane.setBackground(color); if (getBackgroundIgnoreForced().equals(color)) { myForcedBackground = null; return; } myForcedBackground = color; } @NotNull Color getForegroundColor() { return myScheme.getDefaultForeground(); } @NotNull @Override public Color getBackgroundColor() { if (myForcedBackground != null) return myForcedBackground; return getBackgroundIgnoreForced(); } @NotNull @Override public TextDrawingCallback getTextDrawingCallback() { return myTextDrawingCallback; } @Override public void setPlaceholder(@Nullable CharSequence text) { myPlaceholderText = text; } @Override public void setPlaceholderAttributes(@Nullable TextAttributes attributes) { myPlaceholderAttributes = attributes; } public TextAttributes getPlaceholderAttributes() { return myPlaceholderAttributes; } public CharSequence getPlaceholder() { return myPlaceholderText; } @Override public void setShowPlaceholderWhenFocused(boolean show) { myShowPlaceholderWhenFocused = show; } public boolean getShowPlaceholderWhenFocused() { return myShowPlaceholderWhenFocused; } Color getBackgroundColor(@NotNull final TextAttributes attributes) { final Color attrColor = attributes.getBackgroundColor(); return Comparing.equal(attrColor, myScheme.getDefaultBackground()) ? getBackgroundColor() : attrColor; } @NotNull private Color getBackgroundIgnoreForced() { Color color = myScheme.getDefaultBackground(); if (myDocument.isWritable()) { return color; } Color readOnlyColor = myScheme.getColor(EditorColors.READONLY_BACKGROUND_COLOR); return readOnlyColor != null ? readOnlyColor : color; } @Nullable public TextRange getComposedTextRange() { return myInputMethodRequestsHandler == null || myInputMethodRequestsHandler.composedText == null ? null : myInputMethodRequestsHandler.composedTextRange; } @Override public int getMaxWidthInRange(int startOffset, int endOffset) { return myView.getMaxWidthInRange(startOffset, endOffset); } public boolean isPaintSelection() { return myPaintSelection || !isOneLineMode() || IJSwingUtilities.hasFocus(getContentComponent()); } public void setPaintSelection(boolean paintSelection) { myPaintSelection = paintSelection; } @Override @NotNull @NonNls public String dumpState() { return "allow caret inside tab: " + mySettings.isCaretInsideTabs() + ", allow caret after line end: " + mySettings.isVirtualSpace() + ", soft wraps: " + (mySoftWrapModel.isSoftWrappingEnabled() ? "on" : "off") + ", caret model: " + getCaretModel().dumpState() + ", soft wraps data: " + getSoftWrapModel().dumpState() + "\n\nfolding data: " + getFoldingModel().dumpState() + (myDocument instanceof DocumentImpl ? "\n\ndocument info: " + ((DocumentImpl)myDocument).dumpState() : "") + "\nfont preferences: " + myScheme.getFontPreferences() + "\npure painting mode: " + myPurePaintingMode + "\ninsets: " + myEditorComponent.getInsets() + (myView == null ? "" : "\nview: " + myView.dumpState()); } @Nullable public CaretRectangle[] getCaretLocations(boolean onlyIfShown) { return myCaretCursor.getCaretLocations(onlyIfShown); } public int getAscent() { return myView.getAscent(); } @Override public int getLineHeight() { return myView.getLineHeight(); } public int getDescent() { return myView.getDescent(); } public int getCharHeight() { return myView.getCharHeight(); } @NotNull public FontMetrics getFontMetrics(@JdkConstants.FontStyle int fontType) { EditorFontType ft; if (fontType == Font.PLAIN) ft = EditorFontType.PLAIN; else if (fontType == Font.BOLD) ft = EditorFontType.BOLD; else if (fontType == Font.ITALIC) ft = EditorFontType.ITALIC; else if (fontType == (Font.BOLD | Font.ITALIC)) ft = EditorFontType.BOLD_ITALIC; else { LOG.error("Unknown font type: " + fontType); ft = EditorFontType.PLAIN; } return myEditorComponent.getFontMetrics(myScheme.getFont(ft)); } public int getPreferredHeight() { return isReleased ? 0 : myView.getPreferredHeight(); } public Dimension getPreferredSize() { return isReleased ? new Dimension() : Registry.is("idea.true.smooth.scrolling.dynamic.scrollbars") ? new Dimension(getPreferredWidthOfVisibleLines(), myView.getPreferredHeight()) : myView.getPreferredSize(); } /* When idea.true.smooth.scrolling=true, this method is used to compute width of currently visible line range rather than width of the whole document. As transparent scrollbars, by definition, prevent blit-acceleration of scrolling, and we really need blit-acceleration because not all hardware can render pixel-by-pixel scrolling with acceptable FPS without it (we now have 4K-5K displays, you know). To have both the hardware acceleration and the transparent scrollbars we need to completely redesign JViewport machinery to support independent layers, which is (probably) possible, but it's a rather cumbersome task. Another approach is to make scrollbars opaque, but only in the editor (as editor is a slow-to-draw component with large screen area). This is what "true smooth scrolling" option currently does. Interestingly, making the vertical scrollbar opaque might actually be a good thing because on modern displays (size, aspect ratio) code rarely extends beyond the right screen edge, and even when it does, its mixing with the navigation bar only reduces intelligibility of both the navigation bar and the code itself. Horizontal scrollbar is another story - a single long line of text forces horizontal scrollbar in the whole document, and in that case "transparent" scrollbar has some merits. However, instead of using transparency, we can hide horizontal scrollbar altogether when it's not needed for currently visible content. In a sense, this approach is superior, as even "transparent" scrollbar is only semi-transparent (thus we may prefer "on-demand" scrollbar in the general case). Hiding the horizontal scrollbar also solves another issue - when both scrollbars are visible, vertical scrolling with a high-precision touchpad can result in unintentional horizontal shifts (because of the touchpad sensitivity). When visible content fully fits horizontally (i.e. in most cases), hiding the unneeded scrollbar reliably prevents the horizontal "jitter". Keep in mind that this functionality is experimental and may need more polishing. In principle, we can apply this method to other components by defining, for example, VariableWidth interface and supporting it in JBScrollPane. */ private int getPreferredWidthOfVisibleLines() { Rectangle area = getScrollingModel().getVisibleArea(); VisualPosition begin = xyToVisualPosition(area.getLocation()); VisualPosition end = xyToVisualPosition(new Point(area.x + area.width, area.y + area.height)); return Math.max(myView.getPreferredWidth(begin.line, end.line), getScrollingWidth()); } /* Returns the width of current horizontal scrolling state. Complements the getPreferredWidthOfVisibleLines() method to allows to retain horizontal scrolling position that is beyond the width of currently visible lines. */ private int getScrollingWidth() { JScrollBar scrollbar = myScrollPane.getHorizontalScrollBar(); if (scrollbar != null) { BoundedRangeModel model = scrollbar.getModel(); if (model != null) { return model.getValue() + model.getExtent(); } } return 0; } @NotNull @Override public Dimension getContentSize() { return myView.getPreferredSize(); } @NotNull @Override public JScrollPane getScrollPane() { return myScrollPane; } @Override public void setBorder(Border border) { myScrollPane.setBorder(border); } @Override public Insets getInsets() { return myScrollPane.getInsets(); } @Override public int logicalPositionToOffset(@NotNull LogicalPosition pos) { return myView.logicalPositionToOffset(pos); } /** * @return information about total number of lines that can be viewed by user. I.e. this is a number of all document * lines (considering that single logical document line may be represented on multiple visual lines because of * soft wraps appliance) minus number of folded lines */ public int getVisibleLineCount() { return getVisibleLogicalLinesCount() + getSoftWrapModel().getSoftWrapsIntroducedLinesNumber(); } /** * @return number of visible logical lines. Generally, that is a total logical lines number minus number of folded lines */ private int getVisibleLogicalLinesCount() { return getDocument().getLineCount() - myFoldingModel.getTotalNumberOfFoldedLines(); } @Override @NotNull public VisualPosition logicalToVisualPosition(@NotNull LogicalPosition logicalPos) { return myView.logicalToVisualPosition(logicalPos, false); } @Override @NotNull public LogicalPosition visualToLogicalPosition(@NotNull VisualPosition visiblePos) { return myView.visualToLogicalPosition(visiblePos); } private int offsetToLogicalLine(int offset) { int textLength = myDocument.getTextLength(); if (textLength == 0) return 0; if (offset > textLength || offset < 0) { throw new IndexOutOfBoundsException("Wrong offset: " + offset + " textLength: " + textLength); } int lineIndex = myDocument.getLineNumber(offset); LOG.assertTrue(lineIndex >= 0 && lineIndex < myDocument.getLineCount()); return lineIndex; } @Override public int calcColumnNumber(int offset, int lineIndex) { return myView.offsetToLogicalPosition(offset).column; } private VisualPosition getTargetPosition(int x, int y, boolean trimToLineWidth) { if (myDocument.getLineCount() == 0) { return new VisualPosition(0, 0); } if (x < 0) { x = 0; } if (y < 0) { y = 0; } int visualLineCount = getVisibleLineCount(); if (yToVisibleLine(y) >= visualLineCount) { y = visibleLineToY(Math.max(0, visualLineCount - 1)); } VisualPosition visualPosition = xyToVisualPosition(new Point(x, y)); if (trimToLineWidth && !mySettings.isVirtualSpace()) { LogicalPosition logicalPosition = visualToLogicalPosition(visualPosition); LogicalPosition lineEndPosition = offsetToLogicalPosition(myDocument.getLineEndOffset(logicalPosition.line)); if (logicalPosition.column > lineEndPosition.column) { visualPosition = logicalToVisualPosition(lineEndPosition.leanForward(true)); } else if (mySoftWrapModel.isInsideSoftWrap(visualPosition)) { VisualPosition beforeSoftWrapPosition = myView.logicalToVisualPosition(logicalPosition, true); if (visualPosition.line == beforeSoftWrapPosition.line) { visualPosition = beforeSoftWrapPosition; } else { visualPosition = myView.logicalToVisualPosition(logicalPosition, false); } } } return visualPosition; } private boolean checkIgnore(@NotNull MouseEvent e) { if (!myIgnoreMouseEventsConsecutiveToInitial) { myInitialMouseEvent = null; return false; } if (myInitialMouseEvent!= null && (e.getComponent() != myInitialMouseEvent.getComponent() || !e.getPoint().equals(myInitialMouseEvent.getPoint()))) { myIgnoreMouseEventsConsecutiveToInitial = false; myInitialMouseEvent = null; return false; } myIgnoreMouseEventsConsecutiveToInitial = false; myInitialMouseEvent = null; e.consume(); return true; } private void processMouseReleased(@NotNull MouseEvent e) { if (checkIgnore(e)) return; if (e.getSource() == myGutterComponent && !(myMousePressedEvent != null && myMousePressedEvent.isConsumed())) { myGutterComponent.mouseReleased(e); } if (getMouseEventArea(e) != EditorMouseEventArea.EDITING_AREA || e.getY() < 0 || e.getX() < 0) { return; } // if (myMousePressedInsideSelection) getSelectionModel().removeSelection(); final FoldRegion region = getFoldingModel().getFoldingPlaceholderAt(e.getPoint()); if (e.getX() >= 0 && e.getY() >= 0 && region != null && region == myMouseSelectedRegion) { getFoldingModel().runBatchFoldingOperation(() -> { myFoldingModel.flushCaretShift(); region.setExpanded(true); }); // The call below is performed because gutter's height is not updated sometimes, i.e. it sticks to the value that corresponds // to the situation when fold region is collapsed. That causes bottom of the gutter to not be repainted and that looks really ugly. myGutterComponent.updateSize(); } // The general idea is to check if the user performed 'caret position change click' (left click most of the time) inside selection // and, in the case of the positive answer, clear selection. Please note that there is a possible case that mouse click // is performed inside selection but it triggers context menu. We don't want to drop the selection then. if (myMousePressedEvent != null && myMousePressedEvent.getClickCount() == 1 && myMousePressedInsideSelection && !myMousePressedEvent.isShiftDown() && !myMousePressedEvent.isPopupTrigger() && !isToggleCaretEvent(myMousePressedEvent) && !isCreateRectangularSelectionEvent(myMousePressedEvent)) { getSelectionModel().removeSelection(); } } @NotNull @Override public DataContext getDataContext() { return getProjectAwareDataContext(DataManager.getInstance().getDataContext(getContentComponent())); } @NotNull private DataContext getProjectAwareDataContext(@NotNull final DataContext original) { if (CommonDataKeys.PROJECT.getData(original) == myProject) return original; return dataId -> { if (CommonDataKeys.PROJECT.is(dataId)) { return myProject; } return original.getData(dataId); }; } private boolean isInsideGutterWhitespaceArea(@NotNull MouseEvent e) { EditorMouseEventArea area = getMouseEventArea(e); return area == EditorMouseEventArea.FOLDING_OUTLINE_AREA && myGutterComponent.convertX(e.getX()) > myGutterComponent.getWhitespaceSeparatorOffset(); } @Override public EditorMouseEventArea getMouseEventArea(@NotNull MouseEvent e) { if (myGutterComponent != e.getSource()) return EditorMouseEventArea.EDITING_AREA; int x = myGutterComponent.convertX(e.getX()); return myGutterComponent.getEditorMouseAreaByOffset(x); } private void requestFocus() { final IdeFocusManager focusManager = IdeFocusManager.getInstance(myProject); if (focusManager.getFocusOwner() != myEditorComponent) { //IDEA-64501 focusManager.requestFocus(myEditorComponent, true); } } private void validateMousePointer(@NotNull MouseEvent e) { if (e.getSource() == myGutterComponent) { myGutterComponent.validateMousePointer(e); } else { myGutterComponent.setActiveFoldRegion(null); if (getSelectionModel().hasSelection() && (e.getModifiersEx() & (InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK)) == 0) { int offset = logicalPositionToOffset(xyToLogicalPosition(e.getPoint())); if (getSelectionModel().getSelectionStart() <= offset && offset < getSelectionModel().getSelectionEnd()) { UIUtil.setCursor(myEditorComponent, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return; } } if (!IdeGlassPaneImpl.hasPreProcessedCursor(myEditorComponent)) { UIUtil.setCursor(myEditorComponent, UIUtil.getTextCursor(getBackgroundColor())); } } } private void runMouseDraggedCommand(@NotNull final MouseEvent e) { if (myCommandProcessor == null || myMousePressedEvent != null && myMousePressedEvent.isConsumed()) { return; } myCommandProcessor.executeCommand(myProject, () -> processMouseDragged(e), "", MOUSE_DRAGGED_GROUP, UndoConfirmationPolicy.DEFAULT, getDocument()); } private void processMouseDragged(@NotNull MouseEvent e) { if (!JBSwingUtilities.isLeftMouseButton(e) && !JBSwingUtilities.isMiddleMouseButton(e)) { return; } EditorMouseEventArea eventArea = getMouseEventArea(e); if (eventArea == EditorMouseEventArea.ANNOTATIONS_AREA) return; if (eventArea == EditorMouseEventArea.LINE_MARKERS_AREA || eventArea == EditorMouseEventArea.FOLDING_OUTLINE_AREA && !isInsideGutterWhitespaceArea(e)) { // The general idea is that we don't want to change caret position on gutter marker area click (e.g. on setting a breakpoint) // but do want to allow bulk selection on gutter marker mouse drag. However, when a drag is performed, the first event is // a 'mouse pressed' event, that's why we remember target line on 'mouse pressed' processing and use that information on // further dragging (if any). if (myDragOnGutterSelectionStartLine >= 0) { mySelectionModel.removeSelection(); myCaretModel.moveToOffset(myDragOnGutterSelectionStartLine < myDocument.getLineCount() ? myDocument.getLineStartOffset(myDragOnGutterSelectionStartLine) : myDocument.getTextLength()); } myDragOnGutterSelectionStartLine = - 1; } boolean columnSelectionDragEvent = isColumnSelectionDragEvent(e); boolean toggleCaretEvent = isToggleCaretEvent(e); boolean addRectangularSelectionEvent = isAddRectangularSelectionEvent(e); boolean columnSelectionDrag = isColumnMode() && !myLastPressCreatedCaret || columnSelectionDragEvent; if (!columnSelectionDragEvent && toggleCaretEvent && !myLastPressCreatedCaret) { return; // ignoring drag after removing a caret } Rectangle visibleArea = getScrollingModel().getVisibleArea(); int x = e.getX(); if (e.getSource() == myGutterComponent) { x = 0; } int dx = 0; if (x < visibleArea.x && visibleArea.x > 0) { dx = x - visibleArea.x; } else { if (x > visibleArea.x + visibleArea.width) { dx = x - visibleArea.x - visibleArea.width; } } int dy = 0; int y = e.getY(); if (y < visibleArea.y && visibleArea.y > 0) { dy = y - visibleArea.y; } else { if (y > visibleArea.y + visibleArea.height) { dy = y - visibleArea.y - visibleArea.height; } } if (dx == 0 && dy == 0) { myScrollingTimer.stop(); SelectionModel selectionModel = getSelectionModel(); Caret leadCaret = getLeadCaret(); int oldSelectionStart = leadCaret.getLeadSelectionOffset(); VisualPosition oldVisLeadSelectionStart = leadCaret.getLeadSelectionPosition(); int oldCaretOffset = getCaretModel().getOffset(); boolean multiCaretSelection = columnSelectionDrag || toggleCaretEvent; VisualPosition newVisualCaret = getTargetPosition(x, y, !multiCaretSelection); LogicalPosition newLogicalCaret = visualToLogicalPosition(newVisualCaret); if (multiCaretSelection) { myMultiSelectionInProgress = true; myRectangularSelectionInProgress = columnSelectionDrag || addRectangularSelectionEvent; myTargetMultiSelectionPosition = xyToVisualPosition(new Point(Math.max(x, 0), Math.max(y, 0))); } else { getCaretModel().moveToVisualPosition(newVisualCaret); } int newCaretOffset = getCaretModel().getOffset(); newVisualCaret = getCaretModel().getVisualPosition(); int caretShift = newCaretOffset - mySavedSelectionStart; if (myMousePressedEvent != null && getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.EDITING_AREA && getMouseEventArea(myMousePressedEvent) != EditorMouseEventArea.LINE_NUMBERS_AREA) { selectionModel.setSelection(oldSelectionStart, newCaretOffset); } else { if (multiCaretSelection) { if (myLastMousePressedLocation != null && (myCurrentDragIsSubstantial || !newLogicalCaret.equals(myLastMousePressedLocation))) { createSelectionTill(newLogicalCaret); blockActionsIfNeeded(e, myLastMousePressedLocation, newLogicalCaret); } } else { if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (caretShift < 0) { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretStart(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; selectionModel.setSelection(mySavedSelectionEnd, newSelection); getCaretModel().moveToOffset(newSelection); } else { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretEnd(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; selectionModel.setSelection(mySavedSelectionStart, newSelection); getCaretModel().moveToOffset(newSelection); } cancelAutoResetForMouseSelectionState(); return; } if (!myMousePressedInsideSelection) { // There is a possible case that lead selection position should be adjusted in accordance with the mouse move direction. // E.g. consider situation when user selects the whole line by clicking at 'line numbers' area. 'Line end' is considered // to be lead selection point then. However, when mouse is dragged down we want to consider 'line start' to be // lead selection point. if ((myMousePressArea == EditorMouseEventArea.LINE_NUMBERS_AREA || myMousePressArea == EditorMouseEventArea.LINE_MARKERS_AREA) && selectionModel.hasSelection()) { if (newCaretOffset >= selectionModel.getSelectionEnd()) { oldSelectionStart = selectionModel.getSelectionStart(); oldVisLeadSelectionStart = selectionModel.getSelectionStartPosition(); } else if (newCaretOffset <= selectionModel.getSelectionStart()) { oldSelectionStart = selectionModel.getSelectionEnd(); oldVisLeadSelectionStart = selectionModel.getSelectionEndPosition(); } } if (oldVisLeadSelectionStart != null) { setSelectionAndBlockActions(e, oldVisLeadSelectionStart, oldSelectionStart, newVisualCaret, newCaretOffset); } else { setSelectionAndBlockActions(e, oldSelectionStart, newCaretOffset); } cancelAutoResetForMouseSelectionState(); } else { if (caretShift != 0) { if (myMousePressedEvent != null) { if (mySettings.isDndEnabled()) { boolean isCopy = UIUtil.isControlKeyDown(e) || isViewer() || !getDocument().isWritable(); mySavedCaretOffsetForDNDUndoHack = oldCaretOffset; getContentComponent().getTransferHandler().exportAsDrag(getContentComponent(), e, isCopy ? TransferHandler.COPY : TransferHandler.MOVE); } else { selectionModel.removeSelection(); } } } } } } } else { myScrollingTimer.start(dx, dy); onSubstantialDrag(e); } } private void clearDnDContext() { if (myDraggedRange != null) { myDraggedRange.dispose(); myDraggedRange = null; } myGutterComponent.myDnDInProgress = false; } private void createSelectionTill(@NotNull LogicalPosition targetPosition) { List<CaretState> caretStates = new ArrayList<>(myCaretStateBeforeLastPress); if (myRectangularSelectionInProgress) { caretStates.addAll(EditorModificationUtil.calcBlockSelectionState(this, myLastMousePressedLocation, targetPosition)); } else { LogicalPosition selectionStart = myLastMousePressedLocation; LogicalPosition selectionEnd = targetPosition; if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { int newCaretOffset = logicalPositionToOffset(targetPosition); if (newCaretOffset < mySavedSelectionStart) { selectionStart = offsetToLogicalPosition(mySavedSelectionEnd); if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(newCaretOffset), 0)); } } else { selectionStart = offsetToLogicalPosition(mySavedSelectionStart); int selectionEndOffset = Math.max(newCaretOffset, mySavedSelectionEnd); if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { targetPosition = selectionEnd = offsetToLogicalPosition(selectionEndOffset); } else if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { targetPosition = selectionEnd = visualToLogicalPosition(new VisualPosition(offsetToVisualLine(selectionEndOffset) + 1, 0)); } } cancelAutoResetForMouseSelectionState(); } caretStates.add(new CaretState(targetPosition, selectionStart, selectionEnd)); } myCaretModel.setCaretsAndSelections(caretStates); } private Caret getLeadCaret() { List<Caret> allCarets = myCaretModel.getAllCarets(); Caret firstCaret = allCarets.get(0); if (firstCaret == myCaretModel.getPrimaryCaret()) { return allCarets.get(allCarets.size() - 1); } return firstCaret; } private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, int startOffset, int endOffset) { mySelectionModel.setSelection(startOffset, endOffset); if (myCurrentDragIsSubstantial || startOffset != endOffset) { onSubstantialDrag(mouseDragEvent); } } private void setSelectionAndBlockActions(@NotNull MouseEvent mouseDragEvent, VisualPosition startPosition, int startOffset, VisualPosition endPosition, int endOffset) { mySelectionModel.setSelection(startPosition, startOffset, endPosition, endOffset); if (myCurrentDragIsSubstantial || startOffset != endOffset || !Comparing.equal(startPosition, endPosition)) { onSubstantialDrag(mouseDragEvent); } } private void blockActionsIfNeeded(@NotNull MouseEvent mouseDragEvent, @NotNull LogicalPosition startPosition, @NotNull LogicalPosition endPosition) { if (myCurrentDragIsSubstantial || !startPosition.equals(endPosition)) { onSubstantialDrag(mouseDragEvent); } } private void onSubstantialDrag(@NotNull MouseEvent mouseDragEvent) { IdeEventQueue.getInstance().blockNextEvents(mouseDragEvent, IdeEventQueue.BlockMode.ACTIONS); myCurrentDragIsSubstantial = true; } private static class RepaintCursorCommand implements Runnable { private long mySleepTime = 500; private boolean myIsBlinkCaret = true; @Nullable private EditorImpl myEditor; private ScheduledFuture<?> mySchedulerHandle; public void start() { if (mySchedulerHandle != null) { mySchedulerHandle.cancel(false); } mySchedulerHandle = EdtExecutorService.getScheduledExecutorInstance().scheduleWithFixedDelay(this, mySleepTime, mySleepTime, TimeUnit.MILLISECONDS); } private void setBlinkPeriod(int blinkPeriod) { mySleepTime = blinkPeriod > 10 ? blinkPeriod : 10; start(); } private void setBlinkCaret(boolean value) { myIsBlinkCaret = value; } @Override public void run() { if (myEditor != null) { CaretCursor activeCursor = myEditor.myCaretCursor; long time = System.currentTimeMillis(); time -= activeCursor.myStartTime; if (time > mySleepTime) { boolean toRepaint = true; if (myIsBlinkCaret) { activeCursor.myIsShown = !activeCursor.myIsShown; } else { toRepaint = !activeCursor.myIsShown; activeCursor.myIsShown = true; } if (toRepaint) { activeCursor.repaint(); } } } } } void updateCaretCursor() { myUpdateCursor = true; } private void setCursorPosition() { final List<CaretRectangle> caretPoints = new ArrayList<>(); for (Caret caret : getCaretModel().getAllCarets()) { boolean isRtl = caret.isAtRtlLocation(); VisualPosition caretPosition = caret.getVisualPosition(); Point pos1 = visualPositionToXY(caretPosition.leanRight(!isRtl)); Point pos2 = visualPositionToXY(new VisualPosition(caretPosition.line, Math.max(0, caretPosition.column + (isRtl ? -1 : 1)), isRtl)); int width = Math.abs(pos2.x - pos1.x); if (!isRtl && myInlayModel.hasInlineElementAt(caretPosition)) { width = Math.min(width, myView.getPlainSpaceWidth()); } caretPoints.add(new CaretRectangle(pos1, width, caret, isRtl)); } myCaretCursor.setPositions(caretPoints.toArray(new CaretRectangle[caretPoints.size()])); } @Override public boolean setCaretVisible(boolean b) { boolean old = myCaretCursor.isActive(); if (b) { myCaretCursor.activate(); } else { myCaretCursor.passivate(); } return old; } @Override public boolean setCaretEnabled(boolean enabled) { boolean old = myCaretCursor.isEnabled(); myCaretCursor.setEnabled(enabled); return old; } @Override public void addFocusListener(@NotNull FocusChangeListener listener) { myFocusListeners.add(listener); } @Override public void addFocusListener(@NotNull FocusChangeListener listener, @NotNull Disposable parentDisposable) { ContainerUtil.add(listener, myFocusListeners, parentDisposable); } @Override @Nullable public Project getProject() { return myProject; } @Override public boolean isOneLineMode() { return myIsOneLineMode; } @Override public boolean isEmbeddedIntoDialogWrapper() { return myEmbeddedIntoDialogWrapper; } @Override public void setEmbeddedIntoDialogWrapper(boolean b) { assertIsDispatchThread(); myEmbeddedIntoDialogWrapper = b; myScrollPane.setFocusable(!b); myEditorComponent.setFocusCycleRoot(!b); myEditorComponent.setFocusable(b); } @Override public void setOneLineMode(boolean isOneLineMode) { myIsOneLineMode = isOneLineMode; getScrollPane().setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); reinitSettings(); } public static class CaretRectangle { public final Point myPoint; public final int myWidth; public final Caret myCaret; public final boolean myIsRtl; private CaretRectangle(Point point, int width, Caret caret, boolean isRtl) { myPoint = point; myWidth = Math.max(width, 2); myCaret = caret; myIsRtl = isRtl; } } class CaretCursor { private CaretRectangle[] myLocations; private boolean myEnabled; @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") private boolean myIsShown; private long myStartTime; private CaretCursor() { myLocations = new CaretRectangle[] {new CaretRectangle(new Point(0, 0), 0, null, false)}; setEnabled(true); } public boolean isEnabled() { return myEnabled; } public void setEnabled(boolean enabled) { myEnabled = enabled; } private void activate() { final boolean blink = mySettings.isBlinkCaret(); final int blinkPeriod = mySettings.getCaretBlinkPeriod(); synchronized (ourCaretBlinkingCommand) { ourCaretBlinkingCommand.myEditor = EditorImpl.this; ourCaretBlinkingCommand.setBlinkCaret(blink); ourCaretBlinkingCommand.setBlinkPeriod(blinkPeriod); myIsShown = true; } } public boolean isActive() { synchronized (ourCaretBlinkingCommand) { return myIsShown; } } private void passivate() { synchronized (ourCaretBlinkingCommand) { myIsShown = false; } } private void setPositions(CaretRectangle[] locations) { myStartTime = System.currentTimeMillis(); myLocations = locations; myIsShown = true; } private void repaint() { myView.repaintCarets(); } @Nullable CaretRectangle[] getCaretLocations(boolean onlyIfShown) { if (onlyIfShown && (!isEnabled() || !myIsShown || isRendererMode() || !IJSwingUtilities.hasFocus(getContentComponent()))) return null; return myLocations; } } private class ScrollingTimer { private Timer myTimer; private static final int TIMER_PERIOD = 100; private static final int CYCLE_SIZE = 20; private int myXCycles; private int myYCycles; private int myDx; private int myDy; private int xPassedCycles; private int yPassedCycles; private void start(int dx, int dy) { myDx = 0; myDy = 0; if (dx > 0) { myXCycles = CYCLE_SIZE / dx + 1; myDx = 1 + dx / CYCLE_SIZE; } else { if (dx < 0) { myXCycles = -CYCLE_SIZE / dx + 1; myDx = -1 + dx / CYCLE_SIZE; } } if (dy > 0) { myYCycles = CYCLE_SIZE / dy + 1; myDy = 1 + dy / CYCLE_SIZE; } else { if (dy < 0) { myYCycles = -CYCLE_SIZE / dy + 1; myDy = -1 + dy / CYCLE_SIZE; } } if (myTimer != null) { return; } myTimer = UIUtil.createNamedTimer("Editor scroll timer", TIMER_PERIOD, e -> { if (isDisposed()) { stop(); return; } myCommandProcessor.executeCommand(myProject, new DocumentRunnable(myDocument, myProject) { @Override public void run() { int oldSelectionStart = mySelectionModel.getLeadSelectionOffset(); VisualPosition caretPosition = myMultiSelectionInProgress ? myTargetMultiSelectionPosition : getCaretModel().getVisualPosition(); int column = caretPosition.column; xPassedCycles++; if (xPassedCycles >= myXCycles) { xPassedCycles = 0; column += myDx; } int line = caretPosition.line; yPassedCycles++; if (yPassedCycles >= myYCycles) { yPassedCycles = 0; line += myDy; } line = Math.max(0, line); column = Math.max(0, column); VisualPosition pos = new VisualPosition(line, column); if (!myMultiSelectionInProgress) { getCaretModel().moveToVisualPosition(pos); getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } int newCaretOffset = getCaretModel().getOffset(); int caretShift = newCaretOffset - mySavedSelectionStart; if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (caretShift < 0) { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretStart(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; mySelectionModel.setSelection(validateOffset(mySavedSelectionEnd), newSelection); getCaretModel().moveToOffset(newSelection); } else { int newSelection = newCaretOffset; if (getMouseSelectionState() == MOUSE_SELECTION_STATE_WORD_SELECTED) { newSelection = myCaretModel.getWordAtCaretEnd(); } else { if (getMouseSelectionState() == MOUSE_SELECTION_STATE_LINE_SELECTED) { newSelection = logicalPositionToOffset( visualToLogicalPosition(new VisualPosition(getCaretModel().getVisualPosition().line + 1, 0))); } } if (newSelection < 0) newSelection = newCaretOffset; mySelectionModel.setSelection(validateOffset(mySavedSelectionStart), newSelection); getCaretModel().moveToOffset(newSelection); } return; } if (myMultiSelectionInProgress && myLastMousePressedLocation != null) { myTargetMultiSelectionPosition = pos; LogicalPosition newLogicalPosition = visualToLogicalPosition(pos); getScrollingModel().scrollTo(newLogicalPosition, ScrollType.RELATIVE); createSelectionTill(newLogicalPosition); } else { mySelectionModel.setSelection(oldSelectionStart, getCaretModel().getOffset()); } } }, EditorBundle.message("move.cursor.command.name"), DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); }); myTimer.start(); } private void stop() { if (myTimer != null) { myTimer.stop(); myTimer = null; } } private int validateOffset(int offset) { if (offset < 0) return 0; if (offset > myDocument.getTextLength()) return myDocument.getTextLength(); return offset; } } private static void updateOpaque(JScrollBar bar) { if (bar instanceof OpaqueAwareScrollBar) { bar.setOpaque(((OpaqueAwareScrollBar)bar).myOpaque); } } private class OpaqueAwareScrollBar extends JBScrollBar { private boolean myOpaque; private OpaqueAwareScrollBar(@JdkConstants.AdjustableOrientation int orientation) { super(orientation); addPropertyChangeListener("opaque", event -> { revalidate(); repaint(); }); } @Override public void setOpaque(boolean opaque) { myOpaque = opaque; super.setOpaque(opaque || shouldScrollBarBeOpaque()); } @Override public boolean isOptimizedDrawingEnabled() { return !myBackgroundImageSet; } } private static final Field decrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "decrButton"); private static final Field incrButtonField = ReflectionUtil.getDeclaredField(BasicScrollBarUI.class, "incrButton"); class MyScrollBar extends OpaqueAwareScrollBar { @NonNls private static final String APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS = "apple.laf.AquaScrollBarUI"; private ScrollBarUI myPersistentUI; private MyScrollBar(@JdkConstants.AdjustableOrientation int orientation) { super(orientation); } void setPersistentUI(ScrollBarUI ui) { myPersistentUI = ui; setUI(ui); } @Override public void setUI(ScrollBarUI ui) { if (myPersistentUI == null) myPersistentUI = ui; super.setUI(myPersistentUI); } /** * This is helper method. It returns height of the top (decrease) scroll bar * button. Please note, that it's possible to return real height only if scroll bar * is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) ) * value. */ int getDecScrollButtonHeight() { ScrollBarUI barUI = getUI(); Insets insets = getInsets(); int top = Math.max(0, insets.top); if (barUI instanceof ButtonlessScrollBarUI) { return top + ((ButtonlessScrollBarUI)barUI).getDecrementButtonHeight(); } if (barUI instanceof BasicScrollBarUI) { try { JButton decrButtonValue = (JButton)decrButtonField.get(barUI); LOG.assertTrue(decrButtonValue != null); return top + decrButtonValue.getHeight(); } catch (Exception exc) { throw new IllegalStateException(exc); } } return top + 15; } /** * This is helper method. It returns height of the bottom (increase) scroll bar * button. Please note, that it's possible to return real height only if scroll bar * is instance of BasicScrollBarUI. Otherwise it returns fake (but good enough :) ) * value. */ int getIncScrollButtonHeight() { ScrollBarUI barUI = getUI(); Insets insets = getInsets(); if (barUI instanceof ButtonlessScrollBarUI) { return insets.top + ((ButtonlessScrollBarUI)barUI).getIncrementButtonHeight(); } if (barUI instanceof BasicScrollBarUI) { try { JButton incrButtonValue = (JButton)incrButtonField.get(barUI); LOG.assertTrue(incrButtonValue != null); return insets.bottom + incrButtonValue.getHeight(); } catch (Exception exc) { throw new IllegalStateException(exc); } } if (APPLE_LAF_AQUA_SCROLL_BAR_UI_CLASS.equals(barUI.getClass().getName())) { return insets.bottom + 30; } return insets.bottom + 15; } @Override public int getUnitIncrement(int direction) { JViewport vp = myScrollPane.getViewport(); Rectangle vr = vp.getViewRect(); return myEditorComponent.getScrollableUnitIncrement(vr, SwingConstants.VERTICAL, direction); } @Override public int getBlockIncrement(int direction) { JViewport vp = myScrollPane.getViewport(); Rectangle vr = vp.getViewRect(); return myEditorComponent.getScrollableBlockIncrement(vr, SwingConstants.VERTICAL, direction); } private void registerRepaintCallback(@Nullable ButtonlessScrollBarUI.ScrollbarRepaintCallback callback) { if (myPersistentUI instanceof ButtonlessScrollBarUI) { ((ButtonlessScrollBarUI)myPersistentUI).registerRepaintCallback(callback); } } } private MyEditable getViewer() { if (myEditable == null) { myEditable = new MyEditable(); } return myEditable; } @Override public CopyProvider getCopyProvider() { return getViewer(); } @Override public CutProvider getCutProvider() { return getViewer(); } @Override public PasteProvider getPasteProvider() { return getViewer(); } @Override public DeleteProvider getDeleteProvider() { return getViewer(); } private class MyEditable implements CutProvider, CopyProvider, PasteProvider, DeleteProvider, DumbAware { @Override public void performCopy(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_COPY, dataContext); } @Override public boolean isCopyEnabled(@NotNull DataContext dataContext) { return true; } @Override public boolean isCopyVisible(@NotNull DataContext dataContext) { return getSelectionModel().hasSelection(true); } @Override public void performCut(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_CUT, dataContext); } @Override public boolean isCutEnabled(@NotNull DataContext dataContext) { return !isViewer(); } @Override public boolean isCutVisible(@NotNull DataContext dataContext) { return isCutEnabled(dataContext) && getSelectionModel().hasSelection(true); } @Override public void performPaste(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_PASTE, dataContext); } @Override public boolean isPastePossible(@NotNull DataContext dataContext) { // Copy of isPasteEnabled. See interface method javadoc. return !isViewer(); } @Override public boolean isPasteEnabled(@NotNull DataContext dataContext) { return !isViewer(); } @Override public void deleteElement(@NotNull DataContext dataContext) { executeAction(IdeActions.ACTION_EDITOR_DELETE, dataContext); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return !isViewer(); } private void executeAction(@NotNull String actionId, @NotNull DataContext dataContext) { EditorAction action = (EditorAction)ActionManager.getInstance().getAction(actionId); if (action != null) { action.actionPerformed(EditorImpl.this, dataContext); } } } @Override public void setColorsScheme(@NotNull EditorColorsScheme scheme) { assertIsDispatchThread(); myScheme = scheme; reinitSettings(); } @Override @NotNull public EditorColorsScheme getColorsScheme() { return myScheme; } static void assertIsDispatchThread() { ApplicationManager.getApplication().assertIsDispatchThread(); } private static void assertReadAccess() { ApplicationManager.getApplication().assertReadAccessAllowed(); } @Override public void setVerticalScrollbarOrientation(int type) { assertIsDispatchThread(); int currentHorOffset = myScrollingModel.getHorizontalScrollOffset(); myScrollBarOrientation = type; myScrollPane.putClientProperty(JBScrollPane.Flip.class, type == VERTICAL_SCROLLBAR_LEFT ? JBScrollPane.Flip.HORIZONTAL : null); myScrollingModel.scrollHorizontally(currentHorOffset); } @Override public void setVerticalScrollbarVisible(boolean b) { myScrollPane .setVerticalScrollBarPolicy(b ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); } @Override public void setHorizontalScrollbarVisible(boolean b) { myScrollPane.setHorizontalScrollBarPolicy( b ? ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED : ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); } @Override public int getVerticalScrollbarOrientation() { return myScrollBarOrientation; } public boolean isMirrored() { return myScrollBarOrientation != EditorEx.VERTICAL_SCROLLBAR_RIGHT; } @NotNull MyScrollBar getVerticalScrollBar() { return myVerticalScrollBar; } @MouseSelectionState private int getMouseSelectionState() { return myMouseSelectionState; } private void setMouseSelectionState(@MouseSelectionState int mouseSelectionState) { if (getMouseSelectionState() == mouseSelectionState) return; myMouseSelectionState = mouseSelectionState; myMouseSelectionChangeTimestamp = System.currentTimeMillis(); myMouseSelectionStateAlarm.cancelAllRequests(); if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE) { if (myMouseSelectionStateResetRunnable == null) { myMouseSelectionStateResetRunnable = () -> resetMouseSelectionState(null); } myMouseSelectionStateAlarm.addRequest(myMouseSelectionStateResetRunnable, Registry.intValue("editor.mouseSelectionStateResetTimeout"), ModalityState.stateForComponent(myEditorComponent)); } } private void resetMouseSelectionState(@Nullable MouseEvent event) { setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); MouseEvent e = event != null ? event : myMouseMovedEvent; if (e != null) { validateMousePointer(e); } } private void cancelAutoResetForMouseSelectionState() { myMouseSelectionStateAlarm.cancelAllRequests(); } void replaceInputMethodText(@NotNull InputMethodEvent e) { if (isReleased) return; getInputMethodRequests(); myInputMethodRequestsHandler.replaceInputMethodText(e); } void inputMethodCaretPositionChanged(@NotNull InputMethodEvent e) { if (isReleased) return; getInputMethodRequests(); myInputMethodRequestsHandler.setInputMethodCaretPosition(e); } @NotNull InputMethodRequests getInputMethodRequests() { if (myInputMethodRequestsHandler == null) { myInputMethodRequestsHandler = new MyInputMethodHandler(); myInputMethodRequestsSwingWrapper = new MyInputMethodHandleSwingThreadWrapper(myInputMethodRequestsHandler); } return myInputMethodRequestsSwingWrapper; } @Override public boolean processKeyTyped(@NotNull KeyEvent e) { if (e.getID() != KeyEvent.KEY_TYPED) return false; char c = e.getKeyChar(); if (UIUtil.isReallyTypedEvent(e)) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction processKeyTyped(c); return true; } else { return false; } } void beforeModalityStateChanged() { myScrollingModel.beforeModalityStateChanged(); } EditorDropHandler getDropHandler() { return myDropHandler; } public void setDropHandler(@NotNull EditorDropHandler dropHandler) { myDropHandler = dropHandler; } public void setHighlightingFilter(@Nullable Condition<RangeHighlighter> filter) { if (myHighlightingFilter == filter) return; Condition<RangeHighlighter> oldFilter = myHighlightingFilter; myHighlightingFilter = filter; for (RangeHighlighter highlighter : myDocumentMarkupModel.getDelegate().getAllHighlighters()) { boolean oldAvailable = oldFilter == null || oldFilter.value(highlighter); boolean newAvailable = filter == null || filter.value(highlighter); if (oldAvailable != newAvailable) { myMarkupModelListener.attributesChanged((RangeHighlighterEx)highlighter, true, EditorUtil.attributesImpactFontStyleOrColor(highlighter.getTextAttributes())); } } } boolean isHighlighterAvailable(@NotNull RangeHighlighter highlighter) { return myHighlightingFilter == null || myHighlightingFilter.value(highlighter); } private static class MyInputMethodHandleSwingThreadWrapper implements InputMethodRequests { private final InputMethodRequests myDelegate; private MyInputMethodHandleSwingThreadWrapper(InputMethodRequests delegate) { myDelegate = delegate; } @NotNull @Override public Rectangle getTextLocation(final TextHitInfo offset) { return execute(() -> myDelegate.getTextLocation(offset)); } @Override public TextHitInfo getLocationOffset(final int x, final int y) { return execute(() -> myDelegate.getLocationOffset(x, y)); } @Override public int getInsertPositionOffset() { return execute(myDelegate::getInsertPositionOffset); } @NotNull @Override public AttributedCharacterIterator getCommittedText(final int beginIndex, final int endIndex, final AttributedCharacterIterator.Attribute[] attributes) { return execute(() -> myDelegate.getCommittedText(beginIndex, endIndex, attributes)); } @Override public int getCommittedTextLength() { return execute(myDelegate::getCommittedTextLength); } @Override @Nullable public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) { return null; } @Override public AttributedCharacterIterator getSelectedText(final AttributedCharacterIterator.Attribute[] attributes) { return execute(() -> myDelegate.getSelectedText(attributes)); } private static <T> T execute(final Computable<T> computable) { return UIUtil.invokeAndWaitIfNeeded(computable); } } private class MyInputMethodHandler implements InputMethodRequests { private String composedText; private ProperTextRange composedTextRange; @NotNull @Override public Rectangle getTextLocation(TextHitInfo offset) { Point caret = logicalPositionToXY(getCaretModel().getLogicalPosition()); Rectangle r = new Rectangle(caret, new Dimension(1, getLineHeight())); Point p = getLocationOnScreen(getContentComponent()); r.translate(p.x, p.y); return r; } @Override @Nullable public TextHitInfo getLocationOffset(int x, int y) { if (composedText != null) { Point p = getLocationOnScreen(getContentComponent()); p.x = x - p.x; p.y = y - p.y; int pos = logicalPositionToOffset(xyToLogicalPosition(p)); if (composedTextRange.containsOffset(pos)) { return TextHitInfo.leading(pos - composedTextRange.getStartOffset()); } } return null; } private Point getLocationOnScreen(Component component) { Point location = new Point(); SwingUtilities.convertPointToScreen(location, component); if (LOG.isDebugEnabled() && !component.isShowing()) { Class<?> type = component.getClass(); Component parent = component.getParent(); while (parent != null && !parent.isShowing()) { type = parent.getClass(); parent = parent.getParent(); } String message = type.getName() + " is not showing"; if (parent != null) message += " on visible " + parent.getClass().getName(); LOG.debug(message); } return location; } @Override public int getInsertPositionOffset() { int composedStartIndex = 0; int composedEndIndex = 0; if (composedText != null) { composedStartIndex = composedTextRange.getStartOffset(); composedEndIndex = composedTextRange.getEndOffset(); } int caretIndex = getCaretModel().getOffset(); if (caretIndex < composedStartIndex) { return caretIndex; } if (caretIndex < composedEndIndex) { return composedStartIndex; } return caretIndex - (composedEndIndex - composedStartIndex); } private String getText(int startIdx, int endIdx) { if (startIdx >= 0 && endIdx > startIdx) { CharSequence chars = getDocument().getImmutableCharSequence(); return chars.subSequence(startIdx, endIdx).toString(); } return ""; } @NotNull @Override public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) { int composedStartIndex = 0; int composedEndIndex = 0; if (composedText != null) { composedStartIndex = composedTextRange.getStartOffset(); composedEndIndex = composedTextRange.getEndOffset(); } String committed; if (beginIndex < composedStartIndex) { if (endIndex <= composedStartIndex) { committed = getText(beginIndex, endIndex - beginIndex); } else { int firstPartLength = composedStartIndex - beginIndex; committed = getText(beginIndex, firstPartLength) + getText(composedEndIndex, endIndex - beginIndex - firstPartLength); } } else { committed = getText(beginIndex + composedEndIndex - composedStartIndex, endIndex - beginIndex); } return new AttributedString(committed).getIterator(); } @Override public int getCommittedTextLength() { int length = getDocument().getTextLength(); if (composedText != null) { length -= composedText.length(); } return length; } @Override @Nullable public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) { return null; } @Override @Nullable public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) { if (myCharKeyPressed) { myNeedToSelectPreviousChar = true; } String text = getSelectionModel().getSelectedText(); return text == null ? null : new AttributedString(text).getIterator(); } private void createComposedString(int composedIndex, @NotNull AttributedCharacterIterator text) { StringBuffer strBuf = new StringBuffer(); // create attributed string with no attributes for (char c = text.setIndex(composedIndex); c != CharacterIterator.DONE; c = text.next()) { strBuf.append(c); } composedText = new String(strBuf); } private void setInputMethodCaretPosition(@NotNull InputMethodEvent e) { if (composedText != null) { int dot = composedTextRange.getStartOffset(); TextHitInfo caretPos = e.getCaret(); if (caretPos != null) { dot += caretPos.getInsertionIndex(); } getCaretModel().moveToOffset(dot); getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } private void runUndoTransparent(@NotNull final Runnable runnable) { CommandProcessor.getInstance().runUndoTransparentAction( () -> CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(runnable), "", getDocument(), UndoConfirmationPolicy.DEFAULT, getDocument())); } private void replaceInputMethodText(@NotNull InputMethodEvent e) { if (myNeedToSelectPreviousChar && SystemInfo.isMac && (Registry.is("ide.mac.pressAndHold.brute.workaround") || Registry.is("ide.mac.pressAndHold.workaround") && (e.getCommittedCharacterCount() > 0 || e.getCaret() == null))) { // This is required to support input of accented characters using press-and-hold method (http://support.apple.com/kb/PH11264). // JDK currently properly supports this functionality only for TextComponent/JTextComponent descendants. // For our editor component we need this workaround. // After https://bugs.openjdk.java.net/browse/JDK-8074882 is fixed, this workaround should be replaced with a proper solution. myNeedToSelectPreviousChar = false; getCaretModel().runForEachCaret(caret -> { int caretOffset = caret.getOffset(); if (caretOffset > 0) { caret.setSelection(caretOffset - 1, caretOffset); } }); } int commitCount = e.getCommittedCharacterCount(); AttributedCharacterIterator text = e.getText(); // old composed text deletion final Document doc = getDocument(); if (composedText != null) { if (!isViewer() && doc.isWritable()) { runUndoTransparent(() -> { int docLength = doc.getTextLength(); ProperTextRange range = composedTextRange.intersection(new TextRange(0, docLength)); if (range != null) { doc.deleteString(range.getStartOffset(), range.getEndOffset()); } }); } composedText = null; } if (text != null) { text.first(); // committed text insertion if (commitCount > 0) { //noinspection ForLoopThatDoesntUseLoopVariable for (char c = text.current(); commitCount > 0; c = text.next(), commitCount--) { if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction processKeyTyped(c); } } } // new composed text insertion if (!isViewer() && doc.isWritable()) { int composedTextIndex = text.getIndex(); if (composedTextIndex < text.getEndIndex()) { createComposedString(composedTextIndex, text); runUndoTransparent(() -> EditorModificationUtil.insertStringAtCaret(EditorImpl.this, composedText, false, false)); composedTextRange = ProperTextRange.from(getCaretModel().getOffset(), composedText.length()); } } } } } private class MyMouseAdapter extends MouseAdapter { @Override public void mousePressed(@NotNull MouseEvent e) { requestFocus(); runMousePressedCommand(e); } @Override public void mouseReleased(@NotNull MouseEvent e) { myMousePressArea = null; myLastMousePressedLocation = null; runMouseReleasedCommand(e); if (!e.isConsumed() && myMousePressedEvent != null && !myMousePressedEvent.isConsumed() && Math.abs(e.getX() - myMousePressedEvent.getX()) < EditorUtil.getSpaceWidth(Font.PLAIN, EditorImpl.this) && Math.abs(e.getY() - myMousePressedEvent.getY()) < getLineHeight()) { runMouseClickedCommand(e); } } @Override public void mouseEntered(@NotNull MouseEvent e) { runMouseEnteredCommand(e); } @Override public void mouseExited(@NotNull MouseEvent e) { runMouseExitedCommand(e); EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) { myGutterComponent.mouseExited(e); } TooltipController.getInstance().cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true); } private void runMousePressedCommand(@NotNull final MouseEvent e) { myLastMousePressedLocation = xyToLogicalPosition(e.getPoint()); myCaretStateBeforeLastPress = isToggleCaretEvent(e) ? myCaretModel.getCaretsAndSelections() : Collections.emptyList(); myCurrentDragIsSubstantial = false; clearDnDContext(); myMousePressedEvent = e; EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); myExpectedCaretOffset = logicalPositionToOffset(myLastMousePressedLocation); try { for (EditorMouseListener mouseListener : myMouseListeners) { mouseListener.mousePressed(event); } } finally { myExpectedCaretOffset = -1; } if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA || event.getArea() == EditorMouseEventArea.FOLDING_OUTLINE_AREA && !isInsideGutterWhitespaceArea(e)) { myDragOnGutterSelectionStartLine = EditorUtil.yPositionToLogicalLine(EditorImpl.this, e); } // On some systems (for example on Linux) popup trigger is MOUSE_PRESSED event. // But this trigger is always consumed by popup handler. In that case we have to // also move caret. if (event.isConsumed() && !(event.getMouseEvent().isPopupTrigger() || event.getArea() == EditorMouseEventArea.EDITING_AREA)) { return; } if (myCommandProcessor != null) { Runnable runnable = () -> { if (processMousePressed(e) && myProject != null && !myProject.isDefault()) { IdeDocumentHistory.getInstance(myProject).includeCurrentCommandAsNavigation(); } }; myCommandProcessor .executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); } else { processMousePressed(e); } invokePopupIfNeeded(event); } private void runMouseClickedCommand(@NotNull final MouseEvent e) { EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); for (EditorMouseListener listener : myMouseListeners) { listener.mouseClicked(event); if (event.isConsumed()) { e.consume(); return; } } } private void runMouseReleasedCommand(@NotNull final MouseEvent e) { myMultiSelectionInProgress = false; myDragOnGutterSelectionStartLine = -1; myScrollingTimer.stop(); if (e.isConsumed()) { return; } EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); invokePopupIfNeeded(event); if (event.isConsumed()) { return; } for (EditorMouseListener listener : myMouseListeners) { listener.mouseReleased(event); if (event.isConsumed()) { e.consume(); return; } } if (myCommandProcessor != null) { Runnable runnable = () -> processMouseReleased(e); myCommandProcessor .executeCommand(myProject, runnable, "", DocCommandGroupId.noneGroupId(getDocument()), UndoConfirmationPolicy.DEFAULT, getDocument()); } else { processMouseReleased(e); } } private void runMouseEnteredCommand(@NotNull MouseEvent e) { EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); for (EditorMouseListener listener : myMouseListeners) { listener.mouseEntered(event); if (event.isConsumed()) { e.consume(); return; } } } private void runMouseExitedCommand(@NotNull MouseEvent e) { EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); for (EditorMouseListener listener : myMouseListeners) { listener.mouseExited(event); if (event.isConsumed()) { e.consume(); return; } } } private boolean processMousePressed(@NotNull final MouseEvent e) { myInitialMouseEvent = e; if (myMouseSelectionState != MOUSE_SELECTION_STATE_NONE && System.currentTimeMillis() - myMouseSelectionChangeTimestamp > Registry.intValue( "editor.mouseSelectionStateResetTimeout")) { resetMouseSelectionState(e); } int x = e.getX(); int y = e.getY(); if (x < 0) x = 0; if (y < 0) y = 0; final EditorMouseEventArea eventArea = getMouseEventArea(e); myMousePressArea = eventArea; if (eventArea == EditorMouseEventArea.FOLDING_OUTLINE_AREA) { final FoldRegion range = myGutterComponent.findFoldingAnchorAt(x, y); if (range != null) { final boolean expansion = !range.isExpanded(); int scrollShift = y - getScrollingModel().getVerticalScrollOffset(); Runnable processor = () -> { myFoldingModel.flushCaretShift(); range.setExpanded(expansion); if (e.isAltDown()) { for (FoldRegion region : myFoldingModel.getAllFoldRegions()) { if (region.getStartOffset() >= range.getStartOffset() && region.getEndOffset() <= range.getEndOffset()) { region.setExpanded(expansion); } } } }; getFoldingModel().runBatchFoldingOperation(processor); y = myGutterComponent.getHeadCenterY(range); getScrollingModel().scrollVertically(y - scrollShift); myGutterComponent.updateSize(); validateMousePointer(e); e.consume(); return false; } } if (e.getSource() == myGutterComponent) { if (eventArea == EditorMouseEventArea.LINE_MARKERS_AREA || eventArea == EditorMouseEventArea.ANNOTATIONS_AREA || eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA) { if (!tweakSelectionIfNecessary(e)) { myGutterComponent.mousePressed(e); } if (e.isConsumed()) return false; } x = 0; } int oldSelectionStart = mySelectionModel.getLeadSelectionOffset(); final int oldStart = mySelectionModel.getSelectionStart(); final int oldEnd = mySelectionModel.getSelectionEnd(); boolean toggleCaret = e.getSource() != myGutterComponent && isToggleCaretEvent(e); boolean lastPressCreatedCaret = myLastPressCreatedCaret; if (e.getClickCount() == 1) { myLastPressCreatedCaret = false; } // Don't move caret on mouse press above gutter line markers area (a place where break points, 'override', 'implements' etc icons // are drawn) and annotations area. E.g. we don't want to change caret position if a user sets new break point (clicks // at 'line markers' area). boolean insideEditorRelatedAreas = eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA || eventArea == EditorMouseEventArea.EDITING_AREA || isInsideGutterWhitespaceArea(e); if (insideEditorRelatedAreas) { VisualPosition visualPosition = getTargetPosition(x, y, true); LogicalPosition pos = visualToLogicalPosition(visualPosition); if (toggleCaret) { Caret caret = getCaretModel().getCaretAt(visualPosition); if (e.getClickCount() == 1) { if (caret == null) { myLastPressCreatedCaret = getCaretModel().addCaret(visualPosition) != null; } else { getCaretModel().removeCaret(caret); } } else if (e.getClickCount() == 3 && lastPressCreatedCaret) { getCaretModel().moveToVisualPosition(visualPosition); } } else if (e.getSource() != myGutterComponent && isCreateRectangularSelectionEvent(e)) { CaretState anchorCaretState = myCaretModel.getCaretsAndSelections().get(0); LogicalPosition anchor = Objects.equals(anchorCaretState.getCaretPosition(), anchorCaretState.getSelectionStart()) ? anchorCaretState.getSelectionEnd() : anchorCaretState.getSelectionStart(); if (anchor == null) anchor = myCaretModel.getLogicalPosition(); mySelectionModel.setBlockSelection(anchor, pos); } else { getCaretModel().removeSecondaryCarets(); getCaretModel().moveToVisualPosition(visualPosition); } } if (e.isPopupTrigger()) return false; requestFocus(); int caretOffset = getCaretModel().getOffset(); int newStart = mySelectionModel.getSelectionStart(); int newEnd = mySelectionModel.getSelectionEnd(); myMouseSelectedRegion = myFoldingModel.getFoldingPlaceholderAt(new Point(x, y)); myMousePressedInsideSelection = mySelectionModel.hasSelection() && caretOffset >= mySelectionModel.getSelectionStart() && caretOffset <= mySelectionModel.getSelectionEnd(); boolean isNavigation = oldStart == oldEnd && newStart == newEnd && oldStart != newStart; if (getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA && e.getClickCount() == 1) { mySelectionModel.selectLineAtCaret(); setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED); mySavedSelectionStart = mySelectionModel.getSelectionStart(); mySavedSelectionEnd = mySelectionModel.getSelectionEnd(); return isNavigation; } if (insideEditorRelatedAreas) { if (e.isShiftDown() && !e.isControlDown() && !e.isAltDown()) { if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (caretOffset < mySavedSelectionStart) { mySelectionModel.setSelection(mySavedSelectionEnd, caretOffset); } else { mySelectionModel.setSelection(mySavedSelectionStart, caretOffset); } } else { int startToUse = oldSelectionStart; if (mySelectionModel.isUnknownDirection() && caretOffset > startToUse) { startToUse = Math.min(oldStart, oldEnd); } mySelectionModel.setSelection(startToUse, caretOffset); } } else { if (!myMousePressedInsideSelection && getSelectionModel().hasSelection()) { setMouseSelectionState(MOUSE_SELECTION_STATE_NONE); mySelectionModel.setSelection(caretOffset, caretOffset); } else { if (e.getButton() == MouseEvent.BUTTON1 && (eventArea == EditorMouseEventArea.EDITING_AREA || eventArea == EditorMouseEventArea.LINE_NUMBERS_AREA) && (!toggleCaret || lastPressCreatedCaret)) { switch (e.getClickCount()) { case 2: selectWordAtCaret(mySettings.isMouseClickSelectionHonorsCamelWords() && mySettings.isCamelWords()); break; case 3: if (HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK && mySettings.isCamelWords()) { // We want to differentiate between triple and quadruple clicks when 'select by camel humps' is on. The former // is assumed to select 'hump' while the later points to the whole word. selectWordAtCaret(false); break; } //noinspection fallthrough case 4: mySelectionModel.selectLineAtCaret(); setMouseSelectionState(MOUSE_SELECTION_STATE_LINE_SELECTED); mySavedSelectionStart = mySelectionModel.getSelectionStart(); mySavedSelectionEnd = mySelectionModel.getSelectionEnd(); mySelectionModel.setUnknownDirection(true); break; } } } } } return isNavigation; } } private static boolean isColumnSelectionDragEvent(@NotNull MouseEvent e) { return e.isAltDown() && !e.isShiftDown() && !e.isControlDown() && !e.isMetaDown(); } private static boolean isToggleCaretEvent(@NotNull MouseEvent e) { return isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_OR_REMOVE_CARET) || isAddRectangularSelectionEvent(e); } private static boolean isAddRectangularSelectionEvent(@NotNull MouseEvent e) { return isMouseActionEvent(e, IdeActions.ACTION_EDITOR_ADD_RECTANGULAR_SELECTION_ON_MOUSE_DRAG); } private static boolean isCreateRectangularSelectionEvent(@NotNull MouseEvent e) { return isMouseActionEvent(e, IdeActions.ACTION_EDITOR_CREATE_RECTANGULAR_SELECTION); } private static boolean isMouseActionEvent(@NotNull MouseEvent e, String actionId) { KeymapManager keymapManager = KeymapManager.getInstance(); if (keymapManager == null) return false; Keymap keymap = keymapManager.getActiveKeymap(); if (keymap == null) return false; MouseShortcut mouseShortcut = KeymapUtil.createMouseShortcut(e); String[] mappedActions = keymap.getActionIds(mouseShortcut); if (!ArrayUtil.contains(actionId, mappedActions)) return false; if (mappedActions.length < 2) return true; ActionManager actionManager = ActionManager.getInstance(); for (String mappedActionId : mappedActions) { if (actionId.equals(mappedActionId)) continue; AnAction action = actionManager.getAction(mappedActionId); AnActionEvent actionEvent = AnActionEvent.createFromAnAction(action, e, ActionPlaces.MAIN_MENU, DataManager.getInstance().getDataContext(e.getComponent())); if (ActionUtil.lastUpdateAndCheckDumb(action, actionEvent, false)) return false; } return true; } private void selectWordAtCaret(boolean honorCamelCase) { mySelectionModel.selectWordAtCaret(honorCamelCase); setMouseSelectionState(MOUSE_SELECTION_STATE_WORD_SELECTED); mySavedSelectionStart = mySelectionModel.getSelectionStart(); mySavedSelectionEnd = mySelectionModel.getSelectionEnd(); getCaretModel().moveToOffset(mySavedSelectionEnd); } /** * Allows to answer if given event should tweak editor selection. * * @param e event for occurred mouse action * @return {@code true} if action that produces given event will trigger editor selection change; {@code false} otherwise */ private boolean tweakSelectionEvent(@NotNull MouseEvent e) { return getSelectionModel().hasSelection() && e.getButton() == MouseEvent.BUTTON1 && e.isShiftDown() && getMouseEventArea(e) == EditorMouseEventArea.LINE_NUMBERS_AREA; } /** * Checks if editor selection should be changed because of click at the given point at gutter and proceeds if necessary. * <p/> * The main idea is that selection can be changed during left mouse clicks on the gutter line numbers area with hold * {@code Shift} button. The selection should be adjusted if necessary. * * @param e event for mouse click on gutter area * @return {@code true} if editor's selection is changed because of the click; {@code false} otherwise */ private boolean tweakSelectionIfNecessary(@NotNull MouseEvent e) { if (!tweakSelectionEvent(e)) { return false; } int startSelectionOffset = getSelectionModel().getSelectionStart(); int startVisLine = offsetToVisualLine(startSelectionOffset); int endSelectionOffset = getSelectionModel().getSelectionEnd(); int endVisLine = offsetToVisualLine(endSelectionOffset - 1); int clickVisLine = yToVisibleLine(e.getPoint().y); if (clickVisLine < startVisLine) { // Expand selection at backward direction. int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0))); getSelectionModel().setSelection(startOffset, endSelectionOffset); getCaretModel().moveToOffset(startOffset); } else if (clickVisLine > endVisLine) { // Expand selection at forward direction. int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine); getSelectionModel().setSelection(getSelectionModel().getSelectionStart(), endLineOffset); getCaretModel().moveToOffset(endLineOffset, true); } else if (startVisLine == endVisLine) { // Remove selection getSelectionModel().removeSelection(); } else { // Reduce selection in backward direction. if (getSelectionModel().getLeadSelectionOffset() == endSelectionOffset) { if (clickVisLine == startVisLine) { clickVisLine++; } int startOffset = logicalPositionToOffset(visualToLogicalPosition(new VisualPosition(clickVisLine, 0))); getSelectionModel().setSelection(startOffset, endSelectionOffset); getCaretModel().moveToOffset(startOffset); } else { // Reduce selection is forward direction. if (clickVisLine == endVisLine) { clickVisLine--; } int endLineOffset = EditorUtil.getVisualLineEndOffset(this, clickVisLine); getSelectionModel().setSelection(startSelectionOffset, endLineOffset); getCaretModel().moveToOffset(endLineOffset); } } e.consume(); return true; } boolean useEditorAntialiasing() { return myUseEditorAntialiasing; } public void setUseEditorAntialiasing(boolean value) { myUseEditorAntialiasing = value; } private static final TooltipGroup FOLDING_TOOLTIP_GROUP = new TooltipGroup("FOLDING_TOOLTIP_GROUP", 10); private class MyMouseMotionListener implements MouseMotionListener { @Override public void mouseDragged(@NotNull MouseEvent e) { if (myDraggedRange != null || myGutterComponent.myDnDInProgress) return; // on Mac we receive events even if drag-n-drop is in progress validateMousePointer(e); ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> runMouseDraggedCommand(e)); EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (event.getArea() == EditorMouseEventArea.LINE_MARKERS_AREA) { myGutterComponent.mouseDragged(e); } for (EditorMouseMotionListener listener : myMouseMotionListeners) { listener.mouseDragged(event); } } @Override public void mouseMoved(@NotNull MouseEvent e) { if (getMouseSelectionState() != MOUSE_SELECTION_STATE_NONE) { if (myMousePressedEvent != null && myMousePressedEvent.getComponent() == e.getComponent()) { Point lastPoint = myMousePressedEvent.getPoint(); Point point = e.getPoint(); int deadZone = Registry.intValue("editor.mouseSelectionStateResetDeadZone"); if (Math.abs(lastPoint.x - point.x) >= deadZone || Math.abs(lastPoint.y - point.y) >= deadZone) { resetMouseSelectionState(e); } } else { validateMousePointer(e); } } else { validateMousePointer(e); } myMouseMovedEvent = e; EditorMouseEvent event = new EditorMouseEvent(EditorImpl.this, e, getMouseEventArea(e)); if (e.getSource() == myGutterComponent) { myGutterComponent.mouseMoved(e); } if (event.getArea() == EditorMouseEventArea.EDITING_AREA) { FoldRegion fold = myFoldingModel.getFoldingPlaceholderAt(e.getPoint()); TooltipController controller = TooltipController.getInstance(); if (fold != null && !fold.shouldNeverExpand()) { DocumentFragment range = createDocumentFragment(fold); final Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getPoint(), getComponent().getRootPane().getLayeredPane()); controller.showTooltip(EditorImpl.this, p, new DocumentFragmentTooltipRenderer(range), false, FOLDING_TOOLTIP_GROUP); } else { controller.cancelTooltip(FOLDING_TOOLTIP_GROUP, e, true); } } for (EditorMouseMotionListener listener : myMouseMotionListeners) { listener.mouseMoved(event); } } @NotNull private DocumentFragment createDocumentFragment(@NotNull FoldRegion fold) { final FoldingGroup group = fold.getGroup(); final int foldStart = fold.getStartOffset(); if (group != null) { final int endOffset = myFoldingModel.getEndOffset(group); if (offsetToVisualLine(endOffset) == offsetToVisualLine(foldStart)) { return new DocumentFragment(myDocument, foldStart, endOffset); } } final int oldEnd = fold.getEndOffset(); return new DocumentFragment(myDocument, foldStart, oldEnd); } } private class MyColorSchemeDelegate extends DelegateColorScheme { private final FontPreferencesImpl myFontPreferences = new FontPreferencesImpl(); private final FontPreferencesImpl myConsoleFontPreferences = new FontPreferencesImpl(); private final Map<TextAttributesKey, TextAttributes> myOwnAttributes = ContainerUtilRt.newHashMap(); private final Map<ColorKey, Color> myOwnColors = ContainerUtilRt.newHashMap(); private final EditorColorsScheme myCustomGlobalScheme; private Map<EditorFontType, Font> myFontsMap; private int myMaxFontSize = EditorFontsConstants.getMaxEditorFontSize(); private int myFontSize = -1; private int myConsoleFontSize = -1; private String myFaceName; private MyColorSchemeDelegate(@Nullable EditorColorsScheme globalScheme) { super(globalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : globalScheme); myCustomGlobalScheme = globalScheme; updateGlobalScheme(); } private void reinitFonts() { EditorColorsScheme delegate = getDelegate(); String editorFontName = getEditorFontName(); int editorFontSize = getEditorFontSize(); updatePreferences(myFontPreferences, editorFontName, editorFontSize, delegate == null ? null : delegate.getFontPreferences()); String consoleFontName = getConsoleFontName(); int consoleFontSize = getConsoleFontSize(); updatePreferences(myConsoleFontPreferences, consoleFontName, consoleFontSize, delegate == null ? null : delegate.getConsoleFontPreferences()); myFontsMap = new EnumMap<>(EditorFontType.class); myFontsMap.put(EditorFontType.PLAIN, new Font(editorFontName, Font.PLAIN, editorFontSize)); myFontsMap.put(EditorFontType.BOLD, new Font(editorFontName, Font.BOLD, editorFontSize)); myFontsMap.put(EditorFontType.ITALIC, new Font(editorFontName, Font.ITALIC, editorFontSize)); myFontsMap.put(EditorFontType.BOLD_ITALIC, new Font(editorFontName, Font.BOLD | Font.ITALIC, editorFontSize)); myFontsMap.put(EditorFontType.CONSOLE_PLAIN, new Font(consoleFontName, Font.PLAIN, consoleFontSize)); myFontsMap.put(EditorFontType.CONSOLE_BOLD, new Font(consoleFontName, Font.BOLD, consoleFontSize)); myFontsMap.put(EditorFontType.CONSOLE_ITALIC, new Font(consoleFontName, Font.ITALIC, consoleFontSize)); myFontsMap.put(EditorFontType.CONSOLE_BOLD_ITALIC, new Font(consoleFontName, Font.BOLD | Font.ITALIC, consoleFontSize)); } private void updatePreferences(FontPreferencesImpl preferences, String fontName, int fontSize, FontPreferences delegatePreferences) { preferences.clear(); preferences.register(fontName, fontSize); if (delegatePreferences != null) { boolean first = true; //skip delegate's primary font for (String font : delegatePreferences.getRealFontFamilies()) { if (!first) { preferences.register(font, fontSize); } first = false; } } preferences.setUseLigatures(delegatePreferences != null && delegatePreferences.useLigatures()); } private void reinitFontsAndSettings() { reinitFonts(); reinitSettings(); } @Override public TextAttributes getAttributes(TextAttributesKey key) { if (myOwnAttributes.containsKey(key)) return myOwnAttributes.get(key); return getDelegate().getAttributes(key); } @Override public void setAttributes(@NotNull TextAttributesKey key, TextAttributes attributes) { myOwnAttributes.put(key, attributes); } @Nullable @Override public Color getColor(ColorKey key) { if (myOwnColors.containsKey(key)) return myOwnColors.get(key); return getDelegate().getColor(key); } @Override public void setColor(ColorKey key, Color color) { myOwnColors.put(key, color); // These two are here because those attributes are cached and I do not whant the clients to call editor's reinit // settings in this case. myCaretModel.reinitSettings(); mySelectionModel.reinitSettings(); } @Override public int getEditorFontSize() { if (myFontSize == -1) { return getDelegate().getEditorFontSize(); } return myFontSize; } @Override public void setEditorFontSize(int fontSize) { if (fontSize < MIN_FONT_SIZE) fontSize = MIN_FONT_SIZE; if (fontSize > myMaxFontSize) fontSize = myMaxFontSize; if (fontSize == myFontSize) return; myFontSize = fontSize; reinitFontsAndSettings(); } @NotNull @Override public FontPreferences getFontPreferences() { return myFontPreferences.getEffectiveFontFamilies().isEmpty() ? getDelegate().getFontPreferences() : myFontPreferences; } @Override public void setFontPreferences(@NotNull FontPreferences preferences) { if (Comparing.equal(preferences, myFontPreferences)) return; preferences.copyTo(myFontPreferences); reinitFontsAndSettings(); } @NotNull @Override public FontPreferences getConsoleFontPreferences() { return myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty() ? getDelegate().getConsoleFontPreferences() : myConsoleFontPreferences; } @Override public void setConsoleFontPreferences(@NotNull FontPreferences preferences) { if (Comparing.equal(preferences, myConsoleFontPreferences)) return; preferences.copyTo(myConsoleFontPreferences); reinitFontsAndSettings(); } @Override public String getEditorFontName() { if (myFaceName == null) { return getDelegate().getEditorFontName(); } return myFaceName; } @Override public void setEditorFontName(String fontName) { if (Comparing.equal(fontName, myFaceName)) return; myFaceName = fontName; reinitFontsAndSettings(); } @NotNull @Override public Font getFont(EditorFontType key) { if (myFontsMap != null) { Font font = myFontsMap.get(key); if (font != null) return font; } return getDelegate().getFont(key); } @Override public void setFont(EditorFontType key, Font font) { if (myFontsMap == null) { reinitFontsAndSettings(); } myFontsMap.put(key, font); reinitSettings(); } @Override @Nullable public Object clone() { return null; } private void updateGlobalScheme() { setDelegate(myCustomGlobalScheme == null ? EditorColorsManager.getInstance().getGlobalScheme() : myCustomGlobalScheme); } @Override public void setDelegate(@NotNull EditorColorsScheme delegate) { super.setDelegate(delegate); int globalFontSize = getDelegate().getEditorFontSize(); myMaxFontSize = Math.max(EditorFontsConstants.getMaxEditorFontSize(), globalFontSize); reinitFonts(); } @Override public void setConsoleFontSize(int fontSize) { myConsoleFontSize = fontSize; reinitFontsAndSettings(); } @Override public int getConsoleFontSize() { return myConsoleFontSize == -1 ? super.getConsoleFontSize() : myConsoleFontSize; } } private static class ExplosionPainter extends AbstractPainter { private final Point myExplosionLocation; private final Image myImage; private static final long TIME_PER_FRAME = 30; private final int myWidth; private final int myHeight; private long lastRepaintTime = System.currentTimeMillis(); private int frameIndex; private static final int TOTAL_FRAMES = 8; private final AtomicBoolean nrp = new AtomicBoolean(true); ExplosionPainter(final Point explosionLocation, Image image) { myExplosionLocation = new Point(explosionLocation.x, explosionLocation.y); myImage = image; myWidth = myImage.getWidth(null); myHeight = myImage.getHeight(null); } @Override public void executePaint(Component component, Graphics2D g) { if (!nrp.get()) return; long currentTimeMillis = System.currentTimeMillis(); float alpha = 1 - (float)frameIndex / TOTAL_FRAMES; g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); Image scaledImage = ImageUtil.scaleImage(myImage, alpha); int x = myExplosionLocation.x - scaledImage.getWidth(null) / 2; int y = myExplosionLocation.y - scaledImage.getHeight(null) / 2; if (currentTimeMillis - lastRepaintTime < TIME_PER_FRAME) { UIUtil.drawImage(g, scaledImage, x, y, null); JobScheduler.getScheduler().schedule(() -> component.repaint(x, y, myWidth, myHeight), TIME_PER_FRAME, TimeUnit.MILLISECONDS); return; } lastRepaintTime = currentTimeMillis; frameIndex++; UIUtil.drawImage(g, scaledImage, x, y, null); if (frameIndex == TOTAL_FRAMES) { nrp.set(false); IdeGlassPane glassPane = IdeGlassPaneUtil.find(component); ApplicationManager.getApplication().invokeLater(() -> glassPane.removePainter(this)); component.repaint(x, y, myWidth, myHeight); } component.repaint(x, y, myWidth, myHeight); } @Override public boolean needsRepaint() { return nrp.get(); } } static boolean handleDrop(@NotNull EditorImpl editor, @NotNull final Transferable t, int dropAction) { final EditorDropHandler dropHandler = editor.getDropHandler(); if (Registry.is("debugger.click.disable.breakpoints")) { try { if (t.isDataFlavorSupported(GutterDraggableObject.flavor)) { Object attachedObject = t.getTransferData(GutterDraggableObject.flavor); if (attachedObject instanceof GutterIconRenderer) { GutterDraggableObject object = ((GutterIconRenderer)attachedObject).getDraggableObject(); if (object != null) { object.remove(); Point mouseLocationOnScreen = MouseInfo.getPointerInfo().getLocation(); JComponent editorComponent = editor.getComponent(); Point editorComponentLocationOnScreen = editorComponent.getLocationOnScreen(); IdeGlassPaneUtil.installPainter( editorComponent, new ExplosionPainter( new Point( mouseLocationOnScreen.x - editorComponentLocationOnScreen.x, mouseLocationOnScreen.y - editorComponentLocationOnScreen.y ), editor.getGutterComponentEx().getDragImage((GutterIconRenderer)attachedObject) ), editor.getDisposable() ); return true; } } } } catch (UnsupportedFlavorException | IOException e) { LOG.warn(e); } } if (dropHandler != null && dropHandler.canHandleDrop(t.getTransferDataFlavors())) { dropHandler.handleDrop(t, editor.getProject(), null, dropAction); return true; } final int caretOffset = editor.getCaretModel().getOffset(); if (editor.myDraggedRange != null && editor.myDraggedRange.getStartOffset() <= caretOffset && caretOffset < editor.myDraggedRange.getEndOffset()) { return false; } if (editor.myDraggedRange != null) { editor.getCaretModel().moveToOffset(editor.mySavedCaretOffsetForDNDUndoHack); } CommandProcessor.getInstance().executeCommand(editor.myProject, () -> { try { editor.getSelectionModel().removeSelection(); final int offset; if (editor.myDraggedRange != null) { editor.getCaretModel().moveToOffset(caretOffset); offset = caretOffset; } else { offset = editor.getCaretModel().getOffset(); } if (editor.getDocument().getRangeGuard(offset, offset) != null) { return; } editor.putUserData(LAST_PASTED_REGION, null); EditorActionHandler pasteHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_PASTE); LOG.assertTrue(pasteHandler instanceof EditorTextInsertHandler, String.valueOf(pasteHandler)); ((EditorTextInsertHandler)pasteHandler).execute(editor, editor.getDataContext(), () -> t); TextRange range = editor.getUserData(LAST_PASTED_REGION); if (range != null) { editor.getCaretModel().moveToOffset(range.getStartOffset()); editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset()); } } catch (Exception exception) { LOG.error(exception); } }, EditorBundle.message("paste.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); return true; } private static class MyTransferHandler extends TransferHandler { private static EditorImpl getEditor(@NotNull JComponent comp) { EditorComponentImpl editorComponent = (EditorComponentImpl)comp; return editorComponent.getEditor(); } @Override public boolean importData(TransferSupport support) { Component comp = support.getComponent(); return comp instanceof JComponent && handleDrop(getEditor((JComponent)comp), support.getTransferable(), support.getDropAction()); } @Override public boolean canImport(@NotNull JComponent comp, @NotNull DataFlavor[] transferFlavors) { Editor editor = getEditor(comp); final EditorDropHandler dropHandler = ((EditorImpl)editor).getDropHandler(); if (dropHandler != null && dropHandler.canHandleDrop(transferFlavors)) { return true; } //should be used a better representation class if (Registry.is("debugger.click.disable.breakpoints") && ArrayUtil.contains(GutterDraggableObject.flavor, transferFlavors)) { return true; } if (editor.isViewer()) return false; int offset = editor.getCaretModel().getOffset(); if (editor.getDocument().getRangeGuard(offset, offset) != null) return false; return ArrayUtil.contains(DataFlavor.stringFlavor, transferFlavors); } @Override @Nullable protected Transferable createTransferable(JComponent c) { EditorImpl editor = getEditor(c); String s = editor.getSelectionModel().getSelectedText(); if (s == null) return null; int selectionStart = editor.getSelectionModel().getSelectionStart(); int selectionEnd = editor.getSelectionModel().getSelectionEnd(); editor.myDraggedRange = editor.getDocument().createRangeMarker(selectionStart, selectionEnd); return new StringSelection(s); } @Override public int getSourceActions(@NotNull JComponent c) { return COPY_OR_MOVE; } @Override protected void exportDone(@NotNull final JComponent source, @Nullable Transferable data, int action) { if (data == null) return; final Component last = DnDManager.getInstance().getLastDropHandler(); if (last != null && !(last instanceof EditorComponentImpl) && !(last instanceof EditorGutterComponentImpl)) return; final EditorImpl editor = getEditor(source); if (action == MOVE && !editor.isViewer() && editor.myDraggedRange != null) { ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(() -> removeDraggedOutFragment(editor)); } editor.clearDnDContext(); } private static void removeDraggedOutFragment(EditorImpl editor) { if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), editor.getProject())) { return; } CommandProcessor.getInstance().executeCommand(editor.myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { Document doc = editor.getDocument(); doc.startGuardedBlockChecking(); try { doc.deleteString(editor.myDraggedRange.getStartOffset(), editor.myDraggedRange.getEndOffset()); } catch (ReadOnlyFragmentModificationException e) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e); } finally { doc.stopGuardedBlockChecking(); } }), EditorBundle.message("move.selection.command.name"), DND_COMMAND_KEY, UndoConfirmationPolicy.DEFAULT, editor.getDocument()); } } private class EditorDocumentAdapter implements PrioritizedDocumentListener { @Override public void beforeDocumentChange(@NotNull DocumentEvent e) { beforeChangedUpdate(); } @Override public void documentChanged(@NotNull DocumentEvent e) { changedUpdate(e); } @Override public int getPriority() { return EditorDocumentPriorities.EDITOR_DOCUMENT_ADAPTER; } } private class EditorDocumentBulkUpdateAdapter implements DocumentBulkUpdateListener { @Override public void updateStarted(@NotNull Document doc) { if (doc != getDocument()) return; bulkUpdateStarted(); } @Override public void updateFinished(@NotNull Document doc) { if (doc != getDocument()) return; bulkUpdateFinished(); } } @Override @NotNull public EditorGutter getGutter() { return getGutterComponentEx(); } @Override public int calcColumnNumber(@NotNull CharSequence text, int start, int offset, int tabSize) { return myView.offsetToLogicalPosition(offset).column; } public boolean isInDistractionFreeMode() { return EditorUtil.isRealFileEditor(this) && (Registry.is("editor.distraction.free.mode") || isInPresentationMode()); } boolean isInPresentationMode() { return UISettings.getInstance().getPresentationMode() && EditorUtil.isRealFileEditor(this); } @Override public void putInfo(@NotNull Map<String, String> info) { final VisualPosition visual = getCaretModel().getVisualPosition(); info.put("caret", visual.getLine() + ":" + visual.getColumn()); } private void invokePopupIfNeeded(EditorMouseEvent event) { if (myContextMenuGroupId != null && event.getArea() == EditorMouseEventArea.EDITING_AREA && event.getMouseEvent().isPopupTrigger() && !event.isConsumed()) { String contextMenuGroupId = myContextMenuGroupId; Inlay inlay = myInlayModel.getElementAt(event.getMouseEvent().getPoint()); if (inlay != null) { String inlayContextMenuGroupId = inlay.getRenderer().getContextMenuGroupId(); if (inlayContextMenuGroupId != null) contextMenuGroupId = inlayContextMenuGroupId; } AnAction action = CustomActionsSchema.getInstance().getCorrectedAction(contextMenuGroupId); if (action instanceof ActionGroup) { ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ActionPlaces.EDITOR_POPUP, (ActionGroup)action); MouseEvent e = event.getMouseEvent(); final Component c = e.getComponent(); if (c != null && c.isShowing()) { popupMenu.getComponent().show(c, e.getX(), e.getY()); } e.consume(); } } } @TestOnly void validateState() { myView.validateState(); mySoftWrapModel.validateState(); myFoldingModel.validateState(); myCaretModel.validateState(); myInlayModel.validateState(); } private class MyScrollPane extends JBScrollPane { private MyScrollPane() { super(0); setupCorners(); } @Override public void setUI(ScrollPaneUI ui) { super.setUI(ui); // disable standard Swing keybindings setInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); } @Override public void layout() { if (isInDistractionFreeMode()) { // re-calc gutter extra size after editor size is set // & layout once again to avoid blinking myGutterComponent.updateSize(true, true); } super.layout(); } @Override protected void processMouseWheelEvent(@NotNull MouseWheelEvent e) { if (mySettings.isWheelFontChangeEnabled()) { if (EditorUtil.isChangeFontSize(e)) { int size = myScheme.getEditorFontSize() - e.getWheelRotation(); if (size >= MIN_FONT_SIZE) { setFontSize(size, SwingUtilities.convertPoint(this, e.getPoint(), getViewport())); } return; } } super.processMouseWheelEvent(e); } @NotNull @Override public JScrollBar createHorizontalScrollBar() { return new OpaqueAwareScrollBar(Adjustable.HORIZONTAL); } @NotNull @Override public JScrollBar createVerticalScrollBar() { return new MyScrollBar(Adjustable.VERTICAL); } @Override protected void setupCorners() { super.setupCorners(); setBorder(new TablessBorder()); } } private class TablessBorder extends SideBorder { private TablessBorder() { super(JBColor.border(), SideBorder.ALL); } @Override public void paintBorder(@NotNull Component c, @NotNull Graphics g, int x, int y, int width, int height) { if (c instanceof JComponent) { Insets insets = ((JComponent)c).getInsets(); if (insets.left > 0) { super.paintBorder(c, g, x, y, width, height); } else { g.setColor(UIUtil.getPanelBackground()); g.fillRect(x, y, width, 1); g.setColor(Gray._50.withAlpha(90)); g.fillRect(x, y, width, 1); } } } @NotNull @Override public Insets getBorderInsets(Component c) { Container splitters = SwingUtilities.getAncestorOfClass(EditorsSplitters.class, c); boolean thereIsSomethingAbove = !SystemInfo.isMac || UISettings.getInstance().getShowMainToolbar() || UISettings.getInstance().getShowNavigationBar() || toolWindowIsNotEmpty(); //noinspection ConstantConditions Component header = myHeaderPanel == null ? null : ArrayUtil.getFirstElement(myHeaderPanel.getComponents()); boolean paintTop = thereIsSomethingAbove && header == null && UISettings.getInstance().getEditorTabPlacement() != SwingConstants.TOP; return splitters == null ? super.getBorderInsets(c) : new Insets(paintTop ? 1 : 0, 0, 0, 0); } private boolean toolWindowIsNotEmpty() { if (myProject == null) return false; ToolWindowManagerEx m = ToolWindowManagerEx.getInstanceEx(myProject); return m != null && !m.getIdsOn(ToolWindowAnchor.TOP).isEmpty(); } @Override public boolean isBorderOpaque() { return true; } } private class MyHeaderPanel extends JPanel { private int myOldHeight; private MyHeaderPanel() { super(new BorderLayout()); } @Override public void revalidate() { myOldHeight = getHeight(); super.revalidate(); } @Override protected void validateTree() { int height = myOldHeight; super.validateTree(); height -= getHeight(); if (height != 0 && !(myOldHeight == 0 && getComponentCount() > 0 && getPermanentHeaderComponent() == getComponent(0))) { myVerticalScrollBar.setValue(myVerticalScrollBar.getValue() - height); } myOldHeight = getHeight(); } } private class MyTextDrawingCallback implements TextDrawingCallback { @Override public void drawChars(@NotNull Graphics g, @NotNull char[] data, int start, int end, int x, int y, Color color, @NotNull FontInfo fontInfo) { myView.drawChars(g, data, start, end, x, y, color, fontInfo); } } private static class NullEditorHighlighter extends EmptyEditorHighlighter { private static final TextAttributes NULL_ATTRIBUTES = new TextAttributes(); NullEditorHighlighter() { super(NULL_ATTRIBUTES); } @Override public void setAttributes(TextAttributes attributes) {} @Override public void setColorScheme(@NotNull EditorColorsScheme scheme) {} } }
background-aware painting in editor dumb mode (3)
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
background-aware painting in editor dumb mode (3)
<ide><path>latform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java <ide> Rectangle rect = ((JViewport)myEditorComponent.getParent()).getViewRect(); <ide> // The LCD text loop is enabled only for opaque images <ide> BufferedImage image = UIUtil.createImage(myEditorComponent, rect.width, rect.height, BufferedImage.TYPE_INT_RGB); <del> Graphics2D graphics = JBSwingUtilities.runGlobalCGTransform(myEditorComponent, image.createGraphics()); <del> graphics.translate(-rect.x, -rect.y); <add> Graphics imageGraphics = image.createGraphics(); <add> imageGraphics.translate(-rect.x, -rect.y); <add> Graphics2D graphics = JBSwingUtilities.runGlobalCGTransform(myEditorComponent, imageGraphics); <ide> graphics.setClip(rect.x, rect.y, rect.width, rect.height); <ide> myEditorComponent.paintComponent(graphics); <ide> graphics.dispose(); <ide> @NotNull <ide> @Override <ide> public FontPreferences getConsoleFontPreferences() { <del> return myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty() ? <add> return myConsoleFontPreferences.getEffectiveFontFamilies().isEmpty() ? <ide> getDelegate().getConsoleFontPreferences() : myConsoleFontPreferences; <ide> } <ide>
Java
apache-2.0
0dc1883b7430b2d5212b4eff694a0732d3ba5132
0
jphp-compiler/jphp,jphp-compiler/jphp,jphp-compiler/jphp,jphp-compiler/jphp
package org.develnext.jphp.core.compiler.jvm.statement; import org.develnext.jphp.core.compiler.common.ASMExpression; import org.develnext.jphp.core.compiler.common.misc.StackItem; import org.develnext.jphp.core.compiler.common.util.CompilerUtils; import org.develnext.jphp.core.compiler.jvm.Constants; import org.develnext.jphp.core.compiler.jvm.JvmCompiler; import org.develnext.jphp.core.compiler.jvm.misc.LocalVariable; import org.develnext.jphp.core.compiler.jvm.statement.expr.*; import org.develnext.jphp.core.compiler.jvm.statement.expr.operator.DynamicAccessCompiler; import org.develnext.jphp.core.compiler.jvm.statement.expr.operator.InstanceOfCompiler; import org.develnext.jphp.core.compiler.jvm.statement.expr.value.*; import org.develnext.jphp.core.tokenizer.TokenMeta; import org.develnext.jphp.core.tokenizer.token.OpenEchoTagToken; import org.develnext.jphp.core.tokenizer.token.Token; import org.develnext.jphp.core.tokenizer.token.expr.ClassExprToken; import org.develnext.jphp.core.tokenizer.token.expr.OperatorExprToken; import org.develnext.jphp.core.tokenizer.token.expr.ValueExprToken; import org.develnext.jphp.core.tokenizer.token.expr.operator.*; import org.develnext.jphp.core.tokenizer.token.expr.value.*; import org.develnext.jphp.core.tokenizer.token.expr.value.macro.*; import org.develnext.jphp.core.tokenizer.token.stmt.*; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import php.runtime.Memory; import php.runtime.OperatorUtils; import php.runtime.annotation.Runtime; import php.runtime.common.Association; import php.runtime.common.Messages; import php.runtime.common.StringUtils; import php.runtime.env.Environment; import php.runtime.env.TraceInfo; import php.runtime.exceptions.CriticalException; import php.runtime.ext.support.compile.CompileClass; import php.runtime.ext.support.compile.CompileConstant; import php.runtime.ext.support.compile.CompileFunction; import php.runtime.invoke.InvokeHelper; import php.runtime.invoke.ObjectInvokeHelper; import php.runtime.invoke.cache.FunctionCallCache; import php.runtime.invoke.cache.MethodCallCache; import php.runtime.lang.ForeachIterator; import php.runtime.lang.IObject; import php.runtime.memory.*; import php.runtime.memory.helper.UndefinedMemory; import php.runtime.memory.support.MemoryUtils; import php.runtime.reflection.*; import php.runtime.reflection.support.Entity; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import static org.objectweb.asm.Opcodes.*; public class ExpressionStmtCompiler extends StmtCompiler { protected final MethodStmtCompiler method; protected final MethodStmtToken methodStatement; protected final ExprStmtToken expression; private MethodNode node; private InsnList code; private Stack<Integer> exprStackInit = new Stack<Integer>(); private int lastLineNumber = -1; private Map<Class<? extends Token>, BaseStatementCompiler> compilers; private static final Map<Class<? extends Token>, Class<? extends BaseStatementCompiler>> compilerRules; static { compilerRules = new HashMap<Class<? extends Token>, Class<? extends BaseStatementCompiler>>(); compilerRules.put(IfStmtToken.class, IfElseCompiler.class); compilerRules.put(SwitchStmtToken.class, SwitchCompiler.class); compilerRules.put(FunctionStmtToken.class, FunctionCompiler.class); compilerRules.put(EchoRawToken.class, EchoRawCompiler.class); compilerRules.put(EchoStmtToken.class, EchoCompiler.class); compilerRules.put(OpenEchoTagToken.class, OpenEchoTagCompiler.class); compilerRules.put(ReturnStmtToken.class, ReturnCompiler.class); compilerRules.put(BodyStmtToken.class, BodyCompiler.class); compilerRules.put(WhileStmtToken.class, WhileCompiler.class); compilerRules.put(DoStmtToken.class, DoCompiler.class); compilerRules.put(ForStmtToken.class, ForCompiler.class); compilerRules.put(ForeachStmtToken.class, ForeachCompiler.class); compilerRules.put(TryStmtToken.class, TryCatchCompiler.class); compilerRules.put(ThrowStmtToken.class, ThrowCompiler.class); compilerRules.put(BreakStmtToken.class, JumpCompiler.class); compilerRules.put(ContinueStmtToken.class, JumpCompiler.class); compilerRules.put(GotoStmtToken.class, GotoCompiler.class); compilerRules.put(LabelStmtToken.class, GotoLabelCompiler.class); compilerRules.put(GlobalStmtToken.class, GlobalDefinitionCompiler.class); compilerRules.put(StaticStmtToken.class, StaticDefinitionCompiler.class); compilerRules.put(JvmCompiler.ClassInitEnvironment.class, ClassInitEnvironmentCompiler.class); // values compilerRules.put(BooleanExprToken.class, BooleanValueCompiler.class); compilerRules.put(IntegerExprToken.class, IntValueCompiler.class); compilerRules.put(NullExprToken.class, NullValueCompiler.class); compilerRules.put(DoubleExprToken.class, DoubleValueCompiler.class); compilerRules.put(StringExprToken.class, StringValueCompiler.class); compilerRules.put(ShellExecExprToken.class, ShellExecValueCompiler.class); compilerRules.put(IncludeExprToken.class, ImportCompiler.class); compilerRules.put(IncludeOnceExprToken.class, ImportCompiler.class); compilerRules.put(RequireExprToken.class, ImportCompiler.class); compilerRules.put(RequireOnceExprToken.class, ImportCompiler.class); compilerRules.put(NewExprToken.class, NewValueCompiler.class); compilerRules.put(StringBuilderExprToken.class, StringBuilderValueCompiler.class); compilerRules.put(UnsetExprToken.class, UnsetCompiler.class); compilerRules.put(IssetExprToken.class, IssetCompiler.class); compilerRules.put(EmptyExprToken.class, EmptyCompiler.class); compilerRules.put(DieExprToken.class, DieCompiler.class); compilerRules.put(StaticExprToken.class, StaticValueCompiler.class); compilerRules.put(ClosureStmtToken.class, ClosureValueCompiler.class); compilerRules.put(GetVarExprToken.class, VarVarValueCompiler.class); compilerRules.put(SelfExprToken.class, SelfValueCompiler.class); compilerRules.put(StaticAccessExprToken.class, StaticAccessValueCompiler.class); compilerRules.put(StaticAccessIssetExprToken.class, StaticAccessValueCompiler.class); compilerRules.put(StaticAccessUnsetExprToken.class, StaticAccessValueCompiler.class); compilerRules.put(ListExprToken.class, ListCompiler.class); compilerRules.put(YieldExprToken.class, YieldValueCompiler.class); // operation compilerRules.put(InstanceofExprToken.class, InstanceOfCompiler.class); compilerRules.put(DynamicAccessAssignExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessEmptyExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessGetRefExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessIssetExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessUnsetExprToken.class, DynamicAccessCompiler.class); compilerRules.put(StaticAccessOperatorExprToken.class, StaticAccessValueAsOperatorCompiler.class); } public ExpressionStmtCompiler(MethodStmtCompiler method, ExprStmtToken expression) { super(method.getCompiler()); this.method = method; this.expression = expression; this.node = method.node; this.code = method.node.instructions; this.methodStatement = method.statement != null ? method.statement : MethodStmtToken.of("", method.clazz.statement); } public ExpressionStmtCompiler(JvmCompiler compiler) { super(compiler); this.expression = null; ClassStmtCompiler classStmtCompiler = new ClassStmtCompiler( compiler, new ClassStmtToken(new TokenMeta("", 0, 0, 0, 0)) ); this.method = new MethodStmtCompiler(classStmtCompiler, (MethodStmtToken) null); this.methodStatement = method.statement != null ? method.statement : MethodStmtToken.of("", method.clazz.statement); this.node = method.node; this.code = method.node.instructions; } @SuppressWarnings("unchecked") public <T extends Token> T write(Class<? extends Token> clazz, T token) { BaseStatementCompiler<T> cmp = (BaseStatementCompiler<T>) getCompiler(clazz); if (cmp == null) throw new CriticalException("Cannot find compiler for " + clazz.getName()); cmp.write(token); return token; } @SuppressWarnings("unchecked") public <T extends Token> T write(T token) { if (token == null) throw new IllegalArgumentException("Token cannot be null"); return write(token.getClass(), token); } @SuppressWarnings("unchecked") public <T extends ValueExprToken> T writeValue(T token, boolean returnValue) { BaseStatementCompiler<T> cmp = (BaseStatementCompiler<T>) getCompiler(token.getClass()); if (cmp == null) throw new CriticalException("Cannot find compiler for " + token.getClass().getName()); if (cmp instanceof BaseExprCompiler) ((BaseExprCompiler) cmp).write(token, returnValue); else throw new CriticalException("Compiler is not for values"); return token; } @SuppressWarnings("unchecked") public <T extends Token> BaseStatementCompiler<T> getCompiler(Class<T> clazz) { if (compilers == null) { compilers = new HashMap<Class<? extends Token>, BaseStatementCompiler>(); } BaseStatementCompiler<T> r = compilers.get(clazz); if (r != null) return r; Class<? extends BaseStatementCompiler<T>> rule = (Class<? extends BaseStatementCompiler<T>>) compilerRules.get(clazz); if (rule == null) return null; try { r = rule.getConstructor(ExpressionStmtCompiler.class).newInstance(this); compilers.put(clazz, r); return r; } catch (Exception e) { throw new CriticalException(e); } } public MethodNode getMethodNode() { return node; } public MethodStmtCompiler getMethod() { return method; } public MethodStmtToken getMethodStatement() { return methodStatement; } public void makeVarStore(LocalVariable variable) { code.add(new VarInsnNode(ASTORE, variable.index)); } public void makeVarLoad(LocalVariable variable) { code.add(new VarInsnNode(ALOAD, variable.index)); } public void makeUnknown(AbstractInsnNode node) { code.add(node); } public LabelNode makeLabel() { LabelNode el; code.add(el = new LabelNode()); return el; } protected Memory getMacros(ValueExprToken token) { if (token instanceof SelfExprToken) { if (method.clazz.entity.isTrait()) { throw new IllegalArgumentException("Cannot use this in Traits"); } else { return new StringMemory(method.clazz.statement.getFulledName()); } } return null; } protected void stackPush(ValueExprToken token, StackItem.Type type) { method.push(new StackItem(token, type)); } public void stackPush(StackItem item) { method.push(item); } public void stackPush(Memory memory) { method.push(new StackItem(memory)); } public void stackPush(ValueExprToken token, Memory memory) { method.push(new StackItem(token, memory)); } public void stackPush(Memory.Type type) { stackPush(null, StackItem.Type.valueOf(type)); } public void stackPush(ValueExprToken token) { Memory o = CompilerUtils.toMemory(token); if (o != null) { stackPush(o); } else if (token instanceof StaticAccessExprToken) { StaticAccessExprToken access = (StaticAccessExprToken) token; if (access.getField() instanceof NameToken) { String constant = ((NameToken) access.getField()).getName(); String clazz = null; ClassEntity entity = null; if (access.getClazz() instanceof ParentExprToken) { entity = method.clazz.entity.getParent(); if (entity != null) clazz = entity.getName(); } else if (access.getClazz() instanceof FulledNameToken) { clazz = ((FulledNameToken) access.getClazz()).getName(); entity = compiler.getModule().findClass(clazz); } if (entity == null && method.clazz.entity != null && method.clazz.entity.getName().equalsIgnoreCase(clazz)) entity = method.clazz.entity; if (entity != null) { ConstantEntity c = entity.findConstant(constant); if (c != null && c.getValue() != null) { stackPush(c.getValue()); stackPeek().setLevel(-1); return; } } } stackPush(token, StackItem.Type.REFERENCE); } else { if (token instanceof VariableExprToken && !methodStatement.isUnstableVariable((VariableExprToken) token)) { LocalVariable local = method.getLocalVariable(((VariableExprToken) token).getName()); if (local != null && local.getValue() != null) { stackPush(token, local.getValue()); stackPeek().setLevel(-1); return; } } stackPush(token, StackItem.Type.REFERENCE); } stackPeek().setLevel(-1); } public StackItem stackPop() { return method.pop(); } public ValueExprToken stackPopToken() { return method.pop().getToken(); } public StackItem stackPeek() { return method.peek(); } public void setStackPeekAsImmutable(boolean value) { method.peek().immutable = value; } public void setStackPeekAsImmutable() { setStackPeekAsImmutable(true); } public ValueExprToken stackPeekToken() { return method.peek().getToken(); } public boolean stackEmpty(boolean relative) { if (relative) return method.getStackCount() == exprStackInit.peek(); else return method.getStackCount() == 0; } public void writeLineNumber(Token token) { if (token.getMeta().getStartLine() > lastLineNumber) { lastLineNumber = token.getMeta().getStartLine(); code.add(new LineNumberNode(lastLineNumber, new LabelNode())); } } public void writeWarning(Token token, String message) { writePushEnv(); writePushTraceInfo(token); writePushConstString(message); writePushConstNull(); writeSysDynamicCall(Environment.class, "warning", void.class, TraceInfo.class, String.class, Object[].class); } public void writePushBooleanAsMemory(boolean value) { if (value) code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "TRUE", Type.getDescriptor(Memory.class) )); else code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "FALSE", Type.getDescriptor(Memory.class) )); stackPush(Memory.Type.REFERENCE); } public void writePushMemory(Memory memory) { Memory.Type type = Memory.Type.REFERENCE; if (memory instanceof UndefinedMemory) { code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "UNDEFINED", Type.getDescriptor(Memory.class) )); } else if (memory instanceof NullMemory) { code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "NULL", Type.getDescriptor(Memory.class) )); } else if (memory instanceof FalseMemory) { writePushConstBoolean(false); return; } else if (memory instanceof TrueMemory) { writePushConstBoolean(true); return; } else if (memory instanceof KeyValueMemory) { writePushMemory(((KeyValueMemory) memory).key); writePopBoxing(); writePushMemory(((KeyValueMemory) memory).getValue()); writePopBoxing(); Object arrayKey = ((KeyValueMemory) memory).getArrayKey(); if (arrayKey instanceof String) { writePushConstString((String) arrayKey); writeSysStaticCall(KeyValueMemory.class, "valueOf", Memory.class, Memory.class, Memory.class, String.class); } else if (arrayKey instanceof LongMemory) { writePushConstantMemory((Memory) arrayKey); writeSysStaticCall(KeyValueMemory.class, "valueOf", Memory.class, Memory.class, Memory.class, Memory.class); } else { writeSysStaticCall(KeyValueMemory.class, "valueOf", Memory.class, Memory.class, Memory.class); } setStackPeekAsImmutable(); return; } else if (memory instanceof ReferenceMemory) { code.add(new TypeInsnNode(NEW, Type.getInternalName(ReferenceMemory.class))); code.add(new InsnNode(DUP)); code.add(new MethodInsnNode(INVOKESPECIAL, Type.getInternalName(ReferenceMemory.class), Constants.INIT_METHOD, "()V", false)); } else if (memory instanceof ArrayMemory) { ArrayMemory array = (ArrayMemory) memory; writePushConstInt(array.size()); if (!array.isList()) { writeSysStaticCall(ArrayMemory.class, "createHashed", ArrayMemory.class, int.class); } else { writeSysStaticCall(ArrayMemory.class, "createListed", ArrayMemory.class, int.class); } ForeachIterator foreachIterator = ((ArrayMemory) memory).foreachIterator(false, false); while (foreachIterator.next()) { writePushDup(); if (array.isList()) { writePushMemory(foreachIterator.getValue()); writePopBoxing(); writeSysDynamicCall(ArrayMemory.class, "add", ReferenceMemory.class, Memory.class); } else { Memory key = foreachIterator.getMemoryKey(); writePushMemory(key); if (!key.isString()) { writePopBoxing(); } writePushMemory(foreachIterator.getValue()); writePopBoxing(); writeSysDynamicCall(ArrayMemory.class, "put", ReferenceMemory.class, Object.class, Memory.class); } writePopAll(1); } /*stackPop(); stackPush(memory);*/ setStackPeekAsImmutable(); return; } else { switch (memory.type) { case INT: { code.add(new LdcInsnNode(memory.toLong())); type = Memory.Type.INT; } break; case DOUBLE: { code.add(new LdcInsnNode(memory.toDouble())); type = Memory.Type.DOUBLE; } break; case STRING: { code.add(new LdcInsnNode(memory.toString())); type = Memory.Type.STRING; } break; } } stackPush(type); setStackPeekAsImmutable(); } public boolean writePopBoxing(boolean asImmutable) { return writePopBoxing(stackPeek().type, asImmutable); } public boolean writePopBoxing(boolean asImmutable, boolean useConstants) { return writePopBoxing(stackPeek().type, asImmutable, useConstants); } public boolean writePopBoxing() { return writePopBoxing(false); } public boolean writePopBoxing(Class<?> clazz, boolean asImmutable) { return writePopBoxing(StackItem.Type.valueOf(clazz), asImmutable); } public boolean writePopBoxing(Class<?> clazz) { return writePopBoxing(clazz, false); } public boolean writePopBoxing(StackItem.Type type) { return writePopBoxing(type, false); } public boolean writePopBoxing(StackItem.Type type, boolean asImmutable) { return writePopBoxing(type, asImmutable, true); } public boolean writePopBoxing(StackItem.Type type, boolean asImmutable, boolean useConstants) { switch (type) { case BOOL: /*if (useConstants && code.getLast() instanceof InsnNode) { InsnNode node = (InsnNode) code.getLast(); StackItem stackPeek = stackPeek(); if (stackPeek.type == StackItem.Type.BOOL) { switch (node.getOpcode()) { case ICONST_0: case ICONST_1: code.remove(node); stackPop(); writePushBooleanAsMemory(node.getOpcode() != ICONST_0); break; default: writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); } break; } }*/ writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); setStackPeekAsImmutable(); return true; case SHORT: case BYTE: case LONG: case INT: { if (useConstants && code.getLast() instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) code.getLast(); code.remove(node); stackPop(); writePushConstantMemory(LongMemory.valueOf((Long) node.cst)); } else { writeSysStaticCall(LongMemory.class, "valueOf", Memory.class, type.toClass()); } setStackPeekAsImmutable(); } return true; case FLOAT: case DOUBLE: { if (useConstants && code.getLast() instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) code.getLast(); code.remove(node); stackPop(); if (type == StackItem.Type.FLOAT) { writePushConstantMemory(DoubleMemory.valueOf((Float) node.cst)); } else { writePushConstantMemory(DoubleMemory.valueOf((Double) node.cst)); } } else { writeSysStaticCall(DoubleMemory.class, "valueOf", Memory.class, type.toClass()); } setStackPeekAsImmutable(); return true; } case STRING: { if (useConstants && code.getLast() instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) code.getLast(); code.remove(node); stackPop(); writePushConstantMemory(StringMemory.valueOf(node.cst.toString())); } else { writeSysStaticCall(StringMemory.class, "valueOf", Memory.class, String.class); } setStackPeekAsImmutable(); return true; } case REFERENCE: { if (asImmutable) { writePopImmutable(); } } break; } return false; } public void writePushSmallInt(int value) { switch (value) { case -1: code.add(new InsnNode(ICONST_M1)); break; case 0: code.add(new InsnNode(ICONST_0)); break; case 1: code.add(new InsnNode(ICONST_1)); break; case 2: code.add(new InsnNode(ICONST_2)); break; case 3: code.add(new InsnNode(ICONST_3)); break; case 4: code.add(new InsnNode(ICONST_4)); break; case 5: code.add(new InsnNode(ICONST_5)); break; default: code.add(new LdcInsnNode(value)); } stackPush(Memory.Type.INT); } public void writePushScalarBoolean(boolean value) { writePushSmallInt(value ? 1 : 0); stackPop(); stackPush(value ? Memory.TRUE : Memory.FALSE); } public void writePushString(String value) { writePushMemory(new StringMemory(value)); } public void writePushConstString(String value) { writePushString(value); } public void writePushConstDouble(double value) { code.add(new LdcInsnNode(value)); stackPush(null, StackItem.Type.DOUBLE); } public void writePushConstFloat(float value) { code.add(new LdcInsnNode(value)); stackPush(null, StackItem.Type.FLOAT); } public void writePushConstLong(long value) { code.add(new LdcInsnNode(value)); stackPush(null, StackItem.Type.LONG); } public void writePushConstInt(int value) { writePushSmallInt(value); } public void writePushConstShort(short value) { writePushConstInt(value); stackPop(); stackPush(null, StackItem.Type.SHORT); } public void writePushConstByte(byte value) { writePushConstInt(value); stackPop(); stackPush(null, StackItem.Type.BYTE); } public void writePushConstBoolean(boolean value) { writePushConstInt(value ? 1 : 0); stackPop(); stackPush(null, StackItem.Type.BOOL); } public void writePushSelf(boolean withLower) { if (method.clazz.entity.isTrait()) { if (method.getLocalVariable("~class_name") != null) { writeVarLoad("~class_name"); } else { writePushEnv(); writeSysDynamicCall(Environment.class, "__getMacroClass", Memory.class); } writePopString(); if (withLower) writePushDupLowerCase(); } else { writePushConstString(method.clazz.statement.getFulledName()); if (withLower) writePushConstString(method.clazz.statement.getFulledName().toLowerCase()); } } public void writePushStatic() { writePushEnv(); writeSysDynamicCall(Environment.class, "getLateStatic", String.class); } public void writePushParent(Token token) { writePushEnv(); writePushTraceInfo(token); if (method.getLocalVariable("~class_name") != null) { writeVarLoad("~class_name"); writeSysDynamicCall(Environment.class, "__getParent", String.class, TraceInfo.class, String.class); } else { writeSysDynamicCall(Environment.class, "__getParent", String.class, TraceInfo.class); } } public void writePushLocal() { writeVarLoad("~local"); } public void writePushEnv() { method.entity.setUsesStackTrace(true); LocalVariable variable = method.getLocalVariable("~env"); if (variable == null) { if (!methodStatement.isStatic()) writePushEnvFromSelf(); else throw new RuntimeException("Cannot find `~env` variable"); return; } stackPush(Memory.Type.REFERENCE); makeVarLoad(variable); } public void writePushEnvFromSelf() { method.entity.setUsesStackTrace(true); writeVarLoad("~this"); writeSysDynamicCall(null, "getEnvironment", Environment.class); } public void writePushDup(StackItem.Type type) { stackPush(null, type); if (type.size() == 2) code.add(new InsnNode(DUP2)); else code.add(new InsnNode(DUP)); } public void writePushDup() { StackItem item = method.peek(); stackPush(item); if (item.type.size() == 2) code.add(new InsnNode(DUP2)); else code.add(new InsnNode(DUP)); } public void writePushDupLowerCase() { writePushDup(); writePopString(); writeSysDynamicCall(String.class, "toLowerCase", String.class); } public void writePushNull() { writePushMemory(Memory.NULL); } public void writePushVoid() { writePushMemory(Memory.UNDEFINED); } public void writePushConstNull() { stackPush(Memory.Type.REFERENCE); code.add(new InsnNode(ACONST_NULL)); } public void writePushNewObject(Class clazz) { code.add(new TypeInsnNode(NEW, Type.getInternalName(clazz))); stackPush(Memory.Type.REFERENCE); writePushDup(); writeSysCall(clazz, INVOKESPECIAL, Constants.INIT_METHOD, void.class); stackPop(); } public void writePushNewObject(String internalName, Class... paramClasses) { code.add(new TypeInsnNode(NEW, internalName)); stackPush(Memory.Type.REFERENCE); writePushDup(); writeSysCall(internalName, INVOKESPECIAL, Constants.INIT_METHOD, void.class, paramClasses); stackPop(); } public void writePushStaticCall(Method method) { writeSysStaticCall( method.getDeclaringClass(), method.getName(), method.getReturnType(), method.getParameterTypes() ); } Memory writePushCompileFunction(CallExprToken function, CompileFunction compileFunction, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { CompileFunction.Method method = compileFunction.find(function.getParameters().size()); if (method == null) { if (!writeOpcode) return Memory.NULL; writeWarning(function, Messages.ERR_EXPECT_LEAST_PARAMS.fetch( compileFunction.name, compileFunction.getMinArgs(), function.getParameters().size() )); if (returnValue) writePushNull(); return null; } else if (!method.isVarArg() && method.argsCount < function.getParameters().size()) { if (!writeOpcode) return Memory.NULL; writeWarning(function, Messages.ERR_EXPECT_EXACTLY_PARAMS.fetch( compileFunction.name, method.argsCount, function.getParameters().size() )); if (returnValue) writePushNull(); return null; } if (statistic != null) statistic.returnType = StackItem.Type.valueOf(method.resultType); Class[] types = method.parameterTypes; ListIterator<ExprStmtToken> iterator = function.getParameters().listIterator(); Object[] arguments = new Object[types.length]; int j = 0; boolean immutable = method.isImmutable; boolean init = false; for (int i = 0; i < method.parameterTypes.length; i++) { Class<?> argType = method.parameterTypes[i]; boolean isRef = method.references[i]; boolean isMutable = method.isPresentAnnotationOfParam(i, Runtime.MutableValue.class); if (method.isPresentAnnotationOfParam(i, Runtime.GetLocals.class)) { if (!writeOpcode) return null; immutable = false; writePushLocal(); } else if (argType == Environment.class) { if (immutable) { arguments[i] = compiler.getEnvironment(); } else { if (!writeOpcode) return null; writePushEnv(); } } else if (argType == TraceInfo.class) { if (immutable) { arguments[i] = function.toTraceInfo(compiler.getContext()); } else { if (!writeOpcode) return null; writePushTraceInfo(function); } } else { if (argType == Memory[].class) { Memory[] args = new Memory[function.getParameters().size() - j]; boolean arrCreated = false; for (int t = 0; t < function.getParameters().size() - j; t++) { ExprStmtToken next = iterator.next(); if (immutable) args[t] = writeExpression(next, true, true, false); if (args[t] == null) { if (!writeOpcode) return null; if (!arrCreated) { if (immutable) { for (int n = 0; n < i /*j*/; n++) { if (arguments[n] instanceof TraceInfo) { writePushTraceInfo(function); } else if (arguments[n] instanceof Environment) { writePushEnv(); } else { writePushMemory((Memory) arguments[n]); writePop(types[n], true, true); arguments[t] = null; } } } // create new array writePushSmallInt(args.length); code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Memory.class))); stackPop(); stackPush(Memory.Type.REFERENCE); arrCreated = true; } writePushDup(); writePushSmallInt(t); writeExpression( next, true, false, writeOpcode ); //if (!isRef) BUGFIX - array is memory[] and so we need to convert value to memory writePopBoxing(!isRef); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); immutable = false; } } if (!immutable && !arrCreated) { code.add(new InsnNode(ACONST_NULL)); stackPush(Memory.Type.REFERENCE); } arguments[i/*j*/] = MemoryUtils.valueOf(args); } else { ExprStmtToken next = iterator.next(); if (!immutable && !init) { init = true; for (int k = 0; k < i/*j*/; k++) { if (arguments[k] != null) { if (arguments[k] instanceof TraceInfo) { writePushTraceInfo(function); } else if (arguments[k] instanceof Environment) { writePushEnv(); } else { writePushMemory((Memory) arguments[k]); writePop(types[k], true, isRef); arguments[k] = null; } } } } if (immutable) arguments[i/*j*/] = writeExpression(next, true, true, false); if (arguments[i/*j*/] == null) { if (!writeOpcode) return null; if (!init) { for (int n = 0; n < i/*j*/; n++) { if (arguments[n] instanceof TraceInfo) { writePushTraceInfo(function); } else if (arguments[n] instanceof Environment) { writePushEnv(); } else { writePushMemory((Memory) arguments[n]); writePop(types[n], true, false); } arguments[n] = null; } init = true; } if (isRef) writeExpression(next, true, false, writeOpcode); else { Memory tmp = writeExpression(next, true, true, true); if (tmp != null) writePushMemory(tmp); } writePop(argType, true, isMutable && !isRef); if (!isMutable && !isRef && stackPeek().type.isReference()) { writeSysDynamicCall(Memory.class, "toValue", Memory.class); } immutable = false; } j++; } } } if (immutable) { if (!returnValue) return null; Object[] typedArguments = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { if (method.parameterTypes[i] != Memory.class && arguments[i] instanceof Memory) typedArguments[i] = method.converters[i].run((Memory) arguments[i]); //MemoryUtils.toValue((Memory)arguments[i], types[i]); else typedArguments[i] = arguments[i]; } try { Object value = method.method.invoke(null, typedArguments); return MemoryUtils.valueOf(value); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } if (!writeOpcode) return null; this.method.entity.setImmutable(false); writeLineNumber(function); writePushStaticCall(method.method); if (returnValue) { if (method.resultType == void.class) writePushNull(); setStackPeekAsImmutable(); } return null; } public void writePushParameters(Collection<Memory> memories) { writePushSmallInt(memories.size()); code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Memory.class))); stackPop(); stackPush(Memory.Type.REFERENCE); int i = 0; for (Memory param : memories) { writePushDup(); writePushSmallInt(i); writePushMemory(param); writePopBoxing(true, false); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); i++; } } public void writePushParameters(Collection<ExprStmtToken> parameters, Memory... additional) { writePushParameters(parameters, true, additional); } public void writePushParameters(Collection<ExprStmtToken> parameters, boolean useConstants, Memory... additional) { if (parameters.isEmpty()) { code.add(new InsnNode(ACONST_NULL)); stackPush(Memory.Type.REFERENCE); return; } if (useConstants && additional == null || additional.length == 0) { List<Memory> constantParameters = new ArrayList<Memory>(); for (ExprStmtToken param : parameters) { Memory paramMemory = writeExpression(param, true, true, false); if (paramMemory == null || paramMemory.isArray()) { // skip arrays. break; } constantParameters.add(paramMemory); } if (constantParameters.size() == parameters.size()) { writePushConstantMemoryArray(constantParameters); return; } } writePushSmallInt(parameters.size() + (additional == null ? 0 : additional.length)); code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Memory.class))); stackPop(); stackPush(Memory.Type.REFERENCE); int i = 0; for (ExprStmtToken param : parameters) { writePushDup(); writePushSmallInt(i); writeExpression(param, true, false); writePopBoxing(); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); i++; } if (additional != null) { for (Memory m : additional) { writePushDup(); writePushSmallInt(i); writePushMemory(m); writePopBoxing(); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); i++; } } } Memory writePushParentDynamicMethod(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { if (!writeOpcode) return null; StaticAccessExprToken dynamic = (StaticAccessExprToken) function.getName(); writeLineNumber(function); writePushThis(); if (dynamic.getField() != null) { if (dynamic.getField() instanceof NameToken) { String name = ((NameToken) dynamic.getField()).getName(); writePushConstString(name); writePushConstString(name.toLowerCase()); } else { writePush(dynamic.getField(), true, false); writePopString(); writePushDupLowerCase(); } } else { writeExpression(dynamic.getFieldExpr(), true, false); writePopString(); writePushDupLowerCase(); } writePushEnv(); writePushTraceInfo(dynamic); writePushParameters(function.getParameters()); writeSysStaticCall( ObjectInvokeHelper.class, "invokeParentMethod", Memory.class, Memory.class, String.class, String.class, Environment.class, TraceInfo.class, Memory[].class ); if (!returnValue) writePopAll(1); if (statistic != null) statistic.returnType = StackItem.Type.REFERENCE; return null; } Memory writePushDynamicMethod(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { if (!writeOpcode) return null; DynamicAccessExprToken access = (DynamicAccessExprToken) function.getName(); if (access instanceof DynamicAccessAssignExprToken) unexpectedToken(access); writeLineNumber(function); writeDynamicAccessPrepare(access, true); writePushParameters(function.getParameters()); writeSysStaticCall( ObjectInvokeHelper.class, "invokeMethod", Memory.class, Memory.class, String.class, String.class, Environment.class, TraceInfo.class, Memory[].class ); if (!returnValue) writePopAll(1); if (statistic != null) statistic.returnType = StackItem.Type.REFERENCE; return null; } boolean writePushFastStaticMethod(CallExprToken function, boolean returnValue) { StaticAccessExprToken access = (StaticAccessExprToken) function.getName(); CompileClass compileClass = compiler.getEnvironment().scope.findCompileClass(access.getClazz().getWord()); if (compileClass == null) return false; ClassEntity classEntity = compiler.getEnvironment().fetchClass(compileClass.getNativeClass()); MethodEntity methodEntity = classEntity.findMethod(access.getField().getWord().toLowerCase()); if (methodEntity != null && methodEntity.getNativeMethod() != null && methodEntity.getNativeMethod().isAnnotationPresent(Runtime.FastMethod.class)) { int cnt = methodEntity.getRequiredParamCount(); if (cnt > function.getParameters().size()) { writeWarning(function, Messages.ERR_EXPECT_EXACTLY_PARAMS.fetch( methodEntity.getClazzName() + "::" + methodEntity.getName(), cnt, function.getParameters().size() )); if (returnValue) writePushNull(); return true; } List<Memory> additional = new ArrayList<Memory>(); for (ParameterEntity param : methodEntity.getParameters()) { if (param.getDefaultValue() != null) additional.add(param.getDefaultValue()); else if (!additional.isEmpty()) throw new IllegalStateException("Arguments with default values must be located at the end"); } writePushEnv(); writePushParameters(function.getParameters(), additional.toArray(new Memory[0])); writeSysStaticCall( compileClass.getNativeClass(), methodEntity.getName(), Memory.class, Environment.class, Memory[].class ); if (!returnValue) writePopAll(1); return true; } return false; } Memory writePushStaticMethod(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { StaticAccessExprToken access = (StaticAccessExprToken) function.getName(); if (!writeOpcode) return null; writeLineNumber(function); if (writePushFastStaticMethod(function, returnValue)) return null; writePushEnv(); writePushTraceInfo(function.getName()); String methodName = null; ValueExprToken clazz = access.getClazz(); if ((clazz instanceof NameToken || (clazz instanceof SelfExprToken && !method.clazz.entity.isTrait())) && access.getField() instanceof NameToken) { String className; if (clazz instanceof SelfExprToken) className = getMacros(clazz).toString(); else className = ((NameToken) clazz).getName(); writePushString(className.toLowerCase()); methodName = ((NameToken) access.getField()).getName(); writePushString(methodName.toLowerCase()); writePushString(className); writePushString(methodName); writePushParameters(function.getParameters()); if (method.clazz.statement.isTrait()) { writePushConstNull(); writePushConstInt(0); } else { int cacheIndex = method.clazz.getAndIncCallMethCount(); writeGetStatic("$CALL_METH_CACHE", MethodCallCache.class); writePushConstInt(cacheIndex); } writeSysStaticCall( InvokeHelper.class, "callStatic", Memory.class, Environment.class, TraceInfo.class, String.class, String.class, // lower sign name String.class, String.class, // origin names Memory[].class, MethodCallCache.class, Integer.TYPE ); } else { if (clazz instanceof NameToken) { writePushString(((NameToken) clazz).getName()); writePushDupLowerCase(); } else if (clazz instanceof SelfExprToken) { writePushSelf(true); } else if (clazz instanceof StaticExprToken) { writePushStatic(); writePushDupLowerCase(); } else { writePush(clazz, true, false); writePopString(); writePushDupLowerCase(); } if (access.getField() != null) { ValueExprToken field = access.getField(); if (field instanceof NameToken) { writePushString(((NameToken) field).getName()); writePushString(((NameToken) field).getName().toLowerCase()); } else if (field instanceof ClassExprToken) { unexpectedToken(field); } else { writePush(access.getField(), true, false); writePopString(); writePushDupLowerCase(); } } else { writeExpression(access.getFieldExpr(), true, false); writePopString(); writePushDupLowerCase(); } writePushParameters(function.getParameters()); if (clazz instanceof StaticExprToken || method.clazz.statement.isTrait() || clazz instanceof VariableExprToken) { writePushConstNull(); writePushConstInt(0); } else { int cacheIndex = method.clazz.getAndIncCallMethCount(); writeGetStatic("$CALL_METH_CACHE", MethodCallCache.class); writePushConstInt(cacheIndex); } writeSysStaticCall( InvokeHelper.class, "callStaticDynamic", Memory.class, Environment.class, TraceInfo.class, String.class, String.class, String.class, String.class, Memory[].class, MethodCallCache.class, Integer.TYPE ); } if (statistic != null) statistic.returnType = StackItem.Type.REFERENCE; return null; } public static class PushCallStatistic { public StackItem.Type returnType = StackItem.Type.REFERENCE; } Memory writePushCall(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { Token name = function.getName(); if (name instanceof NameToken) { String realName = ((NameToken) name).getName(); CompileFunction compileFunction = compiler.getScope().findCompileFunction(realName); // try find system function, like max, sin, cos, etc. if (compileFunction == null && name instanceof FulledNameToken && compiler.getEnvironment().fetchFunction(realName) == null && compiler.findFunction(realName) == null) { String tryName = ((FulledNameToken) name).getLastName().getName(); compileFunction = compiler.getScope().findCompileFunction(tryName); } if (compileFunction != null) { return writePushCompileFunction(function, compileFunction, returnValue, writeOpcode, statistic); } else { if (!writeOpcode) return null; method.entity.setImmutable(false); int index = method.clazz.getAndIncCallFuncCount(); writePushEnv(); writePushTraceInfo(function); writePushString(realName.toLowerCase()); writePushString(realName); writePushParameters(function.getParameters()); writeGetStatic("$CALL_FUNC_CACHE", FunctionCallCache.class); writePushConstInt(index); writeSysStaticCall( InvokeHelper.class, "call", Memory.class, Environment.class, TraceInfo.class, String.class, String.class, Memory[].class, FunctionCallCache.class, Integer.TYPE ); if (!returnValue) writePopAll(1); } } else if (name instanceof StaticAccessExprToken) { method.entity.setImmutable(false); if (((StaticAccessExprToken) name).isAsParent()) return writePushParentDynamicMethod(function, returnValue, writeOpcode, statistic); else return writePushStaticMethod(function, returnValue, writeOpcode, statistic); } else if (name instanceof DynamicAccessExprToken) { method.entity.setImmutable(false); return writePushDynamicMethod(function, returnValue, writeOpcode, statistic); } else { if (!writeOpcode) return null; method.entity.setImmutable(false); writeLineNumber(function); writePush((ValueExprToken) function.getName(), true, false); writePopBoxing(); writePushParameters(function.getParameters()); writePushEnv(); writePushTraceInfo(function); writeSysStaticCall( InvokeHelper.class, "callAny", Memory.class, Memory.class, Memory[].class, Environment.class, TraceInfo.class ); if (!returnValue) writePopAll(1); } return null; } public void writeDefineVariables(Collection<VariableExprToken> values) { for (VariableExprToken value : values) writeDefineVariable(value); } public void writeUndefineVariables(Collection<VariableExprToken> values) { LabelNode end = new LabelNode(); for (VariableExprToken value : values) writeUndefineVariable(value, end); } public void writeDefineGlobalVar(String name) { writePushEnv(); writePushConstString(name); writeSysDynamicCall(Environment.class, "getOrCreateGlobal", Memory.class, String.class); makeVarStore(method.getLocalVariable(name)); stackPop(); } public void writePushThis() { if (method.clazz.isClosure() || method.getGeneratorEntity() != null) { writeVarLoad("~this"); writeGetDynamic("self", Memory.class); } else { if (method.getLocalVariable("this") == null) { if (!methodStatement.isStatic()) { LabelNode label = writeLabel(node); LocalVariable local = method.addLocalVariable("this", label, Memory.class); writeDefineThis(local); } else { writePushNull(); return; } } writeVarLoad("this"); } } protected void writeDefineThis(LocalVariable variable) { if (method.clazz.isClosure() || method.getGeneratorEntity() != null) { writeVarLoad("~this"); writeGetDynamic("self", Memory.class); makeVarStore(variable); stackPop(); } else { LabelNode endLabel = new LabelNode(); LabelNode elseLabel = new LabelNode(); if (methodStatement.isStatic()) { writePushMemory(Memory.UNDEFINED); writeVarStore(variable, false, false); } else { writeVarLoad("~this"); writeSysDynamicCall(IObject.class, "isMock", Boolean.TYPE); code.add(new JumpInsnNode(IFEQ, elseLabel)); stackPop(); if (variable.isReference()) { writePushMemory(Memory.UNDEFINED); writeSysStaticCall(ReferenceMemory.class, "valueOf", Memory.class, Memory.class); } else { writePushMemory(Memory.UNDEFINED); } writeVarStore(variable, false, false); code.add(new JumpInsnNode(GOTO, endLabel)); code.add(elseLabel); writeVarLoad("~this"); writeSysStaticCall(ObjectMemory.class, "valueOf", Memory.class, IObject.class); makeVarStore(variable); stackPop(); code.add(endLabel); } } variable.pushLevel(); variable.setValue(null); variable.setImmutable(false); variable.setReference(true); } protected void writeDefineVariable(VariableExprToken value) { if (methodStatement.isUnusedVariable(value)) return; LocalVariable variable = method.getLocalVariable(value.getName()); if (variable == null) { LabelNode label = writeLabel(node, value.getMeta().getStartLine()); variable = method.addLocalVariable(value.getName(), label, Memory.class); if (methodStatement.isReference(value) || compiler.getScope().superGlobals.contains(value.getName())) { variable.setReference(true); } else { variable.setReference(false); } if (variable.name.equals("this") && method.getLocalVariable("~this") != null) { // $this writeDefineThis(variable); } else if (compiler.getScope().superGlobals.contains(value.getName())) { // super-globals writeDefineGlobalVar(value.getName()); } else if (methodStatement.isDynamicLocal()) { // ref-local variables writePushLocal(); writePushConstString(value.getName()); writeSysDynamicCall(Memory.class, "refOfIndex", Memory.class, String.class); makeVarStore(variable); stackPop(); variable.pushLevel(); variable.setValue(null); variable.setReference(true); } else { // simple local variables if (variable.isReference()) { writePushNewObject(ReferenceMemory.class); } else { writePushNull(); } makeVarStore(variable); stackPop(); variable.pushLevel(); } } else variable.pushLevel(); } protected void writeUndefineVariable(VariableExprToken value, LabelNode end) { LocalVariable variable = method.getLocalVariable(value.getName()); if (variable != null) variable.popLevel(); } public void writePushVariable(VariableExprToken value) { LocalVariable variable = method.getLocalVariable(value.getName()); if (variable == null || variable.getClazz() == null) writePushNull(); else { writeVarLoad(variable); } } public Memory tryWritePushVariable(VariableExprToken value, boolean heavyObjects) { if (methodStatement.isUnstableVariable(value)) return null; if (compiler.getScope().superGlobals.contains(value.getName())) return null; LocalVariable variable = method.getLocalVariable(value.getName()); if (variable == null || variable.getClazz() == null || methodStatement.isUnusedVariable(value)) { return Memory.NULL; } else { if (methodStatement.variable(value).isPassed()) return null; Memory mem = variable.getValue(); if (mem != null) { if (!heavyObjects) { if (mem.isArray() || mem.toString().length() > 100) { return null; } } return mem; } } return null; } public Memory writePushArray(ArrayExprToken array, boolean returnMemory, boolean writeOpcode) { if (array.getParameters().isEmpty()) { if (returnMemory) return new ArrayMemory(); else if (writeOpcode) writeSysStaticCall(ArrayMemory.class, "valueOf", Memory.class); } else { ArrayMemory ret = returnMemory ? new ArrayMemory() : null; if (ret == null) { boolean map = false; for (ExprStmtToken token : array.getParameters()) { for (Token sub : token.getTokens()) { if (sub instanceof KeyValueExprToken) { map = true; break; } } if (map) break; } writePushConstInt(array.getParameters().size()); if (map) { writeSysStaticCall(ArrayMemory.class, "createHashed", ArrayMemory.class, int.class); } else { writeSysStaticCall(ArrayMemory.class, "createListed", ArrayMemory.class, int.class); } } for (ExprStmtToken param : array.getParameters()) { if (ret == null) writePushDup(); Memory result = writeExpression(param, true, true, ret == null); if (result != null) { if (ret != null) { ret.add(result); continue; } else { writePushMemory(result); } } else { if (!writeOpcode) { return null; } ret = null; } if (result == null && returnMemory) { return writePushArray(array, false, writeOpcode); } writePopBoxing(); writePopImmutable(); writeSysDynamicCall(ArrayMemory.class, "add", ReferenceMemory.class, Memory.class); writePopAll(1); } if (ret != null) return ret; } setStackPeekAsImmutable(); return null; } public int writePushTraceInfo(Token token) { return writePushTraceInfo(token.getMeta().getStartLine(), token.getMeta().getStartPosition()); } void writePushGetFromArray(int index, Class clazz) { writePushSmallInt(index); code.add(new InsnNode(AALOAD)); stackPop(); stackPop(); stackPush(null, StackItem.Type.valueOf(clazz)); } void writePushGetArrayLength() { code.add(new InsnNode(ARRAYLENGTH)); stackPop(); stackPush(null, StackItem.Type.INT); } int createTraceInfo(Token token) { return method.clazz.addTraceInfo(token); } int writePushTraceInfo(int line, int position) { int index = method.clazz.addTraceInfo(line, position); writePushTraceInfo(index); return index; } void writePushTraceInfo(int traceIndex) { writeGetStatic("$TRC", TraceInfo[].class); writePushGetFromArray(traceIndex, TraceInfo.class); } void writePushCreateTraceInfo(int line, int position) { writeGetStatic("$FN", String.class); writePushMemory(LongMemory.valueOf(line)); writePushMemory(LongMemory.valueOf(position)); writeSysStaticCall(TraceInfo.class, "valueOf", TraceInfo.class, String.class, Long.TYPE, Long.TYPE); } int writePushConstantMemory(Memory memory) { int index = method.clazz.addMemoryConstant(memory); writeGetStatic("$MEM", Memory[].class); writePushGetFromArray(index, Memory.class); return index; } int writePushConstantMemoryArray(Collection<Memory> memories) { int index = method.clazz.addMemoryArray(memories); writeGetStatic("$AMEM", Memory[][].class); writePushGetFromArray(index, Memory[].class); return index; } Memory tryWritePushMacro(MacroToken macro, boolean writeOpcode) { if (macro instanceof LineMacroToken) { return LongMemory.valueOf(macro.getMeta().getStartLine() + 1); } else if (macro instanceof FileMacroToken) { return new StringMemory(compiler.getSourceFile()); } else if (macro instanceof DirMacroToken) { String sourceFile = compiler.getSourceFile(); String parent = new File(sourceFile).getParent(); // Fix issue #198. if (sourceFile.startsWith(parent + "//") && parent.endsWith(":")) { parent += "//"; } return new StringMemory(parent); } else if (macro instanceof FunctionMacroToken) { if (method.clazz == null) { return Memory.CONST_EMPTY_STRING; } if (method.clazz.isClosure()) { return new StringMemory("{closure}"); } if (StringUtils.isEmpty(method.clazz.getFunctionName())) return method.clazz.isSystem() ? Memory.CONST_EMPTY_STRING : method.getRealName() == null ? Memory.CONST_EMPTY_STRING : new StringMemory(method.getRealName()); else { return method.clazz.getFunctionName() == null ? Memory.CONST_EMPTY_STRING : new StringMemory(method.clazz.getFunctionName()); } } else if (macro instanceof MethodMacroToken) { if (method.clazz == null) { return Memory.CONST_EMPTY_STRING; } if (method.clazz.isClosure()) { return new StringMemory("{closure}"); } if (method.clazz.isSystem()) return method.clazz.getFunctionName() != null ? new StringMemory(method.clazz.getFunctionName()) : Memory.NULL; else return new StringMemory( method.clazz.entity.getName() + (method.getRealName() == null ? "" : "::" + method.getRealName()) ); } else if (macro instanceof ClassMacroToken) { if (method.clazz.entity.isTrait()) { if (writeOpcode) { writePushEnv(); writeSysDynamicCall(Environment.class, "__getMacroClass", Memory.class); } return null; } else { if (method.clazz.getClassContext() != null) { return new StringMemory(method.clazz.getClassContext().getFulledName()); } else { return new StringMemory(method.clazz.isSystem() ? "" : method.clazz.entity.getName()); } } } else if (macro instanceof NamespaceMacroToken) { return new StringMemory( compiler.getNamespace() == null || compiler.getNamespace().getName() == null ? "" : compiler.getNamespace().getName().getName() ); } else if (macro instanceof TraitMacroToken) { if (method.clazz.entity.isTrait()) return new StringMemory(method.clazz.entity.getName()); else return Memory.CONST_EMPTY_STRING; } else throw new IllegalArgumentException("Unsupported macro value: " + macro.getWord()); } Memory writePushName(NameToken token, boolean returnMemory, boolean writeOpcode) { CompileConstant constant = compiler.getScope().findCompileConstant(token.getName()); if (constant != null) { if (returnMemory) return constant.value; else if (writeOpcode) writePushMemory(constant.value); } else { ConstantEntity constantEntity = compiler.findConstant(token.getName()); /*if (constantEntity == null) // TODO: maybe it's not needed! we should search a namespaced constant in local context constantEntity = compiler.getScope().findUserConstant(token.getName()); */ if (constantEntity != null) { if (returnMemory) return constantEntity.getValue(); else if (writeOpcode) { writePushMemory(constantEntity.getValue()); setStackPeekAsImmutable(); } } else { if (!writeOpcode) return null; writePushEnv(); writePushString(token.getName()); writePushString(token.getName().toLowerCase()); // writePushDupLowerCase(); writePushTraceInfo(token); writeSysDynamicCall(Environment.class, "__getConstant", Memory.class, String.class, String.class, TraceInfo.class); setStackPeekAsImmutable(); } } return null; } Memory tryWritePushReference(StackItem item, boolean writeOpcode, boolean toStack, boolean heavyObjects) { if (item.getToken() instanceof VariableExprToken) { writePushVariable((VariableExprToken) item.getToken()); return null; } return tryWritePush(item, writeOpcode, toStack, heavyObjects); } Memory tryWritePush(StackItem item, boolean writeOpcode, boolean toStack, boolean heavyObjects) { if (item.getToken() != null) return tryWritePush(item.getToken(), true, writeOpcode, heavyObjects); else if (item.getMemory() != null) { return item.getMemory(); } else if (toStack) stackPush(null, item.type); return null; } StackItem.Type tryGetType(StackItem item) { if (item.getToken() != null) { return tryGetType(item.getToken()); } else if (item.getMemory() != null) { return StackItem.Type.valueOf(item.getMemory().type); } else return item.type; } public boolean tryIsImmutable(StackItem item) { if (item.getToken() != null) { return tryIsImmutable(item.getToken()); } else if (item.getMemory() != null) return true; else return item.type.isConstant(); } public Memory tryWritePush(StackItem item) { return tryWritePush(item, true, true, true); } public void writePush(StackItem item) { writePush(item, true, false); } public void writePush(StackItem item, boolean tryGetMemory, boolean heavyObjects) { if (tryGetMemory) { Memory memory = tryWritePushReference(item, true, true, heavyObjects); if (memory != null) writePushMemory(memory); } else { tryWritePushReference(item, true, true, heavyObjects); } } public void writePush(StackItem item, StackItem.Type castType) { Memory memory = tryWritePush(item); if (memory != null) { switch (castType) { case DOUBLE: writePushConstDouble(memory.toDouble()); return; case FLOAT: writePushConstFloat((float) memory.toDouble()); return; case LONG: writePushConstLong(memory.toLong()); return; case INT: writePushConstInt((int) memory.toLong()); return; case SHORT: writePushConstInt((short) memory.toLong()); return; case BYTE: writePushConstByte((byte) memory.toLong()); return; case BOOL: writePushConstBoolean(memory.toBoolean()); return; case STRING: writePushConstString(memory.toString()); return; } writePushMemory(memory); } writePop(castType.toClass(), true, true); } boolean tryIsImmutable(ValueExprToken value) { if (value instanceof IntegerExprToken) return true; else if (value instanceof DoubleExprToken) return true; else if (value instanceof StringExprToken) return true; else if (value instanceof LineMacroToken) return true; else if (value instanceof MacroToken) return true; else if (value instanceof ArrayExprToken) return true; else if (value instanceof StringBuilderExprToken) return true; else if (value instanceof NameToken) return true; else if (value instanceof CallExprToken) { PushCallStatistic statistic = new PushCallStatistic(); writePushCall((CallExprToken) value, true, false, statistic); return statistic.returnType.isConstant(); } return false; } StackItem.Type tryGetType(ValueExprToken value) { if (value instanceof IntegerExprToken) return StackItem.Type.LONG; else if (value instanceof DoubleExprToken) return StackItem.Type.DOUBLE; else if (value instanceof StringExprToken) return StackItem.Type.STRING; else if (value instanceof LineMacroToken) return StackItem.Type.LONG; else if (value instanceof MacroToken) return StackItem.Type.STRING; else if (value instanceof ArrayExprToken) return StackItem.Type.ARRAY; else if (value instanceof StringBuilderExprToken) return StackItem.Type.STRING; else if (value instanceof CallExprToken) { PushCallStatistic statistic = new PushCallStatistic(); writePushCall((CallExprToken) value, true, false, statistic); return statistic.returnType; } else if (value instanceof NameToken) { Memory tmpMemory = writePushName((NameToken) value, true, false); return tmpMemory == null ? StackItem.Type.REFERENCE : StackItem.Type.valueOf(tmpMemory.type); } else return StackItem.Type.REFERENCE; } Memory tryWritePush(ValueExprToken value, boolean returnValue, boolean writeOpcode, boolean heavyObjects) { if (writeOpcode) { BaseStatementCompiler compiler = getCompiler(value.getClass()); if (compiler != null) { if (compiler instanceof BaseExprCompiler) { ((BaseExprCompiler) compiler).write(value, returnValue); } else throw new IllegalStateException("Compiler must be extended by " + BaseExprCompiler.class.getName()); return null; } } if (value instanceof NameToken) { return writePushName((NameToken) value, returnValue, writeOpcode); } if (value instanceof ArrayExprToken) { return writePushArray((ArrayExprToken) value, returnValue, writeOpcode); } else if (value instanceof CallExprToken) { return writePushCall((CallExprToken) value, returnValue, writeOpcode, null); } else if (value instanceof MacroToken) { return tryWritePushMacro((MacroToken) value, writeOpcode); } else if (value instanceof VariableExprToken) { if (writeOpcode) writePushVariable((VariableExprToken) value); /*if (returnValue) return tryWritePushVariable((VariableExprToken) value, heavyObjects); */ } return null; } public void writePush(ValueExprToken value, boolean returnValue, boolean heavyObjects) { if (value instanceof VariableExprToken) { writePushVariable((VariableExprToken) value); return; } Memory memory = tryWritePush(value, returnValue, true, heavyObjects); if (memory != null) writePushMemory(memory); } @SuppressWarnings("unchecked") boolean methodExists(Class clazz, String method, Class... paramClasses) { try { clazz.getDeclaredMethod(method, paramClasses); return true; } catch (java.lang.NoSuchMethodException e) { return false; } } void writeSysCall(String internalClassName, int INVOKE_TYPE, String method, Class returnClazz, Class... paramClasses) { Type[] args = new Type[paramClasses.length]; if (INVOKE_TYPE == INVOKEVIRTUAL || INVOKE_TYPE == INVOKEINTERFACE) stackPop(); // this for (int i = 0; i < args.length; i++) { args[i] = Type.getType(paramClasses[i]); stackPop(); } code.add(new MethodInsnNode( INVOKE_TYPE, internalClassName, method, Type.getMethodDescriptor(Type.getType(returnClazz), args), false )); if (returnClazz != void.class) { stackPush(null, StackItem.Type.valueOf(returnClazz)); } } @SuppressWarnings("unchecked") void writeSysCall(Class clazz, int INVOKE_TYPE, String method, Class returnClazz, Class... paramClasses) { if (INVOKE_TYPE != INVOKESPECIAL && clazz != null) { if (compiler.getScope().isDebugMode()) { if (!methodExists(clazz, method, paramClasses)) { throw new NoSuchMethodException(clazz, method, paramClasses); } } } Type[] args = new Type[paramClasses.length]; if (INVOKE_TYPE == INVOKEVIRTUAL || INVOKE_TYPE == INVOKEINTERFACE) stackPop(); // this for (int i = 0; i < args.length; i++) { args[i] = Type.getType(paramClasses[i]); stackPop(); } String owner = clazz == null ? this.method.clazz.node.name : Type.getInternalName(clazz); if (clazz == null && this.method.clazz.entity.isTrait()) throw new CriticalException("[Compiler Error] Cannot use current classname in Trait"); code.add(new MethodInsnNode( INVOKE_TYPE, owner, method, Type.getMethodDescriptor(Type.getType(returnClazz), args), clazz != null && clazz.isInterface() )); if (returnClazz != void.class) { stackPush(null, StackItem.Type.valueOf(returnClazz)); } } public void writeTickTrigger(Token token) { writeTickTrigger(token.toTraceInfo(getCompiler().getContext())); } public void writeTickTrigger(TraceInfo trace) { if (compiler.getScope().isDebugMode() && method.getLocalVariable("~local") != null) { int line = trace.getStartLine(); if (method.registerTickTrigger(line)) { writePushEnv(); writePushTraceInfo(trace.getStartLine(), trace.getStartPosition()); writePushLocal(); writeSysDynamicCall(Environment.class, "__tick", void.class, TraceInfo.class, ArrayMemory.class); } } } public void writeSysDynamicCall(Class clazz, String method, Class returnClazz, Class... paramClasses) throws NoSuchMethodException { writeSysCall( clazz, clazz != null && clazz.isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL, method, returnClazz, paramClasses ); } public void writeSysStaticCall(Class clazz, String method, Class returnClazz, Class... paramClasses) throws NoSuchMethodException { writeSysCall(clazz, INVOKESTATIC, method, returnClazz, paramClasses); } public void writePopImmutable() { if (!stackPeek().immutable) { writeSysDynamicCall(Memory.class, "toImmutable", Memory.class); setStackPeekAsImmutable(); } } public void writeVarStore(LocalVariable variable, boolean returned, boolean asImmutable) { writePopBoxing(); if (asImmutable) writePopImmutable(); if (returned) { writePushDup(); } makeVarStore(variable); stackPop(); } public void checkAssignableVar(VariableExprToken var) { if (method.clazz.isClosure() || !method.clazz.isSystem()) { if (var.getName().equals("this")) compiler.getEnvironment().error(var.toTraceInfo(compiler.getContext()), "Cannot re-assign $this"); } } public void writeVarAssign(LocalVariable variable, VariableExprToken token, boolean returned, boolean asImmutable) { if (token != null) checkAssignableVar(token); writePopBoxing(asImmutable); if (variable.isReference()) { writeVarLoad(variable); writeSysStaticCall(Memory.class, "assignRight", Memory.class, Memory.class, Memory.class); if (!returned) writePopAll(1); } else { if (returned) { writePushDup(); } makeVarStore(variable); stackPop(); } } public void writeVarStore(LocalVariable variable, boolean returned) { writeVarStore(variable, returned, false); } public void writeVarLoad(LocalVariable variable) { stackPush(Memory.Type.valueOf(variable.getClazz())); makeVarLoad(variable); } public void writeVarLoad(String name) { LocalVariable local = method.getLocalVariable(name); if (local == null) throw new IllegalArgumentException("Variable '" + name + "' is not registered"); writeVarLoad(local); } public void writePutStatic(Class clazz, String name, Class fieldClass) { code.add(new FieldInsnNode(PUTSTATIC, Type.getInternalName(clazz), name, Type.getDescriptor(fieldClass))); stackPop(); } public void writePutStatic(String name, Class fieldClass) { code.add(new FieldInsnNode( PUTSTATIC, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPop(); } public void writePutDynamic(String name, Class fieldClass) { code.add(new FieldInsnNode( PUTFIELD, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPop(); } public void writeGetStatic(Class clazz, String name, Class fieldClass) { code.add(new FieldInsnNode(GETSTATIC, Type.getInternalName(clazz), name, Type.getDescriptor(fieldClass))); stackPush(null, StackItem.Type.valueOf(fieldClass)); setStackPeekAsImmutable(); } public void writeGetStatic(String name, Class fieldClass) { code.add(new FieldInsnNode( GETSTATIC, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPush(null, StackItem.Type.valueOf(fieldClass)); setStackPeekAsImmutable(); } public void writeGetDynamic(String name, Class fieldClass) { stackPop(); code.add(new FieldInsnNode( GETFIELD, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPush(null, StackItem.Type.valueOf(fieldClass)); setStackPeekAsImmutable(); } void writeGetEnum(Enum enumInstance) { writeGetStatic(enumInstance.getDeclaringClass(), enumInstance.name(), enumInstance.getDeclaringClass()); } void writeVariableAssign(VariableExprToken variable, StackItem R, AssignExprToken operator, boolean returnValue) { LocalVariable local = method.getLocalVariable(variable.getName()); checkAssignableVar(variable); Memory value = R.getMemory(); writeLineNumber(variable); if (local.isReference()) { String name = "assign"; if (operator.isAsReference()) name = "assignRef"; if (!R.isKnown()) { stackPush(R); writePopBoxing(); writePopImmutable(); writePushVariable(variable); writeSysStaticCall(Memory.class, name + "Right", Memory.class, stackPeek().type.toClass(), Memory.class); } else { writePushVariable(variable); Memory tmp = tryWritePush(R); if (tmp != null) { value = tmp; writePushMemory(value); } writePopBoxing(); writePopImmutable(); writeSysDynamicCall(Memory.class, name, Memory.class, stackPeek().type.toClass()); } if (!returnValue) writePopAll(1); } else { Memory result = tryWritePush(R); if (result != null) { writePushMemory(result); value = result; } writePopBoxing(); writeVarStore(local, returnValue, true); } /*if (!methodStatement.variable(variable).isPassed()) local.setValue(value); if (methodStatement.isDynamicLocal()) */ local.setValue(null); } void writeScalarOperator(StackItem L, StackItem.Type Lt, StackItem R, StackItem.Type Rt, OperatorExprToken operator, Class operatorResult, String operatorName) { boolean isInvert = !R.isKnown(); if (!R.isKnown() && !L.isKnown() && R.getLevel() > L.getLevel()) isInvert = false; if (operator instanceof ConcatExprToken) { if (isInvert) { stackPush(R); writePopString(); writePush(L, StackItem.Type.STRING); writeSysStaticCall(OperatorUtils.class, "concatRight", String.class, String.class, String.class); } else { writePush(L, StackItem.Type.STRING); writePush(R, StackItem.Type.STRING); writeSysDynamicCall(String.class, "concat", String.class, String.class); } return; } else if (operator instanceof PlusExprToken || operator instanceof MinusExprToken || operator instanceof MulExprToken) { if (operator instanceof MinusExprToken && isInvert) { // nothing } else if (Lt.isLikeNumber() && Rt.isLikeNumber()) { StackItem.Type cast = StackItem.Type.LONG; if (Lt.isLikeDouble() || Rt.isLikeDouble()) cast = StackItem.Type.DOUBLE; writePush(L, cast); writePush(R, cast); code.add(new InsnNode(CompilerUtils.getOperatorOpcode(operator, cast))); stackPop(); stackPop(); stackPush(null, cast); return; } } if (isInvert) { stackPush(R); writePopBoxing(); writePush(L); if (operator.isSide()) operatorName += "Right"; writeSysDynamicCall(Memory.class, operatorName, operatorResult, stackPeek().type.toClass()); } else { writePush(L); writePopBoxing(); writePush(R); writeSysDynamicCall(Memory.class, operatorName, operatorResult, stackPeek().type.toClass()); } } public void writePop(Class clazz, boolean boxing, boolean asImmutable) { if (clazz == String.class) writePopString(); else if (clazz == Character.TYPE) writePopChar(); else if (clazz == Boolean.TYPE) writePopBoolean(); else if (clazz == Memory.class) { if (boxing) writePopBoxing(asImmutable); } else if (clazz == Double.TYPE) writePopDouble(); else if (clazz == Float.TYPE) writePopFloat(); else if (clazz == Long.TYPE) writePopLong(); else if (clazz == Integer.TYPE || clazz == Byte.TYPE || clazz == Short.TYPE) writePopInteger(); else throw new IllegalArgumentException("Cannot pop this class: " + clazz.getName()); } public void writePopInteger() { writePopLong(); code.add(new InsnNode(L2I)); stackPop(); stackPush(null, StackItem.Type.INT); } public void writePopFloat() { writePopDouble(); code.add(new InsnNode(D2F)); stackPop(); stackPush(null, StackItem.Type.FLOAT); } public void writePopLong() { switch (stackPeek().type) { case LONG: break; case FLOAT: { code.add(new InsnNode(L2F)); stackPop(); stackPush(Memory.Type.INT); } break; case BYTE: case SHORT: case BOOL: case CHAR: case INT: { code.add(new InsnNode(I2L)); stackPop(); stackPush(Memory.Type.INT); } break; case DOUBLE: { code.add(new InsnNode(D2L)); stackPop(); stackPush(Memory.Type.INT); } break; case STRING: { writeSysStaticCall(StringMemory.class, "toNumeric", Memory.class, String.class); writeSysDynamicCall(Memory.class, "toLong", Long.TYPE); } break; default: { writeSysDynamicCall(Memory.class, "toLong", Long.TYPE); } } } public void writePopDouble() { switch (stackPeek().type) { case DOUBLE: break; case BYTE: case SHORT: case BOOL: case CHAR: case INT: { code.add(new InsnNode(I2D)); stackPop(); stackPush(Memory.Type.DOUBLE); } break; case LONG: { code.add(new InsnNode(L2D)); stackPop(); stackPush(Memory.Type.DOUBLE); } break; case STRING: { writeSysStaticCall(StringMemory.class, "toNumeric", Memory.class, String.class); writeSysDynamicCall(Memory.class, "toDouble", Double.TYPE); } break; default: { writeSysDynamicCall(Memory.class, "toDouble", Double.TYPE); } } } public void writePopString() { StackItem.Type peek = stackPeek().type; switch (peek) { case STRING: break; default: if (peek.isConstant()) { if (peek == StackItem.Type.BOOL) writeSysStaticCall(Memory.class, "boolToString", String.class, peek.toClass()); else writeSysStaticCall(String.class, "valueOf", String.class, peek.toClass()); } else writeSysDynamicCall(Memory.class, "toString", String.class); } } public void writePopChar() { StackItem.Type peek = stackPeek().type; if (peek == StackItem.Type.CHAR) return; if (peek.isConstant()) { writeSysStaticCall(OperatorUtils.class, "toChar", Character.TYPE, peek.toClass()); } else { writePopBoxing(); writeSysDynamicCall(Memory.class, "toChar", Character.TYPE); } } public void writePopBooleanAsObject() { StackItem.Type peek = stackPeek().type; writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, peek.toClass()); setStackPeekAsImmutable(); } public void writePopBoolean() { StackItem.Type peek = stackPeek().type; switch (peek) { case BOOL: break; case BYTE: case INT: case SHORT: case CHAR: case LONG: { writeSysStaticCall(OperatorUtils.class, "toBoolean", Boolean.TYPE, peek.toClass()); } break; case DOUBLE: { writeSysStaticCall(OperatorUtils.class, "toBoolean", Boolean.TYPE, Double.TYPE); } break; case STRING: { writeSysStaticCall(OperatorUtils.class, "toBoolean", Boolean.TYPE, String.class); } break; case REFERENCE: { writeSysDynamicCall(Memory.class, "toBoolean", Boolean.TYPE); } break; } } public void writeDynamicAccessInfo(DynamicAccessExprToken dynamic, boolean addLowerName) { if (dynamic.getField() != null) { if (dynamic.getField() instanceof NameToken) { String name = ((NameToken) dynamic.getField()).getName(); writePushString(name); if (addLowerName) writePushString(name.toLowerCase()); } else { writePush(dynamic.getField(), true, false); writePopString(); if (addLowerName) { writePushDupLowerCase(); } } } else { writeExpression(dynamic.getFieldExpr(), true, false); writePopString(); if (addLowerName) { writePushDupLowerCase(); } } writePushEnv(); writePushTraceInfo(dynamic); } public void writeDynamicAccessPrepare(DynamicAccessExprToken dynamic, boolean addLowerName) { if (stackEmpty(true)) unexpectedToken(dynamic); StackItem o = stackPop(); writePush(o); if (stackPeek().isConstant()) unexpectedToken(dynamic); writePopBoxing(); if (dynamic instanceof DynamicAccessAssignExprToken) { if (((DynamicAccessAssignExprToken) dynamic).getValue() != null) { writeExpression(((DynamicAccessAssignExprToken) dynamic).getValue(), true, false); writePopBoxing(true); } } writeDynamicAccessInfo(dynamic, addLowerName); } void writeArrayGet(ArrayGetExprToken operator, boolean returnValue) { StackItem o = stackPeek(); ValueExprToken L = null; if (o.getToken() != null) { stackPop(); writePush(L = o.getToken(), true, false); writePopBoxing(); } String methodName = operator instanceof ArrayGetRefExprToken ? "refOfIndex" : "valueOfIndex"; boolean isShortcut = operator instanceof ArrayGetRefExprToken && ((ArrayGetRefExprToken) operator).isShortcut(); int i = 0; int size = operator.getParameters().size(); int traceIndex = createTraceInfo(operator); for (ExprStmtToken param : operator.getParameters()) { writePushTraceInfo(traceIndex); // push dup trace writeExpression(param, true, false); if (operator instanceof ArrayGetUnsetExprToken && i == size - 1) { writePopBoxing(); writeSysDynamicCall(Memory.class, "unsetOfIndex", void.class, TraceInfo.class, stackPeek().type.toClass()); if (returnValue) writePushNull(); } else if (operator instanceof ArrayGetIssetExprToken && i == size - 1) { writePopBoxing(); writeSysDynamicCall(Memory.class, "issetOfIndex", Memory.class, TraceInfo.class, stackPeek().type.toClass()); } else if (operator instanceof ArrayGetEmptyExprToken && i == size - 1) { writePopBoxing(); writeSysDynamicCall(Memory.class, "emptyOfIndex", Memory.class, TraceInfo.class, stackPeek().type.toClass()); } else { // TODO: Remove. // PHP CMP: $hack = &$arr[0]; // boolean isMemory = stackPeek().type.toClass() == Memory.class; //if (isMemory) /*if (compiler.isPhpMode()){ if (i == size - 1 && isShortcut){ writePopBoxing(); writeSysDynamicCall(Memory.class, methodName + "AsShortcut", Memory.class, TraceInfo.class, Memory.class); continue; } }*/ writeSysDynamicCall(Memory.class, methodName, Memory.class, TraceInfo.class, stackPeek().type.toClass()); i++; } } } Memory writeUnaryOperator(OperatorExprToken operator, boolean returnValue, boolean writeOpcode) { if (stackEmpty(true)) unexpectedToken(operator); StackItem o = stackPop(); ValueExprToken L = o.getToken(); Memory mem = tryWritePush(o, false, false, true); StackItem.Type type = tryGetType(o); if (mem != null) { Memory result = CompilerUtils.calcUnary(getCompiler().getEnvironment(), operator.toTraceInfo(getCompiler().getContext()), mem, operator); if (operator instanceof ValueIfElseToken) { ValueIfElseToken valueIfElseToken = (ValueIfElseToken) operator; ExprStmtToken ret = valueIfElseToken.getValue(); if (mem.toBoolean()) { if (ret == null) result = mem; else result = writeExpression(ret, true, true, false); } else { result = writeExpression(valueIfElseToken.getAlternative(), true, true, false); } } else if (operator instanceof ArrayGetExprToken && !(operator instanceof ArrayGetRefExprToken)) { // TODO: check!!! /*Memory array = mem; ArrayGetExprToken arrayGet = (ArrayGetExprToken)operator; for(ExprStmtToken expr : arrayGet.getParameters()){ Memory key = writeExpression(expr, true, true, false); if (key == null) break; result = array = array.valueOfIndex(key).toImmutable(); }*/ } if (result != null) { stackPush(result); setStackPeekAsImmutable(); return result; } } if (!writeOpcode) return null; writeLineNumber(operator); String name = operator.getCode(); Class operatorResult = operator.getResultClass(); LocalVariable variable = null; if (L instanceof VariableExprToken) { variable = method.getLocalVariable(((VariableExprToken) L).getName()); if (operator instanceof ArrayPushExprToken || operator instanceof ArrayGetRefExprToken) variable.setValue(null); } if (operator instanceof IncExprToken || operator instanceof DecExprToken) { if (variable == null || variable.isReference()) { if (operator.getAssociation() == Association.LEFT && returnValue) { writePush(o); if (stackPeek().type.isConstant()) unexpectedToken(operator); writePushDup(); writePopImmutable(); code.add(new InsnNode(SWAP)); writePushDup(); } else { writePush(o); if (stackPeek().type.isConstant()) unexpectedToken(operator); writePushDup(); } writeSysDynamicCall(Memory.class, name, operatorResult); writeSysDynamicCall(Memory.class, "assign", Memory.class, operatorResult); if (!returnValue || operator.getAssociation() == Association.LEFT) { writePopAll(1); } } else { writePush(o); if (stackPeek().type.isConstant()) unexpectedToken(operator); if (operator.getAssociation() == Association.LEFT && returnValue) { writeVarLoad(variable); } writeSysDynamicCall(Memory.class, name, operatorResult); variable.setValue(null); // TODO for constant values if (operator.getAssociation() == Association.RIGHT) writeVarStore(variable, returnValue); else { writeVarStore(variable, false); } } } else if (operator instanceof AmpersandRefToken) { writePush(o, false, false); setStackPeekAsImmutable(); Token token = o.getToken(); if (token instanceof VariableExprToken) { LocalVariable local = method.getLocalVariable(((VariableExprToken) token).getName()); local.setValue(null); } } else if (operator instanceof SilentToken) { writePushEnv(); writeSysDynamicCall(Environment.class, "__pushSilent", void.class); writePush(o); writePushEnv(); writeSysDynamicCall(Environment.class, "__popSilent", void.class); } else if (operator instanceof ValueIfElseToken) { writePush(o); ValueIfElseToken valueIfElseToken = (ValueIfElseToken) operator; LabelNode end = new LabelNode(); LabelNode elseL = new LabelNode(); if (valueIfElseToken.getValue() == null) { StackItem.Type dup = stackPeek().type; writePushDup(); writePopBoolean(); code.add(new JumpInsnNode(Opcodes.IFEQ, elseL)); stackPop(); writePopBoxing(); stackPop(); code.add(new JumpInsnNode(Opcodes.GOTO, end)); code.add(elseL); makePop(dup); // remove duplicate of condition value , IMPORTANT!!! writeExpression(valueIfElseToken.getAlternative(), true, false); writePopBoxing(); code.add(end); } else { writePopBoolean(); code.add(new JumpInsnNode(Opcodes.IFEQ, elseL)); stackPop(); writeExpression(valueIfElseToken.getValue(), true, false); writePopBoxing(); stackPop(); code.add(new JumpInsnNode(Opcodes.GOTO, end)); // goto end // else code.add(elseL); writeExpression(valueIfElseToken.getAlternative(), true, false); writePopBoxing(); code.add(end); } setStackPeekAsImmutable(false); } else if (operator instanceof ArrayGetExprToken) { stackPush(o); writeArrayGet((ArrayGetExprToken) operator, returnValue); } else if (operator instanceof CallOperatorToken) { stackPush(o); CallOperatorToken call = (CallOperatorToken) operator; writePushParameters(call.getParameters()); writePushEnv(); writePushTraceInfo(operator); writeSysStaticCall( InvokeHelper.class, "callAny", Memory.class, Memory.class, Memory[].class, Environment.class, TraceInfo.class ); if (!returnValue) writePopAll(1); } else { writePush(o); writePopBoxing(); if (operator.isEnvironmentNeeded() && operator.isTraceNeeded()) { writePushEnv(); writePushTraceInfo(operator); writeSysDynamicCall(Memory.class, name, operatorResult, Environment.class, TraceInfo.class); } else if (operator.isEnvironmentNeeded()) { writePushEnv(); writeSysDynamicCall(Memory.class, name, operatorResult, Environment.class); } else if (operator.isTraceNeeded()) { writePushTraceInfo(operator); writeSysDynamicCall(Memory.class, name, operatorResult, TraceInfo.class); } else writeSysDynamicCall(Memory.class, name, operatorResult); if (!returnValue) { writePopAll(1); } } return null; } Memory writeLogicOperator(LogicOperatorExprToken operator, boolean returnValue, boolean writeOpcode) { if (stackEmpty(true)) unexpectedToken(operator); if (!writeOpcode) { StackItem top = stackPeek(); Memory one = tryWritePush(top, false, false, true); if (one == null) return null; Memory two = writeExpression(operator.getRightValue(), true, true, false); if (two == null) return null; stackPop(); Memory r = operator.calc(getCompiler().getEnvironment(), operator.toTraceInfo(getCompiler().getContext()), one, two); stackPush(r); return r; } writeLineNumber(operator); StackItem o = stackPop(); writePush(o); writePopBoolean(); LabelNode end = new LabelNode(); LabelNode next = new LabelNode(); if (operator instanceof BooleanOrExprToken || operator instanceof BooleanOr2ExprToken) { code.add(new JumpInsnNode(IFEQ, next)); stackPop(); if (returnValue) { writePushBooleanAsMemory(true); stackPop(); } } else if (operator instanceof BooleanAndExprToken || operator instanceof BooleanAnd2ExprToken) { code.add(new JumpInsnNode(IFNE, next)); stackPop(); if (returnValue) { writePushBooleanAsMemory(false); stackPop(); } } code.add(new JumpInsnNode(GOTO, end)); code.add(next); writeExpression(operator.getRightValue(), returnValue, false); if (returnValue) { if (operator.getLast() instanceof ValueIfElseToken) writePopBoxing(); else writePopBooleanAsObject(); } code.add(end); return null; } Memory writeOperator(OperatorExprToken operator, boolean returnValue, boolean writeOpcode) { if (writeOpcode) { BaseExprCompiler compiler = (BaseExprCompiler) getCompiler(operator.getClass()); if (compiler != null) { if (writeOpcode) { writeLineNumber(operator); } compiler.write(operator, returnValue); return null; } } if (operator instanceof LogicOperatorExprToken) { return writeLogicOperator((LogicOperatorExprToken) operator, returnValue, writeOpcode); } if (!operator.isBinary()) { return writeUnaryOperator(operator, returnValue, writeOpcode); } if (stackEmpty(true)) unexpectedToken(operator); StackItem o1 = stackPop(); if (o1.isInvalidForOperations()) unexpectedToken(operator); if (stackEmpty(true)) unexpectedToken(operator); StackItem o2 = stackPeek(); ValueExprToken L = stackPopToken(); if (o2.isInvalidForOperations()) unexpectedToken(operator); if (!(operator instanceof AssignExprToken || operator instanceof AssignOperatorExprToken)) if (o1.getMemory() != null && o2.getMemory() != null) { Memory result; stackPush(result = CompilerUtils.calcBinary( getCompiler().getEnvironment(), operator.toTraceInfo(getCompiler().getContext()), o2.getMemory(), o1.getMemory(), operator, false )); return result; } LocalVariable variable = null; if (L instanceof VariableExprToken) { variable = method.getLocalVariable(((VariableExprToken) L).getName()); } if (operator instanceof AssignExprToken) { if (L instanceof VariableExprToken) { if (!writeOpcode) return null; writeVariableAssign((VariableExprToken) L, o1, (AssignExprToken) operator, returnValue); return null; } } Memory value1 = operator instanceof AssignableOperatorToken ? null : tryWritePush(o2, false, false, true); // LEFT Memory value2 = tryWritePush(o1, false, false, true); // RIGHT if (value1 != null && value2 != null) { stackPush(value1); stackPush(value2); return writeOperator(operator, returnValue, writeOpcode); } if (!returnValue && CompilerUtils.isOperatorAlwaysReturn(operator)) { unexpectedToken(operator); } if (!writeOpcode) { stackPush(o2); stackPush(o1); return null; } if (writeOpcode) { writeLineNumber(operator); } StackItem.Type Lt = tryGetType(o2); StackItem.Type Rt = tryGetType(o1); String name = operator.getCode(); Class operatorResult = operator.getResultClass(); boolean isInvert = false; boolean sideOperator = operator.isSide(); if (variable != null && !variable.isReference()) { if (operator instanceof AssignOperatorExprToken) { name = ((AssignOperatorExprToken) operator).getOperatorCode(); if (operator instanceof AssignConcatExprToken) operatorResult = String.class; if (operator instanceof AssignPlusExprToken || operator instanceof AssignMulExprToken) sideOperator = false; } } if (operator instanceof AssignableOperatorToken && tryIsImmutable(o2)) unexpectedToken(operator); if (Lt.isConstant() && Rt.isConstant()) { if (operator instanceof AssignableOperatorToken) unexpectedToken(operator); writeScalarOperator(o2, Lt, o1, Rt, operator, operatorResult, name); } else { isInvert = !o1.isKnown(); if (!o1.isKnown() && !o2.isKnown() && o1.getLevel() > o2.getLevel()) isInvert = false; if (Lt.isConstant() && !isInvert) { writePush(o2); if (methodExists(OperatorUtils.class, name, Lt.toClass(), Rt.toClass())) { writePush(o1); writeSysStaticCall(OperatorUtils.class, name, operatorResult, Lt.toClass(), Rt.toClass()); } else { writePopBoxing(); writePush(o1); writeSysDynamicCall(Memory.class, name, operatorResult, Rt.toClass()); } } else { if (isInvert) { stackPush(o1); if (o2.isKnown()) writePopBoxing(false); writePush(o2); if (!o2.isKnown() && !o2.type.isReference()) { writeSysStaticCall(OperatorUtils.class, name, operatorResult, Lt.toClass(), Rt.toClass()); name = null; } else if (sideOperator) { name += "Right"; } /*if (cloneValue){ writeSysDynamicCall(Memory.class, name, operatorResult, isInvert ? Lt.toClass() : Rt.toClass()); writePush(o2); name = null; }*/ } else { writePush(o2); writePopBoxing(false); /*if (cloneValue) writePushDup();*/ writePush(o1); if (Rt.isReference()) { writePopBoxing(false); } if (!o1.immutable && !operator.isMutableArguments()) writePopImmutable(); } if (name != null) { writeSysDynamicCall(Memory.class, name, operatorResult, isInvert ? Lt.toClass() : Rt.toClass()); } if (operator.getCheckerCode() != null) { writePopBoxing(); writePushEnv(); writePushTraceInfo(operator); writeSysDynamicCall(Memory.class, operator.getCheckerCode(), Memory.class, Environment.class, TraceInfo.class); } } setStackPeekAsImmutable(); if (operator instanceof AssignOperatorExprToken) { if (variable == null || variable.isReference()) { /*if (isInvert) writeSysStaticCall(Memory.class, "assignRight", Memory.class, Rt.toClass(), Memory.class); else writeSysDynamicCall(Memory.class, "assign", Memory.class, stackPeek().type.toClass()); */ if (!returnValue) writePopAll(1); } else { if (returnValue) writePushDup(StackItem.Type.valueOf(operatorResult)); writePopBoxing(operatorResult); makeVarStore(variable); variable.setValue(!stackPeek().isConstant() ? null : stackPeek().getMemory()); stackPop(); } } } return null; } void writeDebugMessage(String message) { writePushEnv(); writePushConstString(message); writeSysDynamicCall(Environment.class, "echo", void.class, String.class); } public void writeConditional(ExprStmtToken condition, LabelNode successLabel) { writeExpression(condition, true, false); writePopBoolean(); code.add(new JumpInsnNode(IFEQ, successLabel)); stackPop(); } public Memory writeExpression(ExprStmtToken expression, boolean returnValue, boolean returnMemory) { return writeExpression(expression, returnValue, returnMemory, true); } public Memory tryCalculateExpression(ExprStmtToken expression) { return writeExpression(expression, true, true, false); } @SuppressWarnings("unchecked") public Memory writeExpression(ExprStmtToken expression, boolean returnValue, boolean returnMemory, boolean writeOpcode) { int initStackSize = method.getStackCount(); exprStackInit.push(initStackSize); if (!expression.isStmtList()) { if (expression.getAsmExpr() == null) { throw new CriticalException("Invalid expression token without asm expr, on line " + expression.getMeta().getStartLine() + ", expr = " + expression.getWord()); } expression = expression.getAsmExpr(); // new ASMExpression(compiler.getEnvironment(), compiler.getContext(), expression).getResult(); } List<Token> tokens = expression.getTokens(); int operatorCount = 0; for (Token token : tokens) { if (token instanceof OperatorExprToken) operatorCount++; } boolean invalid = false; for (Token token : tokens) { if (token == null) continue; writeTickTrigger(token); if (writeOpcode) { if (token instanceof StmtToken) { if (!(token instanceof ReturnStmtToken)) method.entity.setImmutable(false); } BaseStatementCompiler cmp = getCompiler(token.getClass()); if (cmp != null && !(cmp instanceof BaseExprCompiler)) { cmp.write(token); continue; } } if (token instanceof ValueExprToken) { // mixed, calls, numbers, strings, vars, etc. if (token instanceof CallExprToken && ((CallExprToken) token).getName() instanceof OperatorExprToken) { if (writeOpcode) { writePush((ValueExprToken) token, true, true); method.entity.setImmutable(false); } else break; } else stackPush((ValueExprToken) token); } else if (token instanceof OperatorExprToken) { // + - * / % && || or ! and == > < etc. operatorCount--; if (operatorCount >= 0) { Memory result; if (operatorCount == 0) { result = writeOperator((OperatorExprToken) token, returnValue, writeOpcode); } else result = writeOperator((OperatorExprToken) token, true, writeOpcode); if (!writeOpcode && result == null) { invalid = true; break; } if (result == null) method.entity.setImmutable(false); } } else break; } Memory result = null; if (!invalid && returnMemory && returnValue && !stackEmpty(false) && stackPeek().isConstant()) { result = stackPop().memory; invalid = true; } if (!invalid) { if (returnValue && !stackEmpty(false) && stackPeek().isKnown()) { if (returnMemory) result = tryWritePush(stackPop(), writeOpcode, returnValue, true); else writePush(stackPop()); } else if (method.getStackCount() > 0) { if (stackPeekToken() instanceof CallableExprToken) { if (returnMemory) result = tryWritePush(stackPopToken(), returnValue, writeOpcode, true); else writePush(stackPopToken(), returnValue, true); } else if (stackPeek().isConstant()) { stackPop(); } } } if (!returnValue && writeOpcode) { writePopAll(method.getStackCount() - initStackSize); } else if (!writeOpcode) { int count = method.getStackCount() - initStackSize; for (int i = 0; i < count; i++) { stackPop(); } } exprStackInit.pop(); return result; } void makePop(StackItem.Type type) { switch (type.size()) { case 2: code.add(new InsnNode(POP2)); break; case 1: code.add(new InsnNode(POP)); break; default: throw new IllegalArgumentException("Invalid of size StackItem: " + type.size()); } } public void writePopAll(int count) { int i = 0; while (method.getStackCount() > 0 && i < count) { i++; StackItem o = stackPop(); ValueExprToken token = o.getToken(); StackItem.Type type = o.type; if (token == null) { switch (type.size()) { case 2: code.add(new InsnNode(POP2)); break; case 1: code.add(new InsnNode(POP)); break; default: throw new IllegalArgumentException("Invalid of size StackItem: " + type.size()); } } else/* if (o.isInvalidForOperations())*/ unexpectedToken(token); } } @Override public Entity compile() { writeDefineVariables(methodStatement.getLocal()); writeExpression(expression, false, false); method.popAll(); return null; } public static class NoSuchMethodException extends RuntimeException { public NoSuchMethodException(Class clazz, String method, Class... parameters) { super("No such method " + clazz.getName() + "." + method + "(" + StringUtils.join(parameters, ", ") + ")"); } } public static class UnsupportedTokenException extends RuntimeException { protected final Token token; public UnsupportedTokenException(Token token) { this.token = token; } } }
jphp-core/src/org/develnext/jphp/core/compiler/jvm/statement/ExpressionStmtCompiler.java
package org.develnext.jphp.core.compiler.jvm.statement; import org.develnext.jphp.core.compiler.common.ASMExpression; import org.develnext.jphp.core.compiler.common.misc.StackItem; import org.develnext.jphp.core.compiler.common.util.CompilerUtils; import org.develnext.jphp.core.compiler.jvm.Constants; import org.develnext.jphp.core.compiler.jvm.JvmCompiler; import org.develnext.jphp.core.compiler.jvm.misc.LocalVariable; import org.develnext.jphp.core.compiler.jvm.statement.expr.*; import org.develnext.jphp.core.compiler.jvm.statement.expr.operator.DynamicAccessCompiler; import org.develnext.jphp.core.compiler.jvm.statement.expr.operator.InstanceOfCompiler; import org.develnext.jphp.core.compiler.jvm.statement.expr.value.*; import org.develnext.jphp.core.tokenizer.TokenMeta; import org.develnext.jphp.core.tokenizer.token.OpenEchoTagToken; import org.develnext.jphp.core.tokenizer.token.Token; import org.develnext.jphp.core.tokenizer.token.expr.ClassExprToken; import org.develnext.jphp.core.tokenizer.token.expr.OperatorExprToken; import org.develnext.jphp.core.tokenizer.token.expr.ValueExprToken; import org.develnext.jphp.core.tokenizer.token.expr.operator.*; import org.develnext.jphp.core.tokenizer.token.expr.value.*; import org.develnext.jphp.core.tokenizer.token.expr.value.macro.*; import org.develnext.jphp.core.tokenizer.token.stmt.*; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import php.runtime.Memory; import php.runtime.OperatorUtils; import php.runtime.annotation.Runtime; import php.runtime.common.Association; import php.runtime.common.Messages; import php.runtime.common.StringUtils; import php.runtime.env.Environment; import php.runtime.env.TraceInfo; import php.runtime.exceptions.CriticalException; import php.runtime.ext.support.compile.CompileClass; import php.runtime.ext.support.compile.CompileConstant; import php.runtime.ext.support.compile.CompileFunction; import php.runtime.invoke.InvokeHelper; import php.runtime.invoke.ObjectInvokeHelper; import php.runtime.invoke.cache.FunctionCallCache; import php.runtime.invoke.cache.MethodCallCache; import php.runtime.lang.ForeachIterator; import php.runtime.lang.IObject; import php.runtime.memory.*; import php.runtime.memory.helper.UndefinedMemory; import php.runtime.memory.support.MemoryUtils; import php.runtime.reflection.*; import php.runtime.reflection.support.Entity; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import static org.objectweb.asm.Opcodes.*; public class ExpressionStmtCompiler extends StmtCompiler { protected final MethodStmtCompiler method; protected final MethodStmtToken methodStatement; protected final ExprStmtToken expression; private MethodNode node; private InsnList code; private Stack<Integer> exprStackInit = new Stack<Integer>(); private int lastLineNumber = -1; private Map<Class<? extends Token>, BaseStatementCompiler> compilers; private static final Map<Class<? extends Token>, Class<? extends BaseStatementCompiler>> compilerRules; static { compilerRules = new HashMap<Class<? extends Token>, Class<? extends BaseStatementCompiler>>(); compilerRules.put(IfStmtToken.class, IfElseCompiler.class); compilerRules.put(SwitchStmtToken.class, SwitchCompiler.class); compilerRules.put(FunctionStmtToken.class, FunctionCompiler.class); compilerRules.put(EchoRawToken.class, EchoRawCompiler.class); compilerRules.put(EchoStmtToken.class, EchoCompiler.class); compilerRules.put(OpenEchoTagToken.class, OpenEchoTagCompiler.class); compilerRules.put(ReturnStmtToken.class, ReturnCompiler.class); compilerRules.put(BodyStmtToken.class, BodyCompiler.class); compilerRules.put(WhileStmtToken.class, WhileCompiler.class); compilerRules.put(DoStmtToken.class, DoCompiler.class); compilerRules.put(ForStmtToken.class, ForCompiler.class); compilerRules.put(ForeachStmtToken.class, ForeachCompiler.class); compilerRules.put(TryStmtToken.class, TryCatchCompiler.class); compilerRules.put(ThrowStmtToken.class, ThrowCompiler.class); compilerRules.put(BreakStmtToken.class, JumpCompiler.class); compilerRules.put(ContinueStmtToken.class, JumpCompiler.class); compilerRules.put(GotoStmtToken.class, GotoCompiler.class); compilerRules.put(LabelStmtToken.class, GotoLabelCompiler.class); compilerRules.put(GlobalStmtToken.class, GlobalDefinitionCompiler.class); compilerRules.put(StaticStmtToken.class, StaticDefinitionCompiler.class); compilerRules.put(JvmCompiler.ClassInitEnvironment.class, ClassInitEnvironmentCompiler.class); // values compilerRules.put(BooleanExprToken.class, BooleanValueCompiler.class); compilerRules.put(IntegerExprToken.class, IntValueCompiler.class); compilerRules.put(NullExprToken.class, NullValueCompiler.class); compilerRules.put(DoubleExprToken.class, DoubleValueCompiler.class); compilerRules.put(StringExprToken.class, StringValueCompiler.class); compilerRules.put(ShellExecExprToken.class, ShellExecValueCompiler.class); compilerRules.put(IncludeExprToken.class, ImportCompiler.class); compilerRules.put(IncludeOnceExprToken.class, ImportCompiler.class); compilerRules.put(RequireExprToken.class, ImportCompiler.class); compilerRules.put(RequireOnceExprToken.class, ImportCompiler.class); compilerRules.put(NewExprToken.class, NewValueCompiler.class); compilerRules.put(StringBuilderExprToken.class, StringBuilderValueCompiler.class); compilerRules.put(UnsetExprToken.class, UnsetCompiler.class); compilerRules.put(IssetExprToken.class, IssetCompiler.class); compilerRules.put(EmptyExprToken.class, EmptyCompiler.class); compilerRules.put(DieExprToken.class, DieCompiler.class); compilerRules.put(StaticExprToken.class, StaticValueCompiler.class); compilerRules.put(ClosureStmtToken.class, ClosureValueCompiler.class); compilerRules.put(GetVarExprToken.class, VarVarValueCompiler.class); compilerRules.put(SelfExprToken.class, SelfValueCompiler.class); compilerRules.put(StaticAccessExprToken.class, StaticAccessValueCompiler.class); compilerRules.put(StaticAccessIssetExprToken.class, StaticAccessValueCompiler.class); compilerRules.put(StaticAccessUnsetExprToken.class, StaticAccessValueCompiler.class); compilerRules.put(ListExprToken.class, ListCompiler.class); compilerRules.put(YieldExprToken.class, YieldValueCompiler.class); // operation compilerRules.put(InstanceofExprToken.class, InstanceOfCompiler.class); compilerRules.put(DynamicAccessAssignExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessEmptyExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessGetRefExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessIssetExprToken.class, DynamicAccessCompiler.class); compilerRules.put(DynamicAccessUnsetExprToken.class, DynamicAccessCompiler.class); compilerRules.put(StaticAccessOperatorExprToken.class, StaticAccessValueAsOperatorCompiler.class); } public ExpressionStmtCompiler(MethodStmtCompiler method, ExprStmtToken expression) { super(method.getCompiler()); this.method = method; this.expression = expression; this.node = method.node; this.code = method.node.instructions; this.methodStatement = method.statement != null ? method.statement : MethodStmtToken.of("", method.clazz.statement); } public ExpressionStmtCompiler(JvmCompiler compiler) { super(compiler); this.expression = null; ClassStmtCompiler classStmtCompiler = new ClassStmtCompiler( compiler, new ClassStmtToken(new TokenMeta("", 0, 0, 0, 0)) ); this.method = new MethodStmtCompiler(classStmtCompiler, (MethodStmtToken) null); this.methodStatement = method.statement != null ? method.statement : MethodStmtToken.of("", method.clazz.statement); this.node = method.node; this.code = method.node.instructions; } @SuppressWarnings("unchecked") public <T extends Token> T write(Class<? extends Token> clazz, T token) { BaseStatementCompiler<T> cmp = (BaseStatementCompiler<T>) getCompiler(clazz); if (cmp == null) throw new CriticalException("Cannot find compiler for " + clazz.getName()); cmp.write(token); return token; } @SuppressWarnings("unchecked") public <T extends Token> T write(T token) { if (token == null) throw new IllegalArgumentException("Token cannot be null"); return write(token.getClass(), token); } @SuppressWarnings("unchecked") public <T extends ValueExprToken> T writeValue(T token, boolean returnValue) { BaseStatementCompiler<T> cmp = (BaseStatementCompiler<T>) getCompiler(token.getClass()); if (cmp == null) throw new CriticalException("Cannot find compiler for " + token.getClass().getName()); if (cmp instanceof BaseExprCompiler) ((BaseExprCompiler) cmp).write(token, returnValue); else throw new CriticalException("Compiler is not for values"); return token; } @SuppressWarnings("unchecked") public <T extends Token> BaseStatementCompiler<T> getCompiler(Class<T> clazz) { if (compilers == null) { compilers = new HashMap<Class<? extends Token>, BaseStatementCompiler>(); } BaseStatementCompiler<T> r = compilers.get(clazz); if (r != null) return r; Class<? extends BaseStatementCompiler<T>> rule = (Class<? extends BaseStatementCompiler<T>>) compilerRules.get(clazz); if (rule == null) return null; try { r = rule.getConstructor(ExpressionStmtCompiler.class).newInstance(this); compilers.put(clazz, r); return r; } catch (Exception e) { throw new CriticalException(e); } } public MethodNode getMethodNode() { return node; } public MethodStmtCompiler getMethod() { return method; } public MethodStmtToken getMethodStatement() { return methodStatement; } public void makeVarStore(LocalVariable variable) { code.add(new VarInsnNode(ASTORE, variable.index)); } public void makeVarLoad(LocalVariable variable) { code.add(new VarInsnNode(ALOAD, variable.index)); } public void makeUnknown(AbstractInsnNode node) { code.add(node); } public LabelNode makeLabel() { LabelNode el; code.add(el = new LabelNode()); return el; } protected Memory getMacros(ValueExprToken token) { if (token instanceof SelfExprToken) { if (method.clazz.entity.isTrait()) { throw new IllegalArgumentException("Cannot use this in Traits"); } else { return new StringMemory(method.clazz.statement.getFulledName()); } } return null; } protected void stackPush(ValueExprToken token, StackItem.Type type) { method.push(new StackItem(token, type)); } public void stackPush(StackItem item) { method.push(item); } public void stackPush(Memory memory) { method.push(new StackItem(memory)); } public void stackPush(ValueExprToken token, Memory memory) { method.push(new StackItem(token, memory)); } public void stackPush(Memory.Type type) { stackPush(null, StackItem.Type.valueOf(type)); } public void stackPush(ValueExprToken token) { Memory o = CompilerUtils.toMemory(token); if (o != null) { stackPush(o); } else if (token instanceof StaticAccessExprToken) { StaticAccessExprToken access = (StaticAccessExprToken) token; if (access.getField() instanceof NameToken) { String constant = ((NameToken) access.getField()).getName(); String clazz = null; ClassEntity entity = null; if (access.getClazz() instanceof ParentExprToken) { entity = method.clazz.entity.getParent(); if (entity != null) clazz = entity.getName(); } else if (access.getClazz() instanceof FulledNameToken) { clazz = ((FulledNameToken) access.getClazz()).getName(); entity = compiler.getModule().findClass(clazz); } if (entity == null && method.clazz.entity != null && method.clazz.entity.getName().equalsIgnoreCase(clazz)) entity = method.clazz.entity; if (entity != null) { ConstantEntity c = entity.findConstant(constant); if (c != null && c.getValue() != null) { stackPush(c.getValue()); stackPeek().setLevel(-1); return; } } } stackPush(token, StackItem.Type.REFERENCE); } else { if (token instanceof VariableExprToken && !methodStatement.isUnstableVariable((VariableExprToken) token)) { LocalVariable local = method.getLocalVariable(((VariableExprToken) token).getName()); if (local != null && local.getValue() != null) { stackPush(token, local.getValue()); stackPeek().setLevel(-1); return; } } stackPush(token, StackItem.Type.REFERENCE); } stackPeek().setLevel(-1); } public StackItem stackPop() { return method.pop(); } public ValueExprToken stackPopToken() { return method.pop().getToken(); } public StackItem stackPeek() { return method.peek(); } public void setStackPeekAsImmutable(boolean value) { method.peek().immutable = value; } public void setStackPeekAsImmutable() { setStackPeekAsImmutable(true); } public ValueExprToken stackPeekToken() { return method.peek().getToken(); } public boolean stackEmpty(boolean relative) { if (relative) return method.getStackCount() == exprStackInit.peek(); else return method.getStackCount() == 0; } public void writeLineNumber(Token token) { if (token.getMeta().getStartLine() > lastLineNumber) { lastLineNumber = token.getMeta().getStartLine(); code.add(new LineNumberNode(lastLineNumber, new LabelNode())); } } public void writeWarning(Token token, String message) { writePushEnv(); writePushTraceInfo(token); writePushConstString(message); writePushConstNull(); writeSysDynamicCall(Environment.class, "warning", void.class, TraceInfo.class, String.class, Object[].class); } public void writePushBooleanAsMemory(boolean value) { if (value) code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "TRUE", Type.getDescriptor(Memory.class) )); else code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "FALSE", Type.getDescriptor(Memory.class) )); stackPush(Memory.Type.REFERENCE); } public void writePushMemory(Memory memory) { Memory.Type type = Memory.Type.REFERENCE; if (memory instanceof UndefinedMemory) { code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "UNDEFINED", Type.getDescriptor(Memory.class) )); } else if (memory instanceof NullMemory) { code.add(new FieldInsnNode( GETSTATIC, Type.getInternalName(Memory.class), "NULL", Type.getDescriptor(Memory.class) )); } else if (memory instanceof FalseMemory) { writePushConstBoolean(false); return; } else if (memory instanceof TrueMemory) { writePushConstBoolean(true); return; } else if (memory instanceof KeyValueMemory) { writePushMemory(((KeyValueMemory) memory).key); writePopBoxing(); writePushMemory(((KeyValueMemory) memory).getValue()); writePopBoxing(); Object arrayKey = ((KeyValueMemory) memory).getArrayKey(); if (arrayKey instanceof String) { writePushConstString((String) arrayKey); writeSysStaticCall(KeyValueMemory.class, "valueOf", Memory.class, Memory.class, Memory.class, String.class); } else if (arrayKey instanceof LongMemory) { writePushConstantMemory((Memory) arrayKey); writeSysStaticCall(KeyValueMemory.class, "valueOf", Memory.class, Memory.class, Memory.class, Memory.class); } else { writeSysStaticCall(KeyValueMemory.class, "valueOf", Memory.class, Memory.class, Memory.class); } setStackPeekAsImmutable(); return; } else if (memory instanceof ReferenceMemory) { code.add(new TypeInsnNode(NEW, Type.getInternalName(ReferenceMemory.class))); code.add(new InsnNode(DUP)); code.add(new MethodInsnNode(INVOKESPECIAL, Type.getInternalName(ReferenceMemory.class), Constants.INIT_METHOD, "()V", false)); } else if (memory instanceof ArrayMemory) { ArrayMemory array = (ArrayMemory) memory; writePushConstInt(array.size()); if (!array.isList()) { writeSysStaticCall(ArrayMemory.class, "createHashed", ArrayMemory.class, int.class); } else { writeSysStaticCall(ArrayMemory.class, "createListed", ArrayMemory.class, int.class); } ForeachIterator foreachIterator = ((ArrayMemory) memory).foreachIterator(false, false); while (foreachIterator.next()) { writePushDup(); if (array.isList()) { writePushMemory(foreachIterator.getValue()); writePopBoxing(); writeSysDynamicCall(ArrayMemory.class, "add", ReferenceMemory.class, Memory.class); } else { Memory key = foreachIterator.getMemoryKey(); writePushMemory(key); if (!key.isString()) { writePopBoxing(); } writePushMemory(foreachIterator.getValue()); writePopBoxing(); writeSysDynamicCall(ArrayMemory.class, "put", ReferenceMemory.class, Object.class, Memory.class); } writePopAll(1); } stackPop(); stackPush(memory); setStackPeekAsImmutable(); return; } else { switch (memory.type) { case INT: { code.add(new LdcInsnNode(memory.toLong())); type = Memory.Type.INT; } break; case DOUBLE: { code.add(new LdcInsnNode(memory.toDouble())); type = Memory.Type.DOUBLE; } break; case STRING: { code.add(new LdcInsnNode(memory.toString())); type = Memory.Type.STRING; } break; } } stackPush(type); setStackPeekAsImmutable(); } public boolean writePopBoxing(boolean asImmutable) { return writePopBoxing(stackPeek().type, asImmutable); } public boolean writePopBoxing(boolean asImmutable, boolean useConstants) { return writePopBoxing(stackPeek().type, asImmutable, useConstants); } public boolean writePopBoxing() { return writePopBoxing(false); } public boolean writePopBoxing(Class<?> clazz, boolean asImmutable) { return writePopBoxing(StackItem.Type.valueOf(clazz), asImmutable); } public boolean writePopBoxing(Class<?> clazz) { return writePopBoxing(clazz, false); } public boolean writePopBoxing(StackItem.Type type) { return writePopBoxing(type, false); } public boolean writePopBoxing(StackItem.Type type, boolean asImmutable) { return writePopBoxing(type, asImmutable, true); } public boolean writePopBoxing(StackItem.Type type, boolean asImmutable, boolean useConstants) { switch (type) { case BOOL: if (useConstants && code.getLast() instanceof InsnNode) { InsnNode node = (InsnNode) code.getLast(); switch (node.getType()) { case ICONST_0: case ICONST_1: case ICONST_2: case ICONST_3: case ICONST_4: case ICONST_5: code.remove(node); stackPop(); writePushBooleanAsMemory(node.getType() != ICONST_0); break; default: writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); } } else { writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); } setStackPeekAsImmutable(); return true; case SHORT: case BYTE: case LONG: case INT: { if (useConstants && code.getLast() instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) code.getLast(); code.remove(node); stackPop(); writePushConstantMemory(LongMemory.valueOf((Long) node.cst)); } else { writeSysStaticCall(LongMemory.class, "valueOf", Memory.class, type.toClass()); } setStackPeekAsImmutable(); } return true; case FLOAT: case DOUBLE: { if (useConstants && code.getLast() instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) code.getLast(); code.remove(node); stackPop(); if (type == StackItem.Type.FLOAT) { writePushConstantMemory(DoubleMemory.valueOf((Float) node.cst)); } else { writePushConstantMemory(DoubleMemory.valueOf((Double) node.cst)); } } else { writeSysStaticCall(DoubleMemory.class, "valueOf", Memory.class, type.toClass()); } setStackPeekAsImmutable(); return true; } case STRING: { if (useConstants && code.getLast() instanceof LdcInsnNode) { LdcInsnNode node = (LdcInsnNode) code.getLast(); code.remove(node); stackPop(); writePushConstantMemory(StringMemory.valueOf(node.cst.toString())); } else { writeSysStaticCall(StringMemory.class, "valueOf", Memory.class, String.class); } setStackPeekAsImmutable(); return true; } case REFERENCE: { if (asImmutable) { writePopImmutable(); } } break; } return false; } public void writePushSmallInt(int value) { switch (value) { case -1: code.add(new InsnNode(ICONST_M1)); break; case 0: code.add(new InsnNode(ICONST_0)); break; case 1: code.add(new InsnNode(ICONST_1)); break; case 2: code.add(new InsnNode(ICONST_2)); break; case 3: code.add(new InsnNode(ICONST_3)); break; case 4: code.add(new InsnNode(ICONST_4)); break; case 5: code.add(new InsnNode(ICONST_5)); break; default: code.add(new LdcInsnNode(value)); } stackPush(Memory.Type.INT); } public void writePushScalarBoolean(boolean value) { writePushSmallInt(value ? 1 : 0); stackPop(); stackPush(value ? Memory.TRUE : Memory.FALSE); } public void writePushString(String value) { writePushMemory(new StringMemory(value)); } public void writePushConstString(String value) { writePushString(value); } public void writePushConstDouble(double value) { code.add(new LdcInsnNode(value)); stackPush(null, StackItem.Type.DOUBLE); } public void writePushConstFloat(float value) { code.add(new LdcInsnNode(value)); stackPush(null, StackItem.Type.FLOAT); } public void writePushConstLong(long value) { code.add(new LdcInsnNode(value)); stackPush(null, StackItem.Type.LONG); } public void writePushConstInt(int value) { writePushSmallInt(value); } public void writePushConstShort(short value) { writePushConstInt(value); stackPop(); stackPush(null, StackItem.Type.SHORT); } public void writePushConstByte(byte value) { writePushConstInt(value); stackPop(); stackPush(null, StackItem.Type.BYTE); } public void writePushConstBoolean(boolean value) { writePushConstInt(value ? 1 : 0); stackPop(); stackPush(null, StackItem.Type.BOOL); } public void writePushSelf(boolean withLower) { if (method.clazz.entity.isTrait()) { if (method.getLocalVariable("~class_name") != null) { writeVarLoad("~class_name"); } else { writePushEnv(); writeSysDynamicCall(Environment.class, "__getMacroClass", Memory.class); } writePopString(); if (withLower) writePushDupLowerCase(); } else { writePushConstString(method.clazz.statement.getFulledName()); if (withLower) writePushConstString(method.clazz.statement.getFulledName().toLowerCase()); } } public void writePushStatic() { writePushEnv(); writeSysDynamicCall(Environment.class, "getLateStatic", String.class); } public void writePushParent(Token token) { writePushEnv(); writePushTraceInfo(token); if (method.getLocalVariable("~class_name") != null) { writeVarLoad("~class_name"); writeSysDynamicCall(Environment.class, "__getParent", String.class, TraceInfo.class, String.class); } else { writeSysDynamicCall(Environment.class, "__getParent", String.class, TraceInfo.class); } } public void writePushLocal() { writeVarLoad("~local"); } public void writePushEnv() { method.entity.setUsesStackTrace(true); LocalVariable variable = method.getLocalVariable("~env"); if (variable == null) { if (!methodStatement.isStatic()) writePushEnvFromSelf(); else throw new RuntimeException("Cannot find `~env` variable"); return; } stackPush(Memory.Type.REFERENCE); makeVarLoad(variable); } public void writePushEnvFromSelf() { method.entity.setUsesStackTrace(true); writeVarLoad("~this"); writeSysDynamicCall(null, "getEnvironment", Environment.class); } public void writePushDup(StackItem.Type type) { stackPush(null, type); if (type.size() == 2) code.add(new InsnNode(DUP2)); else code.add(new InsnNode(DUP)); } public void writePushDup() { StackItem item = method.peek(); stackPush(item); if (item.type.size() == 2) code.add(new InsnNode(DUP2)); else code.add(new InsnNode(DUP)); } public void writePushDupLowerCase() { writePushDup(); writePopString(); writeSysDynamicCall(String.class, "toLowerCase", String.class); } public void writePushNull() { writePushMemory(Memory.NULL); } public void writePushVoid() { writePushMemory(Memory.UNDEFINED); } public void writePushConstNull() { stackPush(Memory.Type.REFERENCE); code.add(new InsnNode(ACONST_NULL)); } public void writePushNewObject(Class clazz) { code.add(new TypeInsnNode(NEW, Type.getInternalName(clazz))); stackPush(Memory.Type.REFERENCE); writePushDup(); writeSysCall(clazz, INVOKESPECIAL, Constants.INIT_METHOD, void.class); stackPop(); } public void writePushNewObject(String internalName, Class... paramClasses) { code.add(new TypeInsnNode(NEW, internalName)); stackPush(Memory.Type.REFERENCE); writePushDup(); writeSysCall(internalName, INVOKESPECIAL, Constants.INIT_METHOD, void.class, paramClasses); stackPop(); } public void writePushStaticCall(Method method) { writeSysStaticCall( method.getDeclaringClass(), method.getName(), method.getReturnType(), method.getParameterTypes() ); } Memory writePushCompileFunction(CallExprToken function, CompileFunction compileFunction, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { CompileFunction.Method method = compileFunction.find(function.getParameters().size()); if (method == null) { if (!writeOpcode) return Memory.NULL; writeWarning(function, Messages.ERR_EXPECT_LEAST_PARAMS.fetch( compileFunction.name, compileFunction.getMinArgs(), function.getParameters().size() )); if (returnValue) writePushNull(); return null; } else if (!method.isVarArg() && method.argsCount < function.getParameters().size()) { if (!writeOpcode) return Memory.NULL; writeWarning(function, Messages.ERR_EXPECT_EXACTLY_PARAMS.fetch( compileFunction.name, method.argsCount, function.getParameters().size() )); if (returnValue) writePushNull(); return null; } if (statistic != null) statistic.returnType = StackItem.Type.valueOf(method.resultType); Class[] types = method.parameterTypes; ListIterator<ExprStmtToken> iterator = function.getParameters().listIterator(); Object[] arguments = new Object[types.length]; int j = 0; boolean immutable = method.isImmutable; boolean init = false; for (int i = 0; i < method.parameterTypes.length; i++) { Class<?> argType = method.parameterTypes[i]; boolean isRef = method.references[i]; boolean isMutable = method.isPresentAnnotationOfParam(i, Runtime.MutableValue.class); if (method.isPresentAnnotationOfParam(i, Runtime.GetLocals.class)) { if (!writeOpcode) return null; immutable = false; writePushLocal(); } else if (argType == Environment.class) { if (immutable) { arguments[i] = compiler.getEnvironment(); } else { if (!writeOpcode) return null; writePushEnv(); } } else if (argType == TraceInfo.class) { if (immutable) { arguments[i] = function.toTraceInfo(compiler.getContext()); } else { if (!writeOpcode) return null; writePushTraceInfo(function); } } else { if (argType == Memory[].class) { Memory[] args = new Memory[function.getParameters().size() - j]; boolean arrCreated = false; for (int t = 0; t < function.getParameters().size() - j; t++) { ExprStmtToken next = iterator.next(); if (immutable) args[t] = writeExpression(next, true, true, false); if (args[t] == null) { if (!writeOpcode) return null; if (!arrCreated) { if (immutable) { for (int n = 0; n < i /*j*/; n++) { if (arguments[n] instanceof TraceInfo) { writePushTraceInfo(function); } else if (arguments[n] instanceof Environment) { writePushEnv(); } else { writePushMemory((Memory) arguments[n]); writePop(types[n], true, true); arguments[t] = null; } } } // create new array writePushSmallInt(args.length); code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Memory.class))); stackPop(); stackPush(Memory.Type.REFERENCE); arrCreated = true; } writePushDup(); writePushSmallInt(t); writeExpression( next, true, false, writeOpcode ); //if (!isRef) BUGFIX - array is memory[] and so we need to convert value to memory writePopBoxing(!isRef); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); immutable = false; } } if (!immutable && !arrCreated) { code.add(new InsnNode(ACONST_NULL)); stackPush(Memory.Type.REFERENCE); } arguments[i/*j*/] = MemoryUtils.valueOf(args); } else { ExprStmtToken next = iterator.next(); if (!immutable && !init) { init = true; for (int k = 0; k < i/*j*/; k++) { if (arguments[k] != null) { if (arguments[k] instanceof TraceInfo) { writePushTraceInfo(function); } else if (arguments[k] instanceof Environment) { writePushEnv(); } else { writePushMemory((Memory) arguments[k]); writePop(types[k], true, isRef); arguments[k] = null; } } } } if (immutable) arguments[i/*j*/] = writeExpression(next, true, true, false); if (arguments[i/*j*/] == null) { if (!writeOpcode) return null; if (!init) { for (int n = 0; n < i/*j*/; n++) { if (arguments[n] instanceof TraceInfo) { writePushTraceInfo(function); } else if (arguments[n] instanceof Environment) { writePushEnv(); } else { writePushMemory((Memory) arguments[n]); writePop(types[n], true, false); } arguments[n] = null; } init = true; } if (isRef) writeExpression(next, true, false, writeOpcode); else { Memory tmp = writeExpression(next, true, true, true); if (tmp != null) writePushMemory(tmp); } writePop(argType, true, isMutable && !isRef); if (!isMutable && !isRef && stackPeek().type.isReference()) { writeSysDynamicCall(Memory.class, "toValue", Memory.class); } immutable = false; } j++; } } } if (immutable) { if (!returnValue) return null; Object[] typedArguments = new Object[arguments.length]; for (int i = 0; i < arguments.length; i++) { if (method.parameterTypes[i] != Memory.class && arguments[i] instanceof Memory) typedArguments[i] = method.converters[i].run((Memory) arguments[i]); //MemoryUtils.toValue((Memory)arguments[i], types[i]); else typedArguments[i] = arguments[i]; } try { Object value = method.method.invoke(null, typedArguments); return MemoryUtils.valueOf(value); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } if (!writeOpcode) return null; this.method.entity.setImmutable(false); writeLineNumber(function); writePushStaticCall(method.method); if (returnValue) { if (method.resultType == void.class) writePushNull(); setStackPeekAsImmutable(); } return null; } public void writePushParameters(Collection<Memory> memories) { writePushSmallInt(memories.size()); code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Memory.class))); stackPop(); stackPush(Memory.Type.REFERENCE); int i = 0; for (Memory param : memories) { writePushDup(); writePushSmallInt(i); writePushMemory(param); writePopBoxing(true, false); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); i++; } } public void writePushParameters(Collection<ExprStmtToken> parameters, Memory... additional) { writePushParameters(parameters, true, additional); } public void writePushParameters(Collection<ExprStmtToken> parameters, boolean useConstants, Memory... additional) { if (parameters.isEmpty()) { code.add(new InsnNode(ACONST_NULL)); stackPush(Memory.Type.REFERENCE); return; } if (useConstants && additional == null || additional.length == 0) { List<Memory> constantParameters = new ArrayList<Memory>(); for (ExprStmtToken param : parameters) { Memory paramMemory = writeExpression(param, true, true, false); if (paramMemory == null || paramMemory.isArray()) { // skip arrays. break; } constantParameters.add(paramMemory); } if (constantParameters.size() == parameters.size()) { writePushConstantMemoryArray(constantParameters); return; } } writePushSmallInt(parameters.size() + (additional == null ? 0 : additional.length)); code.add(new TypeInsnNode(ANEWARRAY, Type.getInternalName(Memory.class))); stackPop(); stackPush(Memory.Type.REFERENCE); int i = 0; for (ExprStmtToken param : parameters) { writePushDup(); writePushSmallInt(i); writeExpression(param, true, false); writePopBoxing(); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); i++; } if (additional != null) { for (Memory m : additional) { writePushDup(); writePushSmallInt(i); writePushMemory(m); writePopBoxing(); code.add(new InsnNode(AASTORE)); stackPop(); stackPop(); stackPop(); i++; } } } Memory writePushParentDynamicMethod(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { if (!writeOpcode) return null; StaticAccessExprToken dynamic = (StaticAccessExprToken) function.getName(); writeLineNumber(function); writePushThis(); if (dynamic.getField() != null) { if (dynamic.getField() instanceof NameToken) { String name = ((NameToken) dynamic.getField()).getName(); writePushConstString(name); writePushConstString(name.toLowerCase()); } else { writePush(dynamic.getField(), true, false); writePopString(); writePushDupLowerCase(); } } else { writeExpression(dynamic.getFieldExpr(), true, false); writePopString(); writePushDupLowerCase(); } writePushEnv(); writePushTraceInfo(dynamic); writePushParameters(function.getParameters()); writeSysStaticCall( ObjectInvokeHelper.class, "invokeParentMethod", Memory.class, Memory.class, String.class, String.class, Environment.class, TraceInfo.class, Memory[].class ); if (!returnValue) writePopAll(1); if (statistic != null) statistic.returnType = StackItem.Type.REFERENCE; return null; } Memory writePushDynamicMethod(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { if (!writeOpcode) return null; DynamicAccessExprToken access = (DynamicAccessExprToken) function.getName(); if (access instanceof DynamicAccessAssignExprToken) unexpectedToken(access); writeLineNumber(function); writeDynamicAccessPrepare(access, true); writePushParameters(function.getParameters()); writeSysStaticCall( ObjectInvokeHelper.class, "invokeMethod", Memory.class, Memory.class, String.class, String.class, Environment.class, TraceInfo.class, Memory[].class ); if (!returnValue) writePopAll(1); if (statistic != null) statistic.returnType = StackItem.Type.REFERENCE; return null; } boolean writePushFastStaticMethod(CallExprToken function, boolean returnValue) { StaticAccessExprToken access = (StaticAccessExprToken) function.getName(); CompileClass compileClass = compiler.getEnvironment().scope.findCompileClass(access.getClazz().getWord()); if (compileClass == null) return false; ClassEntity classEntity = compiler.getEnvironment().fetchClass(compileClass.getNativeClass()); MethodEntity methodEntity = classEntity.findMethod(access.getField().getWord().toLowerCase()); if (methodEntity != null && methodEntity.getNativeMethod() != null && methodEntity.getNativeMethod().isAnnotationPresent(Runtime.FastMethod.class)) { int cnt = methodEntity.getRequiredParamCount(); if (cnt > function.getParameters().size()) { writeWarning(function, Messages.ERR_EXPECT_EXACTLY_PARAMS.fetch( methodEntity.getClazzName() + "::" + methodEntity.getName(), cnt, function.getParameters().size() )); if (returnValue) writePushNull(); return true; } List<Memory> additional = new ArrayList<Memory>(); for (ParameterEntity param : methodEntity.getParameters()) { if (param.getDefaultValue() != null) additional.add(param.getDefaultValue()); else if (!additional.isEmpty()) throw new IllegalStateException("Arguments with default values must be located at the end"); } writePushEnv(); writePushParameters(function.getParameters(), additional.toArray(new Memory[0])); writeSysStaticCall( compileClass.getNativeClass(), methodEntity.getName(), Memory.class, Environment.class, Memory[].class ); if (!returnValue) writePopAll(1); return true; } return false; } Memory writePushStaticMethod(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { StaticAccessExprToken access = (StaticAccessExprToken) function.getName(); if (!writeOpcode) return null; writeLineNumber(function); if (writePushFastStaticMethod(function, returnValue)) return null; writePushEnv(); writePushTraceInfo(function.getName()); String methodName = null; ValueExprToken clazz = access.getClazz(); if ((clazz instanceof NameToken || (clazz instanceof SelfExprToken && !method.clazz.entity.isTrait())) && access.getField() instanceof NameToken) { String className; if (clazz instanceof SelfExprToken) className = getMacros(clazz).toString(); else className = ((NameToken) clazz).getName(); writePushString(className.toLowerCase()); methodName = ((NameToken) access.getField()).getName(); writePushString(methodName.toLowerCase()); writePushString(className); writePushString(methodName); writePushParameters(function.getParameters()); if (method.clazz.statement.isTrait()) { writePushConstNull(); writePushConstInt(0); } else { int cacheIndex = method.clazz.getAndIncCallMethCount(); writeGetStatic("$CALL_METH_CACHE", MethodCallCache.class); writePushConstInt(cacheIndex); } writeSysStaticCall( InvokeHelper.class, "callStatic", Memory.class, Environment.class, TraceInfo.class, String.class, String.class, // lower sign name String.class, String.class, // origin names Memory[].class, MethodCallCache.class, Integer.TYPE ); } else { if (clazz instanceof NameToken) { writePushString(((NameToken) clazz).getName()); writePushDupLowerCase(); } else if (clazz instanceof SelfExprToken) { writePushSelf(true); } else if (clazz instanceof StaticExprToken) { writePushStatic(); writePushDupLowerCase(); } else { writePush(clazz, true, false); writePopString(); writePushDupLowerCase(); } if (access.getField() != null) { ValueExprToken field = access.getField(); if (field instanceof NameToken) { writePushString(((NameToken) field).getName()); writePushString(((NameToken) field).getName().toLowerCase()); } else if (field instanceof ClassExprToken) { unexpectedToken(field); } else { writePush(access.getField(), true, false); writePopString(); writePushDupLowerCase(); } } else { writeExpression(access.getFieldExpr(), true, false); writePopString(); writePushDupLowerCase(); } writePushParameters(function.getParameters()); if (clazz instanceof StaticExprToken || method.clazz.statement.isTrait() || clazz instanceof VariableExprToken) { writePushConstNull(); writePushConstInt(0); } else { int cacheIndex = method.clazz.getAndIncCallMethCount(); writeGetStatic("$CALL_METH_CACHE", MethodCallCache.class); writePushConstInt(cacheIndex); } writeSysStaticCall( InvokeHelper.class, "callStaticDynamic", Memory.class, Environment.class, TraceInfo.class, String.class, String.class, String.class, String.class, Memory[].class, MethodCallCache.class, Integer.TYPE ); } if (statistic != null) statistic.returnType = StackItem.Type.REFERENCE; return null; } public static class PushCallStatistic { public StackItem.Type returnType = StackItem.Type.REFERENCE; } Memory writePushCall(CallExprToken function, boolean returnValue, boolean writeOpcode, PushCallStatistic statistic) { Token name = function.getName(); if (name instanceof NameToken) { String realName = ((NameToken) name).getName(); CompileFunction compileFunction = compiler.getScope().findCompileFunction(realName); // try find system function, like max, sin, cos, etc. if (compileFunction == null && name instanceof FulledNameToken && compiler.getEnvironment().fetchFunction(realName) == null && compiler.findFunction(realName) == null) { String tryName = ((FulledNameToken) name).getLastName().getName(); compileFunction = compiler.getScope().findCompileFunction(tryName); } if (compileFunction != null) { return writePushCompileFunction(function, compileFunction, returnValue, writeOpcode, statistic); } else { if (!writeOpcode) return null; method.entity.setImmutable(false); int index = method.clazz.getAndIncCallFuncCount(); writePushEnv(); writePushTraceInfo(function); writePushString(realName.toLowerCase()); writePushString(realName); writePushParameters(function.getParameters()); writeGetStatic("$CALL_FUNC_CACHE", FunctionCallCache.class); writePushConstInt(index); writeSysStaticCall( InvokeHelper.class, "call", Memory.class, Environment.class, TraceInfo.class, String.class, String.class, Memory[].class, FunctionCallCache.class, Integer.TYPE ); if (!returnValue) writePopAll(1); } } else if (name instanceof StaticAccessExprToken) { method.entity.setImmutable(false); if (((StaticAccessExprToken) name).isAsParent()) return writePushParentDynamicMethod(function, returnValue, writeOpcode, statistic); else return writePushStaticMethod(function, returnValue, writeOpcode, statistic); } else if (name instanceof DynamicAccessExprToken) { method.entity.setImmutable(false); return writePushDynamicMethod(function, returnValue, writeOpcode, statistic); } else { if (!writeOpcode) return null; method.entity.setImmutable(false); writeLineNumber(function); writePush((ValueExprToken) function.getName(), true, false); writePopBoxing(); writePushParameters(function.getParameters()); writePushEnv(); writePushTraceInfo(function); writeSysStaticCall( InvokeHelper.class, "callAny", Memory.class, Memory.class, Memory[].class, Environment.class, TraceInfo.class ); if (!returnValue) writePopAll(1); } return null; } public void writeDefineVariables(Collection<VariableExprToken> values) { for (VariableExprToken value : values) writeDefineVariable(value); } public void writeUndefineVariables(Collection<VariableExprToken> values) { LabelNode end = new LabelNode(); for (VariableExprToken value : values) writeUndefineVariable(value, end); } public void writeDefineGlobalVar(String name) { writePushEnv(); writePushConstString(name); writeSysDynamicCall(Environment.class, "getOrCreateGlobal", Memory.class, String.class); makeVarStore(method.getLocalVariable(name)); stackPop(); } public void writePushThis() { if (method.clazz.isClosure() || method.getGeneratorEntity() != null) { writeVarLoad("~this"); writeGetDynamic("self", Memory.class); } else { if (method.getLocalVariable("this") == null) { if (!methodStatement.isStatic()) { LabelNode label = writeLabel(node); LocalVariable local = method.addLocalVariable("this", label, Memory.class); writeDefineThis(local); } else { writePushNull(); return; } } writeVarLoad("this"); } } protected void writeDefineThis(LocalVariable variable) { if (method.clazz.isClosure() || method.getGeneratorEntity() != null) { writeVarLoad("~this"); writeGetDynamic("self", Memory.class); makeVarStore(variable); stackPop(); } else { LabelNode endLabel = new LabelNode(); LabelNode elseLabel = new LabelNode(); if (methodStatement.isStatic()) { writePushMemory(Memory.UNDEFINED); writeVarStore(variable, false, false); } else { writeVarLoad("~this"); writeSysDynamicCall(IObject.class, "isMock", Boolean.TYPE); code.add(new JumpInsnNode(IFEQ, elseLabel)); stackPop(); if (variable.isReference()) { writePushMemory(Memory.UNDEFINED); writeSysStaticCall(ReferenceMemory.class, "valueOf", Memory.class, Memory.class); } else { writePushMemory(Memory.UNDEFINED); } writeVarStore(variable, false, false); code.add(new JumpInsnNode(GOTO, endLabel)); code.add(elseLabel); writeVarLoad("~this"); writeSysStaticCall(ObjectMemory.class, "valueOf", Memory.class, IObject.class); makeVarStore(variable); stackPop(); code.add(endLabel); } } variable.pushLevel(); variable.setValue(null); variable.setImmutable(false); variable.setReference(true); } protected void writeDefineVariable(VariableExprToken value) { if (methodStatement.isUnusedVariable(value)) return; LocalVariable variable = method.getLocalVariable(value.getName()); if (variable == null) { LabelNode label = writeLabel(node, value.getMeta().getStartLine()); variable = method.addLocalVariable(value.getName(), label, Memory.class); if (methodStatement.isReference(value) || compiler.getScope().superGlobals.contains(value.getName())) { variable.setReference(true); } else { variable.setReference(false); } if (variable.name.equals("this") && method.getLocalVariable("~this") != null) { // $this writeDefineThis(variable); } else if (compiler.getScope().superGlobals.contains(value.getName())) { // super-globals writeDefineGlobalVar(value.getName()); } else if (methodStatement.isDynamicLocal()) { // ref-local variables writePushLocal(); writePushConstString(value.getName()); writeSysDynamicCall(Memory.class, "refOfIndex", Memory.class, String.class); makeVarStore(variable); stackPop(); variable.pushLevel(); variable.setValue(null); variable.setReference(true); } else { // simple local variables if (variable.isReference()) { writePushNewObject(ReferenceMemory.class); } else { writePushNull(); } makeVarStore(variable); stackPop(); variable.pushLevel(); } } else variable.pushLevel(); } protected void writeUndefineVariable(VariableExprToken value, LabelNode end) { LocalVariable variable = method.getLocalVariable(value.getName()); if (variable != null) variable.popLevel(); } public void writePushVariable(VariableExprToken value) { LocalVariable variable = method.getLocalVariable(value.getName()); if (variable == null || variable.getClazz() == null) writePushNull(); else { writeVarLoad(variable); } } public Memory tryWritePushVariable(VariableExprToken value, boolean heavyObjects) { if (methodStatement.isUnstableVariable(value)) return null; if (compiler.getScope().superGlobals.contains(value.getName())) return null; LocalVariable variable = method.getLocalVariable(value.getName()); if (variable == null || variable.getClazz() == null || methodStatement.isUnusedVariable(value)) { return Memory.NULL; } else { if (methodStatement.variable(value).isPassed()) return null; Memory mem = variable.getValue(); if (mem != null) { if (!heavyObjects) { if (mem.isArray() || mem.toString().length() > 100) { return null; } } return mem; } } return null; } public Memory writePushArray(ArrayExprToken array, boolean returnMemory, boolean writeOpcode) { if (array.getParameters().isEmpty()) { if (returnMemory) return new ArrayMemory(); else if (writeOpcode) writeSysStaticCall(ArrayMemory.class, "valueOf", Memory.class); } else { ArrayMemory ret = returnMemory ? new ArrayMemory() : null; if (ret == null) { boolean map = false; for (ExprStmtToken token : array.getParameters()) { for (Token sub : token.getTokens()) { if (sub instanceof KeyValueExprToken) { map = true; break; } } if (map) break; } writePushConstInt(array.getParameters().size()); if (map) { writeSysStaticCall(ArrayMemory.class, "createHashed", ArrayMemory.class, int.class); } else { writeSysStaticCall(ArrayMemory.class, "createListed", ArrayMemory.class, int.class); } } for (ExprStmtToken param : array.getParameters()) { if (ret == null) writePushDup(); Memory result = writeExpression(param, true, true, ret == null); if (result != null) { if (ret != null) { ret.add(result); continue; } else { writePushMemory(result); } } else { if (!writeOpcode) { return null; } ret = null; } if (result == null && returnMemory) { return writePushArray(array, false, writeOpcode); } writePopBoxing(); writePopImmutable(); writeSysDynamicCall(ArrayMemory.class, "add", ReferenceMemory.class, Memory.class); writePopAll(1); } if (ret != null) return ret; } setStackPeekAsImmutable(); return null; } public int writePushTraceInfo(Token token) { return writePushTraceInfo(token.getMeta().getStartLine(), token.getMeta().getStartPosition()); } void writePushGetFromArray(int index, Class clazz) { writePushSmallInt(index); code.add(new InsnNode(AALOAD)); stackPop(); stackPop(); stackPush(null, StackItem.Type.valueOf(clazz)); } void writePushGetArrayLength() { code.add(new InsnNode(ARRAYLENGTH)); stackPop(); stackPush(null, StackItem.Type.INT); } int createTraceInfo(Token token) { return method.clazz.addTraceInfo(token); } int writePushTraceInfo(int line, int position) { int index = method.clazz.addTraceInfo(line, position); writePushTraceInfo(index); return index; } void writePushTraceInfo(int traceIndex) { writeGetStatic("$TRC", TraceInfo[].class); writePushGetFromArray(traceIndex, TraceInfo.class); } void writePushCreateTraceInfo(int line, int position) { writeGetStatic("$FN", String.class); writePushMemory(LongMemory.valueOf(line)); writePushMemory(LongMemory.valueOf(position)); writeSysStaticCall(TraceInfo.class, "valueOf", TraceInfo.class, String.class, Long.TYPE, Long.TYPE); } int writePushConstantMemory(Memory memory) { int index = method.clazz.addMemoryConstant(memory); writeGetStatic("$MEM", Memory[].class); writePushGetFromArray(index, Memory.class); return index; } int writePushConstantMemoryArray(Collection<Memory> memories) { int index = method.clazz.addMemoryArray(memories); writeGetStatic("$AMEM", Memory[][].class); writePushGetFromArray(index, Memory[].class); return index; } Memory tryWritePushMacro(MacroToken macro, boolean writeOpcode) { if (macro instanceof LineMacroToken) { return LongMemory.valueOf(macro.getMeta().getStartLine() + 1); } else if (macro instanceof FileMacroToken) { return new StringMemory(compiler.getSourceFile()); } else if (macro instanceof DirMacroToken) { String sourceFile = compiler.getSourceFile(); String parent = new File(sourceFile).getParent(); // Fix issue #198. if (sourceFile.startsWith(parent + "//") && parent.endsWith(":")) { parent += "//"; } return new StringMemory(parent); } else if (macro instanceof FunctionMacroToken) { if (method.clazz == null) { return Memory.CONST_EMPTY_STRING; } if (method.clazz.isClosure()) { return new StringMemory("{closure}"); } if (StringUtils.isEmpty(method.clazz.getFunctionName())) return method.clazz.isSystem() ? Memory.CONST_EMPTY_STRING : method.getRealName() == null ? Memory.CONST_EMPTY_STRING : new StringMemory(method.getRealName()); else { return method.clazz.getFunctionName() == null ? Memory.CONST_EMPTY_STRING : new StringMemory(method.clazz.getFunctionName()); } } else if (macro instanceof MethodMacroToken) { if (method.clazz == null) { return Memory.CONST_EMPTY_STRING; } if (method.clazz.isClosure()) { return new StringMemory("{closure}"); } if (method.clazz.isSystem()) return method.clazz.getFunctionName() != null ? new StringMemory(method.clazz.getFunctionName()) : Memory.NULL; else return new StringMemory( method.clazz.entity.getName() + (method.getRealName() == null ? "" : "::" + method.getRealName()) ); } else if (macro instanceof ClassMacroToken) { if (method.clazz.entity.isTrait()) { if (writeOpcode) { writePushEnv(); writeSysDynamicCall(Environment.class, "__getMacroClass", Memory.class); } return null; } else { if (method.clazz.getClassContext() != null) { return new StringMemory(method.clazz.getClassContext().getFulledName()); } else { return new StringMemory(method.clazz.isSystem() ? "" : method.clazz.entity.getName()); } } } else if (macro instanceof NamespaceMacroToken) { return new StringMemory( compiler.getNamespace() == null || compiler.getNamespace().getName() == null ? "" : compiler.getNamespace().getName().getName() ); } else if (macro instanceof TraitMacroToken) { if (method.clazz.entity.isTrait()) return new StringMemory(method.clazz.entity.getName()); else return Memory.CONST_EMPTY_STRING; } else throw new IllegalArgumentException("Unsupported macro value: " + macro.getWord()); } Memory writePushName(NameToken token, boolean returnMemory, boolean writeOpcode) { CompileConstant constant = compiler.getScope().findCompileConstant(token.getName()); if (constant != null) { if (returnMemory) return constant.value; else if (writeOpcode) writePushMemory(constant.value); } else { ConstantEntity constantEntity = compiler.findConstant(token.getName()); /*if (constantEntity == null) // TODO: maybe it's not needed! we should search a namespaced constant in local context constantEntity = compiler.getScope().findUserConstant(token.getName()); */ if (constantEntity != null) { if (returnMemory) return constantEntity.getValue(); else if (writeOpcode) { writePushMemory(constantEntity.getValue()); setStackPeekAsImmutable(); } } else { if (!writeOpcode) return null; writePushEnv(); writePushString(token.getName()); writePushString(token.getName().toLowerCase()); // writePushDupLowerCase(); writePushTraceInfo(token); writeSysDynamicCall(Environment.class, "__getConstant", Memory.class, String.class, String.class, TraceInfo.class); setStackPeekAsImmutable(); } } return null; } Memory tryWritePushReference(StackItem item, boolean writeOpcode, boolean toStack, boolean heavyObjects) { if (item.getToken() instanceof VariableExprToken) { writePushVariable((VariableExprToken) item.getToken()); return null; } return tryWritePush(item, writeOpcode, toStack, heavyObjects); } Memory tryWritePush(StackItem item, boolean writeOpcode, boolean toStack, boolean heavyObjects) { if (item.getToken() != null) return tryWritePush(item.getToken(), true, writeOpcode, heavyObjects); else if (item.getMemory() != null) { return item.getMemory(); } else if (toStack) stackPush(null, item.type); return null; } StackItem.Type tryGetType(StackItem item) { if (item.getToken() != null) { return tryGetType(item.getToken()); } else if (item.getMemory() != null) { return StackItem.Type.valueOf(item.getMemory().type); } else return item.type; } public boolean tryIsImmutable(StackItem item) { if (item.getToken() != null) { return tryIsImmutable(item.getToken()); } else if (item.getMemory() != null) return true; else return item.type.isConstant(); } public Memory tryWritePush(StackItem item) { return tryWritePush(item, true, true, true); } public void writePush(StackItem item) { writePush(item, true, false); } public void writePush(StackItem item, boolean tryGetMemory, boolean heavyObjects) { if (tryGetMemory) { Memory memory = tryWritePushReference(item, true, true, heavyObjects); if (memory != null) writePushMemory(memory); } else { tryWritePushReference(item, true, true, heavyObjects); } } public void writePush(StackItem item, StackItem.Type castType) { Memory memory = tryWritePush(item); if (memory != null) { switch (castType) { case DOUBLE: writePushConstDouble(memory.toDouble()); return; case FLOAT: writePushConstFloat((float) memory.toDouble()); return; case LONG: writePushConstLong(memory.toLong()); return; case INT: writePushConstInt((int) memory.toLong()); return; case SHORT: writePushConstInt((short) memory.toLong()); return; case BYTE: writePushConstByte((byte) memory.toLong()); return; case BOOL: writePushConstBoolean(memory.toBoolean()); return; case STRING: writePushConstString(memory.toString()); return; } writePushMemory(memory); } writePop(castType.toClass(), true, true); } boolean tryIsImmutable(ValueExprToken value) { if (value instanceof IntegerExprToken) return true; else if (value instanceof DoubleExprToken) return true; else if (value instanceof StringExprToken) return true; else if (value instanceof LineMacroToken) return true; else if (value instanceof MacroToken) return true; else if (value instanceof ArrayExprToken) return true; else if (value instanceof StringBuilderExprToken) return true; else if (value instanceof NameToken) return true; else if (value instanceof CallExprToken) { PushCallStatistic statistic = new PushCallStatistic(); writePushCall((CallExprToken) value, true, false, statistic); return statistic.returnType.isConstant(); } return false; } StackItem.Type tryGetType(ValueExprToken value) { if (value instanceof IntegerExprToken) return StackItem.Type.LONG; else if (value instanceof DoubleExprToken) return StackItem.Type.DOUBLE; else if (value instanceof StringExprToken) return StackItem.Type.STRING; else if (value instanceof LineMacroToken) return StackItem.Type.LONG; else if (value instanceof MacroToken) return StackItem.Type.STRING; else if (value instanceof ArrayExprToken) return StackItem.Type.ARRAY; else if (value instanceof StringBuilderExprToken) return StackItem.Type.STRING; else if (value instanceof CallExprToken) { PushCallStatistic statistic = new PushCallStatistic(); writePushCall((CallExprToken) value, true, false, statistic); return statistic.returnType; } else if (value instanceof NameToken) { Memory tmpMemory = writePushName((NameToken) value, true, false); return tmpMemory == null ? StackItem.Type.REFERENCE : StackItem.Type.valueOf(tmpMemory.type); } else return StackItem.Type.REFERENCE; } Memory tryWritePush(ValueExprToken value, boolean returnValue, boolean writeOpcode, boolean heavyObjects) { if (writeOpcode) { BaseStatementCompiler compiler = getCompiler(value.getClass()); if (compiler != null) { if (compiler instanceof BaseExprCompiler) { ((BaseExprCompiler) compiler).write(value, returnValue); } else throw new IllegalStateException("Compiler must be extended by " + BaseExprCompiler.class.getName()); return null; } } if (value instanceof NameToken) { return writePushName((NameToken) value, returnValue, writeOpcode); } if (value instanceof ArrayExprToken) { return writePushArray((ArrayExprToken) value, returnValue, writeOpcode); } else if (value instanceof CallExprToken) { return writePushCall((CallExprToken) value, returnValue, writeOpcode, null); } else if (value instanceof MacroToken) { return tryWritePushMacro((MacroToken) value, writeOpcode); } else if (value instanceof VariableExprToken) { if (writeOpcode) writePushVariable((VariableExprToken) value); /*if (returnValue) return tryWritePushVariable((VariableExprToken) value, heavyObjects); */ } return null; } public void writePush(ValueExprToken value, boolean returnValue, boolean heavyObjects) { if (value instanceof VariableExprToken) { writePushVariable((VariableExprToken) value); return; } Memory memory = tryWritePush(value, returnValue, true, heavyObjects); if (memory != null) writePushMemory(memory); } @SuppressWarnings("unchecked") boolean methodExists(Class clazz, String method, Class... paramClasses) { try { clazz.getDeclaredMethod(method, paramClasses); return true; } catch (java.lang.NoSuchMethodException e) { return false; } } void writeSysCall(String internalClassName, int INVOKE_TYPE, String method, Class returnClazz, Class... paramClasses) { Type[] args = new Type[paramClasses.length]; if (INVOKE_TYPE == INVOKEVIRTUAL || INVOKE_TYPE == INVOKEINTERFACE) stackPop(); // this for (int i = 0; i < args.length; i++) { args[i] = Type.getType(paramClasses[i]); stackPop(); } code.add(new MethodInsnNode( INVOKE_TYPE, internalClassName, method, Type.getMethodDescriptor(Type.getType(returnClazz), args), false )); if (returnClazz != void.class) { stackPush(null, StackItem.Type.valueOf(returnClazz)); } } @SuppressWarnings("unchecked") void writeSysCall(Class clazz, int INVOKE_TYPE, String method, Class returnClazz, Class... paramClasses) { if (INVOKE_TYPE != INVOKESPECIAL && clazz != null) { if (compiler.getScope().isDebugMode()) { if (!methodExists(clazz, method, paramClasses)) { throw new NoSuchMethodException(clazz, method, paramClasses); } } } Type[] args = new Type[paramClasses.length]; if (INVOKE_TYPE == INVOKEVIRTUAL || INVOKE_TYPE == INVOKEINTERFACE) stackPop(); // this for (int i = 0; i < args.length; i++) { args[i] = Type.getType(paramClasses[i]); stackPop(); } String owner = clazz == null ? this.method.clazz.node.name : Type.getInternalName(clazz); if (clazz == null && this.method.clazz.entity.isTrait()) throw new CriticalException("[Compiler Error] Cannot use current classname in Trait"); code.add(new MethodInsnNode( INVOKE_TYPE, owner, method, Type.getMethodDescriptor(Type.getType(returnClazz), args), clazz != null && clazz.isInterface() )); if (returnClazz != void.class) { stackPush(null, StackItem.Type.valueOf(returnClazz)); } } public void writeTickTrigger(Token token) { writeTickTrigger(token.toTraceInfo(getCompiler().getContext())); } public void writeTickTrigger(TraceInfo trace) { if (compiler.getScope().isDebugMode() && method.getLocalVariable("~local") != null) { int line = trace.getStartLine(); if (method.registerTickTrigger(line)) { writePushEnv(); writePushTraceInfo(trace.getStartLine(), trace.getStartPosition()); writePushLocal(); writeSysDynamicCall(Environment.class, "__tick", void.class, TraceInfo.class, ArrayMemory.class); } } } public void writeSysDynamicCall(Class clazz, String method, Class returnClazz, Class... paramClasses) throws NoSuchMethodException { writeSysCall( clazz, clazz != null && clazz.isInterface() ? INVOKEINTERFACE : INVOKEVIRTUAL, method, returnClazz, paramClasses ); } public void writeSysStaticCall(Class clazz, String method, Class returnClazz, Class... paramClasses) throws NoSuchMethodException { writeSysCall(clazz, INVOKESTATIC, method, returnClazz, paramClasses); } public void writePopImmutable() { if (!stackPeek().immutable) { writeSysDynamicCall(Memory.class, "toImmutable", Memory.class); setStackPeekAsImmutable(); } } public void writeVarStore(LocalVariable variable, boolean returned, boolean asImmutable) { writePopBoxing(); if (asImmutable) writePopImmutable(); if (returned) { writePushDup(); } makeVarStore(variable); stackPop(); } public void checkAssignableVar(VariableExprToken var) { if (method.clazz.isClosure() || !method.clazz.isSystem()) { if (var.getName().equals("this")) compiler.getEnvironment().error(var.toTraceInfo(compiler.getContext()), "Cannot re-assign $this"); } } public void writeVarAssign(LocalVariable variable, VariableExprToken token, boolean returned, boolean asImmutable) { if (token != null) checkAssignableVar(token); writePopBoxing(asImmutable); if (variable.isReference()) { writeVarLoad(variable); writeSysStaticCall(Memory.class, "assignRight", Memory.class, Memory.class, Memory.class); if (!returned) writePopAll(1); } else { if (returned) { writePushDup(); } makeVarStore(variable); stackPop(); } } public void writeVarStore(LocalVariable variable, boolean returned) { writeVarStore(variable, returned, false); } public void writeVarLoad(LocalVariable variable) { stackPush(Memory.Type.valueOf(variable.getClazz())); makeVarLoad(variable); } public void writeVarLoad(String name) { LocalVariable local = method.getLocalVariable(name); if (local == null) throw new IllegalArgumentException("Variable '" + name + "' is not registered"); writeVarLoad(local); } public void writePutStatic(Class clazz, String name, Class fieldClass) { code.add(new FieldInsnNode(PUTSTATIC, Type.getInternalName(clazz), name, Type.getDescriptor(fieldClass))); stackPop(); } public void writePutStatic(String name, Class fieldClass) { code.add(new FieldInsnNode( PUTSTATIC, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPop(); } public void writePutDynamic(String name, Class fieldClass) { code.add(new FieldInsnNode( PUTFIELD, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPop(); } public void writeGetStatic(Class clazz, String name, Class fieldClass) { code.add(new FieldInsnNode(GETSTATIC, Type.getInternalName(clazz), name, Type.getDescriptor(fieldClass))); stackPush(null, StackItem.Type.valueOf(fieldClass)); setStackPeekAsImmutable(); } public void writeGetStatic(String name, Class fieldClass) { code.add(new FieldInsnNode( GETSTATIC, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPush(null, StackItem.Type.valueOf(fieldClass)); setStackPeekAsImmutable(); } public void writeGetDynamic(String name, Class fieldClass) { stackPop(); code.add(new FieldInsnNode( GETFIELD, method.clazz.node.name, name, Type.getDescriptor(fieldClass) )); stackPush(null, StackItem.Type.valueOf(fieldClass)); setStackPeekAsImmutable(); } void writeGetEnum(Enum enumInstance) { writeGetStatic(enumInstance.getDeclaringClass(), enumInstance.name(), enumInstance.getDeclaringClass()); } void writeVariableAssign(VariableExprToken variable, StackItem R, AssignExprToken operator, boolean returnValue) { LocalVariable local = method.getLocalVariable(variable.getName()); checkAssignableVar(variable); Memory value = R.getMemory(); writeLineNumber(variable); if (local.isReference()) { String name = "assign"; if (operator.isAsReference()) name = "assignRef"; if (!R.isKnown()) { stackPush(R); writePopBoxing(); writePopImmutable(); writePushVariable(variable); writeSysStaticCall(Memory.class, name + "Right", Memory.class, stackPeek().type.toClass(), Memory.class); } else { writePushVariable(variable); Memory tmp = tryWritePush(R); if (tmp != null) { value = tmp; writePushMemory(value); } writePopBoxing(); writePopImmutable(); writeSysDynamicCall(Memory.class, name, Memory.class, stackPeek().type.toClass()); } if (!returnValue) writePopAll(1); } else { Memory result = tryWritePush(R); if (result != null) { writePushMemory(result); value = result; } writePopBoxing(); writeVarStore(local, returnValue, true); } /*if (!methodStatement.variable(variable).isPassed()) local.setValue(value); if (methodStatement.isDynamicLocal()) */ local.setValue(null); } void writeScalarOperator(StackItem L, StackItem.Type Lt, StackItem R, StackItem.Type Rt, OperatorExprToken operator, Class operatorResult, String operatorName) { boolean isInvert = !R.isKnown(); if (!R.isKnown() && !L.isKnown() && R.getLevel() > L.getLevel()) isInvert = false; if (operator instanceof ConcatExprToken) { if (isInvert) { stackPush(R); writePopString(); writePush(L, StackItem.Type.STRING); writeSysStaticCall(OperatorUtils.class, "concatRight", String.class, String.class, String.class); } else { writePush(L, StackItem.Type.STRING); writePush(R, StackItem.Type.STRING); writeSysDynamicCall(String.class, "concat", String.class, String.class); } return; } else if (operator instanceof PlusExprToken || operator instanceof MinusExprToken || operator instanceof MulExprToken) { if (operator instanceof MinusExprToken && isInvert) { // nothing } else if (Lt.isLikeNumber() && Rt.isLikeNumber()) { StackItem.Type cast = StackItem.Type.LONG; if (Lt.isLikeDouble() || Rt.isLikeDouble()) cast = StackItem.Type.DOUBLE; writePush(L, cast); writePush(R, cast); code.add(new InsnNode(CompilerUtils.getOperatorOpcode(operator, cast))); stackPop(); stackPop(); stackPush(null, cast); return; } } if (isInvert) { stackPush(R); writePopBoxing(); writePush(L); if (operator.isSide()) operatorName += "Right"; writeSysDynamicCall(Memory.class, operatorName, operatorResult, stackPeek().type.toClass()); } else { writePush(L); writePopBoxing(); writePush(R); writeSysDynamicCall(Memory.class, operatorName, operatorResult, stackPeek().type.toClass()); } } public void writePop(Class clazz, boolean boxing, boolean asImmutable) { if (clazz == String.class) writePopString(); else if (clazz == Character.TYPE) writePopChar(); else if (clazz == Boolean.TYPE) writePopBoolean(); else if (clazz == Memory.class) { if (boxing) writePopBoxing(asImmutable); } else if (clazz == Double.TYPE) writePopDouble(); else if (clazz == Float.TYPE) writePopFloat(); else if (clazz == Long.TYPE) writePopLong(); else if (clazz == Integer.TYPE || clazz == Byte.TYPE || clazz == Short.TYPE) writePopInteger(); else throw new IllegalArgumentException("Cannot pop this class: " + clazz.getName()); } public void writePopInteger() { writePopLong(); code.add(new InsnNode(L2I)); stackPop(); stackPush(null, StackItem.Type.INT); } public void writePopFloat() { writePopDouble(); code.add(new InsnNode(D2F)); stackPop(); stackPush(null, StackItem.Type.FLOAT); } public void writePopLong() { switch (stackPeek().type) { case LONG: break; case FLOAT: { code.add(new InsnNode(L2F)); stackPop(); stackPush(Memory.Type.INT); } break; case BYTE: case SHORT: case BOOL: case CHAR: case INT: { code.add(new InsnNode(I2L)); stackPop(); stackPush(Memory.Type.INT); } break; case DOUBLE: { code.add(new InsnNode(D2L)); stackPop(); stackPush(Memory.Type.INT); } break; case STRING: { writeSysStaticCall(StringMemory.class, "toNumeric", Memory.class, String.class); writeSysDynamicCall(Memory.class, "toLong", Long.TYPE); } break; default: { writeSysDynamicCall(Memory.class, "toLong", Long.TYPE); } } } public void writePopDouble() { switch (stackPeek().type) { case DOUBLE: break; case BYTE: case SHORT: case BOOL: case CHAR: case INT: { code.add(new InsnNode(I2D)); stackPop(); stackPush(Memory.Type.DOUBLE); } break; case LONG: { code.add(new InsnNode(L2D)); stackPop(); stackPush(Memory.Type.DOUBLE); } break; case STRING: { writeSysStaticCall(StringMemory.class, "toNumeric", Memory.class, String.class); writeSysDynamicCall(Memory.class, "toDouble", Double.TYPE); } break; default: { writeSysDynamicCall(Memory.class, "toDouble", Double.TYPE); } } } public void writePopString() { StackItem.Type peek = stackPeek().type; switch (peek) { case STRING: break; default: if (peek.isConstant()) { if (peek == StackItem.Type.BOOL) writeSysStaticCall(Memory.class, "boolToString", String.class, peek.toClass()); else writeSysStaticCall(String.class, "valueOf", String.class, peek.toClass()); } else writeSysDynamicCall(Memory.class, "toString", String.class); } } public void writePopChar() { StackItem.Type peek = stackPeek().type; if (peek == StackItem.Type.CHAR) return; if (peek.isConstant()) { writeSysStaticCall(OperatorUtils.class, "toChar", Character.TYPE, peek.toClass()); } else { writePopBoxing(); writeSysDynamicCall(Memory.class, "toChar", Character.TYPE); } } public void writePopBooleanAsObject() { StackItem.Type peek = stackPeek().type; writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, peek.toClass()); setStackPeekAsImmutable(); } public void writePopBoolean() { StackItem.Type peek = stackPeek().type; switch (peek) { case BOOL: break; case BYTE: case INT: case SHORT: case CHAR: case LONG: { writeSysStaticCall(OperatorUtils.class, "toBoolean", Boolean.TYPE, peek.toClass()); } break; case DOUBLE: { writeSysStaticCall(OperatorUtils.class, "toBoolean", Boolean.TYPE, Double.TYPE); } break; case STRING: { writeSysStaticCall(OperatorUtils.class, "toBoolean", Boolean.TYPE, String.class); } break; case REFERENCE: { writeSysDynamicCall(Memory.class, "toBoolean", Boolean.TYPE); } break; } } public void writeDynamicAccessInfo(DynamicAccessExprToken dynamic, boolean addLowerName) { if (dynamic.getField() != null) { if (dynamic.getField() instanceof NameToken) { String name = ((NameToken) dynamic.getField()).getName(); writePushString(name); if (addLowerName) writePushString(name.toLowerCase()); } else { writePush(dynamic.getField(), true, false); writePopString(); if (addLowerName) { writePushDupLowerCase(); } } } else { writeExpression(dynamic.getFieldExpr(), true, false); writePopString(); if (addLowerName) { writePushDupLowerCase(); } } writePushEnv(); writePushTraceInfo(dynamic); } public void writeDynamicAccessPrepare(DynamicAccessExprToken dynamic, boolean addLowerName) { if (stackEmpty(true)) unexpectedToken(dynamic); StackItem o = stackPop(); writePush(o); if (stackPeek().isConstant()) unexpectedToken(dynamic); writePopBoxing(); if (dynamic instanceof DynamicAccessAssignExprToken) { if (((DynamicAccessAssignExprToken) dynamic).getValue() != null) { writeExpression(((DynamicAccessAssignExprToken) dynamic).getValue(), true, false); writePopBoxing(true); } } writeDynamicAccessInfo(dynamic, addLowerName); } void writeArrayGet(ArrayGetExprToken operator, boolean returnValue) { StackItem o = stackPeek(); ValueExprToken L = null; if (o.getToken() != null) { stackPop(); writePush(L = o.getToken(), true, false); writePopBoxing(); } String methodName = operator instanceof ArrayGetRefExprToken ? "refOfIndex" : "valueOfIndex"; boolean isShortcut = operator instanceof ArrayGetRefExprToken && ((ArrayGetRefExprToken) operator).isShortcut(); int i = 0; int size = operator.getParameters().size(); int traceIndex = createTraceInfo(operator); for (ExprStmtToken param : operator.getParameters()) { writePushTraceInfo(traceIndex); // push dup trace writeExpression(param, true, false); if (operator instanceof ArrayGetUnsetExprToken && i == size - 1) { writePopBoxing(); writeSysDynamicCall(Memory.class, "unsetOfIndex", void.class, TraceInfo.class, stackPeek().type.toClass()); if (returnValue) writePushNull(); } else if (operator instanceof ArrayGetIssetExprToken && i == size - 1) { writePopBoxing(); writeSysDynamicCall(Memory.class, "issetOfIndex", Memory.class, TraceInfo.class, stackPeek().type.toClass()); } else if (operator instanceof ArrayGetEmptyExprToken && i == size - 1) { writePopBoxing(); writeSysDynamicCall(Memory.class, "emptyOfIndex", Memory.class, TraceInfo.class, stackPeek().type.toClass()); } else { // TODO: Remove. // PHP CMP: $hack = &$arr[0]; // boolean isMemory = stackPeek().type.toClass() == Memory.class; //if (isMemory) /*if (compiler.isPhpMode()){ if (i == size - 1 && isShortcut){ writePopBoxing(); writeSysDynamicCall(Memory.class, methodName + "AsShortcut", Memory.class, TraceInfo.class, Memory.class); continue; } }*/ writeSysDynamicCall(Memory.class, methodName, Memory.class, TraceInfo.class, stackPeek().type.toClass()); i++; } } } Memory writeUnaryOperator(OperatorExprToken operator, boolean returnValue, boolean writeOpcode) { if (stackEmpty(true)) unexpectedToken(operator); StackItem o = stackPop(); ValueExprToken L = o.getToken(); Memory mem = tryWritePush(o, false, false, true); StackItem.Type type = tryGetType(o); if (mem != null) { Memory result = CompilerUtils.calcUnary(getCompiler().getEnvironment(), operator.toTraceInfo(getCompiler().getContext()), mem, operator); if (operator instanceof ValueIfElseToken) { ValueIfElseToken valueIfElseToken = (ValueIfElseToken) operator; ExprStmtToken ret = valueIfElseToken.getValue(); if (mem.toBoolean()) { if (ret == null) result = mem; else result = writeExpression(ret, true, true, false); } else { result = writeExpression(valueIfElseToken.getAlternative(), true, true, false); } } else if (operator instanceof ArrayGetExprToken && !(operator instanceof ArrayGetRefExprToken)) { // TODO: check!!! /*Memory array = mem; ArrayGetExprToken arrayGet = (ArrayGetExprToken)operator; for(ExprStmtToken expr : arrayGet.getParameters()){ Memory key = writeExpression(expr, true, true, false); if (key == null) break; result = array = array.valueOfIndex(key).toImmutable(); }*/ } if (result != null) { stackPush(result); setStackPeekAsImmutable(); return result; } } if (!writeOpcode) return null; writeLineNumber(operator); String name = operator.getCode(); Class operatorResult = operator.getResultClass(); LocalVariable variable = null; if (L instanceof VariableExprToken) { variable = method.getLocalVariable(((VariableExprToken) L).getName()); if (operator instanceof ArrayPushExprToken || operator instanceof ArrayGetRefExprToken) variable.setValue(null); } if (operator instanceof IncExprToken || operator instanceof DecExprToken) { if (variable == null || variable.isReference()) { if (operator.getAssociation() == Association.LEFT && returnValue) { writePush(o); if (stackPeek().type.isConstant()) unexpectedToken(operator); writePushDup(); writePopImmutable(); code.add(new InsnNode(SWAP)); writePushDup(); } else { writePush(o); if (stackPeek().type.isConstant()) unexpectedToken(operator); writePushDup(); } writeSysDynamicCall(Memory.class, name, operatorResult); writeSysDynamicCall(Memory.class, "assign", Memory.class, operatorResult); if (!returnValue || operator.getAssociation() == Association.LEFT) { writePopAll(1); } } else { writePush(o); if (stackPeek().type.isConstant()) unexpectedToken(operator); if (operator.getAssociation() == Association.LEFT && returnValue) { writeVarLoad(variable); } writeSysDynamicCall(Memory.class, name, operatorResult); variable.setValue(null); // TODO for constant values if (operator.getAssociation() == Association.RIGHT) writeVarStore(variable, returnValue); else { writeVarStore(variable, false); } } } else if (operator instanceof AmpersandRefToken) { writePush(o, false, false); setStackPeekAsImmutable(); Token token = o.getToken(); if (token instanceof VariableExprToken) { LocalVariable local = method.getLocalVariable(((VariableExprToken) token).getName()); local.setValue(null); } } else if (operator instanceof SilentToken) { writePushEnv(); writeSysDynamicCall(Environment.class, "__pushSilent", void.class); writePush(o); writePushEnv(); writeSysDynamicCall(Environment.class, "__popSilent", void.class); } else if (operator instanceof ValueIfElseToken) { writePush(o); ValueIfElseToken valueIfElseToken = (ValueIfElseToken) operator; LabelNode end = new LabelNode(); LabelNode elseL = new LabelNode(); if (valueIfElseToken.getValue() == null) { StackItem.Type dup = stackPeek().type; writePushDup(); writePopBoolean(); code.add(new JumpInsnNode(Opcodes.IFEQ, elseL)); stackPop(); writePopBoxing(); stackPop(); code.add(new JumpInsnNode(Opcodes.GOTO, end)); code.add(elseL); makePop(dup); // remove duplicate of condition value , IMPORTANT!!! writeExpression(valueIfElseToken.getAlternative(), true, false); writePopBoxing(); code.add(end); } else { writePopBoolean(); code.add(new JumpInsnNode(Opcodes.IFEQ, elseL)); stackPop(); writeExpression(valueIfElseToken.getValue(), true, false); writePopBoxing(); stackPop(); code.add(new JumpInsnNode(Opcodes.GOTO, end)); // goto end // else code.add(elseL); writeExpression(valueIfElseToken.getAlternative(), true, false); writePopBoxing(); code.add(end); } setStackPeekAsImmutable(false); } else if (operator instanceof ArrayGetExprToken) { stackPush(o); writeArrayGet((ArrayGetExprToken) operator, returnValue); } else if (operator instanceof CallOperatorToken) { stackPush(o); CallOperatorToken call = (CallOperatorToken) operator; writePushParameters(call.getParameters()); writePushEnv(); writePushTraceInfo(operator); writeSysStaticCall( InvokeHelper.class, "callAny", Memory.class, Memory.class, Memory[].class, Environment.class, TraceInfo.class ); if (!returnValue) writePopAll(1); } else { writePush(o); writePopBoxing(); if (operator.isEnvironmentNeeded() && operator.isTraceNeeded()) { writePushEnv(); writePushTraceInfo(operator); writeSysDynamicCall(Memory.class, name, operatorResult, Environment.class, TraceInfo.class); } else if (operator.isEnvironmentNeeded()) { writePushEnv(); writeSysDynamicCall(Memory.class, name, operatorResult, Environment.class); } else if (operator.isTraceNeeded()) { writePushTraceInfo(operator); writeSysDynamicCall(Memory.class, name, operatorResult, TraceInfo.class); } else writeSysDynamicCall(Memory.class, name, operatorResult); if (!returnValue) { writePopAll(1); } } return null; } Memory writeLogicOperator(LogicOperatorExprToken operator, boolean returnValue, boolean writeOpcode) { if (stackEmpty(true)) unexpectedToken(operator); if (!writeOpcode) { StackItem top = stackPeek(); Memory one = tryWritePush(top, false, false, true); if (one == null) return null; Memory two = writeExpression(operator.getRightValue(), true, true, false); if (two == null) return null; stackPop(); Memory r = operator.calc(getCompiler().getEnvironment(), operator.toTraceInfo(getCompiler().getContext()), one, two); stackPush(r); return r; } writeLineNumber(operator); StackItem o = stackPop(); writePush(o); writePopBoolean(); LabelNode end = new LabelNode(); LabelNode next = new LabelNode(); if (operator instanceof BooleanOrExprToken || operator instanceof BooleanOr2ExprToken) { code.add(new JumpInsnNode(IFEQ, next)); stackPop(); if (returnValue) { writePushBooleanAsMemory(true); stackPop(); } } else if (operator instanceof BooleanAndExprToken || operator instanceof BooleanAnd2ExprToken) { code.add(new JumpInsnNode(IFNE, next)); stackPop(); if (returnValue) { writePushBooleanAsMemory(false); stackPop(); } } code.add(new JumpInsnNode(GOTO, end)); code.add(next); writeExpression(operator.getRightValue(), returnValue, false); if (returnValue) { if (operator.getLast() instanceof ValueIfElseToken) writePopBoxing(); else writePopBooleanAsObject(); } code.add(end); return null; } Memory writeOperator(OperatorExprToken operator, boolean returnValue, boolean writeOpcode) { if (writeOpcode) { BaseExprCompiler compiler = (BaseExprCompiler) getCompiler(operator.getClass()); if (compiler != null) { if (writeOpcode) { writeLineNumber(operator); } compiler.write(operator, returnValue); return null; } } if (operator instanceof LogicOperatorExprToken) { return writeLogicOperator((LogicOperatorExprToken) operator, returnValue, writeOpcode); } if (!operator.isBinary()) { return writeUnaryOperator(operator, returnValue, writeOpcode); } if (stackEmpty(true)) unexpectedToken(operator); StackItem o1 = stackPop(); if (o1.isInvalidForOperations()) unexpectedToken(operator); if (stackEmpty(true)) unexpectedToken(operator); StackItem o2 = stackPeek(); ValueExprToken L = stackPopToken(); if (o2.isInvalidForOperations()) unexpectedToken(operator); if (!(operator instanceof AssignExprToken || operator instanceof AssignOperatorExprToken)) if (o1.getMemory() != null && o2.getMemory() != null) { Memory result; stackPush(result = CompilerUtils.calcBinary( getCompiler().getEnvironment(), operator.toTraceInfo(getCompiler().getContext()), o2.getMemory(), o1.getMemory(), operator, false )); return result; } LocalVariable variable = null; if (L instanceof VariableExprToken) { variable = method.getLocalVariable(((VariableExprToken) L).getName()); } if (operator instanceof AssignExprToken) { if (L instanceof VariableExprToken) { if (!writeOpcode) return null; writeVariableAssign((VariableExprToken) L, o1, (AssignExprToken) operator, returnValue); return null; } } Memory value1 = operator instanceof AssignableOperatorToken ? null : tryWritePush(o2, false, false, true); // LEFT Memory value2 = tryWritePush(o1, false, false, true); // RIGHT if (value1 != null && value2 != null) { stackPush(value1); stackPush(value2); return writeOperator(operator, returnValue, writeOpcode); } if (!returnValue && CompilerUtils.isOperatorAlwaysReturn(operator)) { unexpectedToken(operator); } if (!writeOpcode) { stackPush(o2); stackPush(o1); return null; } if (writeOpcode) { writeLineNumber(operator); } StackItem.Type Lt = tryGetType(o2); StackItem.Type Rt = tryGetType(o1); String name = operator.getCode(); Class operatorResult = operator.getResultClass(); boolean isInvert = false; boolean sideOperator = operator.isSide(); if (variable != null && !variable.isReference()) { if (operator instanceof AssignOperatorExprToken) { name = ((AssignOperatorExprToken) operator).getOperatorCode(); if (operator instanceof AssignConcatExprToken) operatorResult = String.class; if (operator instanceof AssignPlusExprToken || operator instanceof AssignMulExprToken) sideOperator = false; } } if (operator instanceof AssignableOperatorToken && tryIsImmutable(o2)) unexpectedToken(operator); if (Lt.isConstant() && Rt.isConstant()) { if (operator instanceof AssignableOperatorToken) unexpectedToken(operator); writeScalarOperator(o2, Lt, o1, Rt, operator, operatorResult, name); } else { isInvert = !o1.isKnown(); if (!o1.isKnown() && !o2.isKnown() && o1.getLevel() > o2.getLevel()) isInvert = false; if (Lt.isConstant() && !isInvert) { writePush(o2); if (methodExists(OperatorUtils.class, name, Lt.toClass(), Rt.toClass())) { writePush(o1); writeSysStaticCall(OperatorUtils.class, name, operatorResult, Lt.toClass(), Rt.toClass()); } else { writePopBoxing(); writePush(o1); writeSysDynamicCall(Memory.class, name, operatorResult, Rt.toClass()); } } else { if (isInvert) { stackPush(o1); if (o2.isKnown()) writePopBoxing(false); writePush(o2); if (!o2.isKnown() && !o2.type.isReference()) { writeSysStaticCall(OperatorUtils.class, name, operatorResult, Lt.toClass(), Rt.toClass()); name = null; } else if (sideOperator) { name += "Right"; } /*if (cloneValue){ writeSysDynamicCall(Memory.class, name, operatorResult, isInvert ? Lt.toClass() : Rt.toClass()); writePush(o2); name = null; }*/ } else { writePush(o2); writePopBoxing(false); /*if (cloneValue) writePushDup();*/ writePush(o1); if (Rt.isReference()) { writePopBoxing(false); } if (!o1.immutable && !operator.isMutableArguments()) writePopImmutable(); } if (name != null) { writeSysDynamicCall(Memory.class, name, operatorResult, isInvert ? Lt.toClass() : Rt.toClass()); } if (operator.getCheckerCode() != null) { writePopBoxing(); writePushEnv(); writePushTraceInfo(operator); writeSysDynamicCall(Memory.class, operator.getCheckerCode(), Memory.class, Environment.class, TraceInfo.class); } } setStackPeekAsImmutable(); if (operator instanceof AssignOperatorExprToken) { if (variable == null || variable.isReference()) { /*if (isInvert) writeSysStaticCall(Memory.class, "assignRight", Memory.class, Rt.toClass(), Memory.class); else writeSysDynamicCall(Memory.class, "assign", Memory.class, stackPeek().type.toClass()); */ if (!returnValue) writePopAll(1); } else { if (returnValue) writePushDup(StackItem.Type.valueOf(operatorResult)); writePopBoxing(operatorResult); makeVarStore(variable); variable.setValue(!stackPeek().isConstant() ? null : stackPeek().getMemory()); stackPop(); } } } return null; } void writeDebugMessage(String message) { writePushEnv(); writePushConstString(message); writeSysDynamicCall(Environment.class, "echo", void.class, String.class); } public void writeConditional(ExprStmtToken condition, LabelNode successLabel) { writeExpression(condition, true, false); writePopBoolean(); code.add(new JumpInsnNode(IFEQ, successLabel)); stackPop(); } public Memory writeExpression(ExprStmtToken expression, boolean returnValue, boolean returnMemory) { return writeExpression(expression, returnValue, returnMemory, true); } public Memory tryCalculateExpression(ExprStmtToken expression) { return writeExpression(expression, true, true, false); } @SuppressWarnings("unchecked") public Memory writeExpression(ExprStmtToken expression, boolean returnValue, boolean returnMemory, boolean writeOpcode) { int initStackSize = method.getStackCount(); exprStackInit.push(initStackSize); if (!expression.isStmtList()) { if (expression.getAsmExpr() == null) { throw new CriticalException("Invalid expression token without asm expr, on line " + expression.getMeta().getStartLine() + ", expr = " + expression.getWord()); } expression = expression.getAsmExpr(); // new ASMExpression(compiler.getEnvironment(), compiler.getContext(), expression).getResult(); } List<Token> tokens = expression.getTokens(); int operatorCount = 0; for (Token token : tokens) { if (token instanceof OperatorExprToken) operatorCount++; } boolean invalid = false; for (Token token : tokens) { if (token == null) continue; writeTickTrigger(token); if (writeOpcode) { if (token instanceof StmtToken) { if (!(token instanceof ReturnStmtToken)) method.entity.setImmutable(false); } BaseStatementCompiler cmp = getCompiler(token.getClass()); if (cmp != null && !(cmp instanceof BaseExprCompiler)) { cmp.write(token); continue; } } if (token instanceof ValueExprToken) { // mixed, calls, numbers, strings, vars, etc. if (token instanceof CallExprToken && ((CallExprToken) token).getName() instanceof OperatorExprToken) { if (writeOpcode) { writePush((ValueExprToken) token, true, true); method.entity.setImmutable(false); } else break; } else stackPush((ValueExprToken) token); } else if (token instanceof OperatorExprToken) { // + - * / % && || or ! and == > < etc. operatorCount--; if (operatorCount >= 0) { Memory result; if (operatorCount == 0) { result = writeOperator((OperatorExprToken) token, returnValue, writeOpcode); } else result = writeOperator((OperatorExprToken) token, true, writeOpcode); if (!writeOpcode && result == null) { invalid = true; break; } if (result == null) method.entity.setImmutable(false); } } else break; } Memory result = null; if (!invalid && returnMemory && returnValue && !stackEmpty(false) && stackPeek().isConstant()) { result = stackPop().memory; invalid = true; } if (!invalid) { if (returnValue && !stackEmpty(false) && stackPeek().isKnown()) { if (returnMemory) result = tryWritePush(stackPop(), writeOpcode, returnValue, true); else writePush(stackPop()); } else if (method.getStackCount() > 0) { if (stackPeekToken() instanceof CallableExprToken) { if (returnMemory) result = tryWritePush(stackPopToken(), returnValue, writeOpcode, true); else writePush(stackPopToken(), returnValue, true); } else if (stackPeek().isConstant()) { stackPop(); } } } if (!returnValue && writeOpcode) { writePopAll(method.getStackCount() - initStackSize); } else if (!writeOpcode) { int count = method.getStackCount() - initStackSize; for (int i = 0; i < count; i++) { stackPop(); } } exprStackInit.pop(); return result; } void makePop(StackItem.Type type) { switch (type.size()) { case 2: code.add(new InsnNode(POP2)); break; case 1: code.add(new InsnNode(POP)); break; default: throw new IllegalArgumentException("Invalid of size StackItem: " + type.size()); } } public void writePopAll(int count) { int i = 0; while (method.getStackCount() > 0 && i < count) { i++; StackItem o = stackPop(); ValueExprToken token = o.getToken(); StackItem.Type type = o.type; if (token == null) { switch (type.size()) { case 2: code.add(new InsnNode(POP2)); break; case 1: code.add(new InsnNode(POP)); break; default: throw new IllegalArgumentException("Invalid of size StackItem: " + type.size()); } } else/* if (o.isInvalidForOperations())*/ unexpectedToken(token); } } @Override public Entity compile() { writeDefineVariables(methodStatement.getLocal()); writeExpression(expression, false, false); method.popAll(); return null; } public static class NoSuchMethodException extends RuntimeException { public NoSuchMethodException(Class clazz, String method, Class... parameters) { super("No such method " + clazz.getName() + "." + method + "(" + StringUtils.join(parameters, ", ") + ")"); } } public static class UnsupportedTokenException extends RuntimeException { protected final Token token; public UnsupportedTokenException(Token token) { this.token = token; } } }
Fix elvis compiler bug.
jphp-core/src/org/develnext/jphp/core/compiler/jvm/statement/ExpressionStmtCompiler.java
Fix elvis compiler bug.
<ide><path>php-core/src/org/develnext/jphp/core/compiler/jvm/statement/ExpressionStmtCompiler.java <ide> <ide> writePopAll(1); <ide> } <del> stackPop(); <del> stackPush(memory); <add> /*stackPop(); <add> stackPush(memory);*/ <ide> <ide> setStackPeekAsImmutable(); <ide> return; <ide> public boolean writePopBoxing(StackItem.Type type, boolean asImmutable, boolean useConstants) { <ide> switch (type) { <ide> case BOOL: <del> if (useConstants && code.getLast() instanceof InsnNode) { <add> /*if (useConstants && code.getLast() instanceof InsnNode) { <ide> InsnNode node = (InsnNode) code.getLast(); <ide> <del> switch (node.getType()) { <del> case ICONST_0: <del> case ICONST_1: <del> case ICONST_2: <del> case ICONST_3: <del> case ICONST_4: <del> case ICONST_5: <del> code.remove(node); <del> <del> stackPop(); <del> writePushBooleanAsMemory(node.getType() != ICONST_0); <del> break; <del> default: <del> writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); <add> StackItem stackPeek = stackPeek(); <add> <add> if (stackPeek.type == StackItem.Type.BOOL) { <add> switch (node.getOpcode()) { <add> case ICONST_0: <add> case ICONST_1: <add> code.remove(node); <add> <add> stackPop(); <add> writePushBooleanAsMemory(node.getOpcode() != ICONST_0); <add> break; <add> default: <add> writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); <add> } <add> <add> break; <ide> } <del> } else { <del> writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); <del> } <del> <add> }*/ <add> <add> writeSysStaticCall(TrueMemory.class, "valueOf", Memory.class, type.toClass()); <ide> setStackPeekAsImmutable(); <ide> return true; <ide> case SHORT:
Java
apache-2.0
c73ffd476dc6f6474168d8d0c1c0a442f4405004
0
AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.example.android.leanback; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.view.ViewCompat; import android.support.v17.leanback.widget.Action; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.ClassPresenterSelector; import android.support.v17.leanback.widget.DetailsOverviewRow; import android.support.v17.leanback.widget.DetailsOverviewRowPresenter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ImageCardView; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.OnActionClickedListener; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.OnItemViewSelectedListener; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.ArrayList; public class DetailsFragment extends android.support.v17.leanback.app.DetailsFragment { private static final String TAG = "leanback.DetailsFragment"; private static final String ITEM = "item"; private static final int NUM_ROWS = 3; private ArrayObjectAdapter mRowsAdapter; private PhotoItem mPhotoItem; @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); ClassPresenterSelector ps = new ClassPresenterSelector(); DetailsOverviewRowPresenter dorPresenter = new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter()); dorPresenter.setOnActionClickedListener(new OnActionClickedListener() { public void onActionClicked(Action action) { Toast.makeText(getActivity(), action.toString(), Toast.LENGTH_SHORT).show(); } }); ps.addClassPresenter(DetailsOverviewRow.class, dorPresenter); ps.addClassPresenter(ListRow.class, new ListRowPresenter()); mRowsAdapter = new ArrayObjectAdapter(ps); PhotoItem item = (PhotoItem) (savedInstanceState != null ? savedInstanceState.getParcelable(ITEM) : null); if (item != null) { setItem(item); } dorPresenter.setSharedElementEnterTransition(getActivity(), DetailsActivity.SHARED_ELEMENT_NAME); setOnItemViewClickedListener(new OnItemViewClickedListener() { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { Log.i(TAG, "onItemClicked: " + item + " row " + row); if (item instanceof PhotoItem){ Intent intent = new Intent(getActivity(), DetailsActivity.class); intent.putExtra(DetailsActivity.EXTRA_ITEM, (PhotoItem) item); Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation( getActivity(), ((ImageCardView)itemViewHolder.view).getMainImageView(), DetailsActivity.SHARED_ELEMENT_NAME).toBundle(); getActivity().startActivity(intent, bundle); } } }); setOnItemViewSelectedListener(new OnItemViewSelectedListener() { @Override public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { Log.i(TAG, "onItemSelected: " + item + " row " + row); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(ITEM, mPhotoItem); } public void setItem(PhotoItem photoItem) { mPhotoItem = photoItem; mRowsAdapter.clear(); Resources res = getActivity().getResources(); DetailsOverviewRow dor = new DetailsOverviewRow("Details Overview"); dor.setImageDrawable(res.getDrawable(photoItem.getImageResourceId())); dor.addAction(new Action(1, "Buy $9.99")); dor.addAction(new Action(2, "Rent", "$3.99", res.getDrawable(R.drawable.ic_action_a))); mRowsAdapter.add(dor); final CardPresenter cardPresenter = new CardPresenter(); for (int i = 0; i < NUM_ROWS; ++i) { ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter); listRowAdapter.add(new PhotoItem("Hello world", R.drawable.gallery_photo_1)); listRowAdapter.add(new PhotoItem("This is a test", R.drawable.gallery_photo_2)); listRowAdapter.add(new PhotoItem("Android TV", R.drawable.gallery_photo_3)); listRowAdapter.add(new PhotoItem("Leanback", R.drawable.gallery_photo_4)); HeaderItem header = new HeaderItem(i, "Row " + i, null); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } setAdapter(mRowsAdapter); } }
samples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsFragment.java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.example.android.leanback; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.view.ViewCompat; import android.support.v17.leanback.widget.Action; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.ClassPresenterSelector; import android.support.v17.leanback.widget.DetailsOverviewRow; import android.support.v17.leanback.widget.DetailsOverviewRowPresenter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.OnActionClickedListener; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.OnItemViewSelectedListener; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.ArrayList; public class DetailsFragment extends android.support.v17.leanback.app.DetailsFragment { private static final String TAG = "leanback.DetailsFragment"; private static final String ITEM = "item"; private static final int NUM_ROWS = 3; private ArrayObjectAdapter mRowsAdapter; private PhotoItem mPhotoItem; @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); ClassPresenterSelector ps = new ClassPresenterSelector(); DetailsOverviewRowPresenter dorPresenter = new DetailsOverviewRowPresenter(new DetailsDescriptionPresenter()); dorPresenter.setOnActionClickedListener(new OnActionClickedListener() { public void onActionClicked(Action action) { Toast.makeText(getActivity(), action.toString(), Toast.LENGTH_SHORT).show(); } }); ps.addClassPresenter(DetailsOverviewRow.class, dorPresenter); ps.addClassPresenter(ListRow.class, new ListRowPresenter()); mRowsAdapter = new ArrayObjectAdapter(ps); PhotoItem item = (PhotoItem) (savedInstanceState != null ? savedInstanceState.getParcelable(ITEM) : null); if (item != null) { setItem(item); } dorPresenter.setSharedElementEnterTransition(getActivity(), DetailsActivity.SHARED_ELEMENT_NAME); setOnItemViewClickedListener(new OnItemViewClickedListener() { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { Log.i(TAG, "onItemClicked: " + item + " row " + row); } }); setOnItemViewSelectedListener(new OnItemViewSelectedListener() { @Override public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { Log.i(TAG, "onItemSelected: " + item + " row " + row); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(ITEM, mPhotoItem); } public void setItem(PhotoItem photoItem) { mPhotoItem = photoItem; Resources res = getActivity().getResources(); DetailsOverviewRow dor = new DetailsOverviewRow("Details Overview"); dor.setImageDrawable(res.getDrawable(photoItem.getImageResourceId())); dor.addAction(new Action(1, "Buy $9.99")); dor.addAction(new Action(2, "Rent", "$3.99", res.getDrawable(R.drawable.ic_action_a))); mRowsAdapter.add(dor); for (int i = 0; i < NUM_ROWS; ++i) { ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new StringPresenter()); listRowAdapter.add("Hello world"); listRowAdapter.add("This is a test"); HeaderItem header = new HeaderItem(i, "Row " + i, null); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } setAdapter(mRowsAdapter); } }
Use image card view for DetailsFragment example b/17499864 Change-Id: I7c5f77da52424afa5020a66b032df68cfdf5846e
samples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsFragment.java
Use image card view for DetailsFragment example
<ide><path>amples/SupportLeanbackDemos/src/com/example/android/leanback/DetailsFragment.java <ide> */ <ide> package com.example.android.leanback; <ide> <add>import android.content.Intent; <ide> import android.content.res.Resources; <ide> import android.os.Bundle; <ide> import android.support.v4.app.ActivityCompat; <add>import android.support.v4.app.ActivityOptionsCompat; <ide> import android.support.v4.view.ViewCompat; <ide> import android.support.v17.leanback.widget.Action; <ide> import android.support.v17.leanback.widget.ArrayObjectAdapter; <ide> import android.support.v17.leanback.widget.DetailsOverviewRow; <ide> import android.support.v17.leanback.widget.DetailsOverviewRowPresenter; <ide> import android.support.v17.leanback.widget.HeaderItem; <add>import android.support.v17.leanback.widget.ImageCardView; <ide> import android.support.v17.leanback.widget.ListRow; <ide> import android.support.v17.leanback.widget.ListRowPresenter; <ide> import android.support.v17.leanback.widget.OnActionClickedListener; <ide> public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, <ide> RowPresenter.ViewHolder rowViewHolder, Row row) { <ide> Log.i(TAG, "onItemClicked: " + item + " row " + row); <add> if (item instanceof PhotoItem){ <add> Intent intent = new Intent(getActivity(), DetailsActivity.class); <add> intent.putExtra(DetailsActivity.EXTRA_ITEM, (PhotoItem) item); <add> <add> Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation( <add> getActivity(), <add> ((ImageCardView)itemViewHolder.view).getMainImageView(), <add> DetailsActivity.SHARED_ELEMENT_NAME).toBundle(); <add> getActivity().startActivity(intent, bundle); <add> } <ide> } <ide> }); <ide> setOnItemViewSelectedListener(new OnItemViewSelectedListener() { <ide> public void setItem(PhotoItem photoItem) { <ide> mPhotoItem = photoItem; <ide> <add> mRowsAdapter.clear(); <ide> Resources res = getActivity().getResources(); <ide> DetailsOverviewRow dor = new DetailsOverviewRow("Details Overview"); <ide> dor.setImageDrawable(res.getDrawable(photoItem.getImageResourceId())); <ide> dor.addAction(new Action(2, "Rent", "$3.99", res.getDrawable(R.drawable.ic_action_a))); <ide> mRowsAdapter.add(dor); <ide> <add> final CardPresenter cardPresenter = new CardPresenter(); <ide> for (int i = 0; i < NUM_ROWS; ++i) { <del> ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new StringPresenter()); <del> listRowAdapter.add("Hello world"); <del> listRowAdapter.add("This is a test"); <add> ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter); <add> listRowAdapter.add(new PhotoItem("Hello world", R.drawable.gallery_photo_1)); <add> listRowAdapter.add(new PhotoItem("This is a test", R.drawable.gallery_photo_2)); <add> listRowAdapter.add(new PhotoItem("Android TV", R.drawable.gallery_photo_3)); <add> listRowAdapter.add(new PhotoItem("Leanback", R.drawable.gallery_photo_4)); <ide> HeaderItem header = new HeaderItem(i, "Row " + i, null); <ide> mRowsAdapter.add(new ListRow(header, listRowAdapter)); <ide> }
Java
apache-2.0
dab79c759736f02e936b96055d7e6948b7a369c8
0
maichler/izpack,izpack/izpack,bradcfisher/izpack,izpack/izpack,mtjandra/izpack,codehaus/izpack,optotronic/izpack,akuhtz/izpack,maichler/izpack,tomas-forsman/izpack,akuhtz/izpack,maichler/izpack,rsharipov/izpack,Murdock01/izpack,akuhtz/izpack,mtjandra/izpack,rsharipov/izpack,codehaus/izpack,Murdock01/izpack,stenix71/izpack,izpack/izpack,bradcfisher/izpack,Murdock01/izpack,Helpstone/izpack,tomas-forsman/izpack,Helpstone/izpack,codehaus/izpack,optotronic/izpack,izpack/izpack,Helpstone/izpack,mtjandra/izpack,rsharipov/izpack,maichler/izpack,akuhtz/izpack,yukron/izpack,rkrell/izpack,mtjandra/izpack,yukron/izpack,tomas-forsman/izpack,optotronic/izpack,rsharipov/izpack,maichler/izpack,yukron/izpack,akuhtz/izpack,Helpstone/izpack,maichler/izpack,stenix71/izpack,codehaus/izpack,Murdock01/izpack,bradcfisher/izpack,optotronic/izpack,codehaus/izpack,tomas-forsman/izpack,stenix71/izpack,rsharipov/izpack,bradcfisher/izpack,codehaus/izpack,rkrell/izpack,Helpstone/izpack,yukron/izpack,yukron/izpack,stenix71/izpack,tomas-forsman/izpack,akuhtz/izpack,stenix71/izpack,mtjandra/izpack,optotronic/izpack,rkrell/izpack,Helpstone/izpack,stenix71/izpack,rkrell/izpack,bradcfisher/izpack,optotronic/izpack,rsharipov/izpack,yukron/izpack,stenix71/izpack,Helpstone/izpack,akuhtz/izpack,Murdock01/izpack,maichler/izpack,Murdock01/izpack,rkrell/izpack,rsharipov/izpack,rkrell/izpack,bradcfisher/izpack,yukron/izpack,codehaus/izpack,mtjandra/izpack,izpack/izpack,izpack/izpack,tomas-forsman/izpack,izpack/izpack,tomas-forsman/izpack,mtjandra/izpack,optotronic/izpack,bradcfisher/izpack,rkrell/izpack,Murdock01/izpack
/* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2002 Jan Blok * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.panels.userinput; import com.izforge.izpack.api.adaptator.IXMLElement; import com.izforge.izpack.api.data.AutomatedInstallData; import com.izforge.izpack.api.substitutor.VariableSubstitutor; import com.izforge.izpack.core.substitutor.VariableSubstitutorImpl; import com.izforge.izpack.installer.console.PanelConsole; import com.izforge.izpack.installer.console.PanelConsoleHelper; import com.izforge.izpack.panels.userinput.processor.Processor; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.OsVersion; import com.izforge.izpack.util.helper.SpecHelper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * The user input panel console helper class. * * @author Mounir El Hajj */ public class UserInputPanelConsoleHelper extends PanelConsoleHelper implements PanelConsole { protected int instanceNumber = 0; private static int instanceCount = 0; private static final String SPEC_FILE_NAME = "userInputSpec.xml"; private static final String NODE_ID = "panel"; private static final String INSTANCE_IDENTIFIER = "order"; protected static final String PANEL_IDENTIFIER = "id"; private static final String FIELD_NODE_ID = "field"; protected static final String ATTRIBUTE_CONDITIONID_NAME = "conditionid"; private static final String VARIABLE = "variable"; private static final String SET = "set"; private static final String TEXT = "txt"; private static final String SPEC = "spec"; private static final String PWD = "pwd"; private static final String TYPE_ATTRIBUTE = "type"; private static final String TEXT_FIELD = "text"; private static final String COMBO_FIELD = "combo"; private static final String STATIC_TEXT = "staticText"; private static final String CHOICE = "choice"; private static final String FILE = "file"; private static final String PASSWORD = "password"; private static final String VALUE = "value"; private static final String RADIO_FIELD = "radio"; private static final String TITLE_FIELD = "title"; private static final String CHECK_FIELD = "check"; private static final String RULE_FIELD = "rule"; private static final String SPACE = "space"; private static final String DIVIDER = "divider"; static final String DISPLAY_FORMAT = "displayFormat"; static final String PLAIN_STRING = "plainString"; static final String SPECIAL_SEPARATOR = "specialSeparator"; static final String LAYOUT = "layout"; static final String RESULT_FORMAT = "resultFormat"; private static final String DESCRIPTION = "description"; private static final String TRUE = "true"; private static final String NAME = "name"; private static final String FAMILY = "family"; private static final String OS = "os"; private static final String SELECTEDPACKS = "createForPack"; private static Input SPACE_INTPUT_FIELD = new Input(SPACE, null, null, SPACE, "\r", 0); private static Input DIVIDER_INPUT_FIELD = new Input(DIVIDER, null, null, DIVIDER, "------------------------------------------", 0); public List<Input> listInputs; public UserInputPanelConsoleHelper() { instanceNumber = instanceCount++; listInputs = new ArrayList<Input>(); } public boolean runConsoleFromProperties(AutomatedInstallData installData, Properties p) { collectInputs(installData); for (Input listInput : listInputs) { String strVariableName = listInput.strVariableName; if (strVariableName != null) { String strVariableValue = p.getProperty(strVariableName); if (strVariableValue != null) { installData.setVariable(strVariableName, strVariableValue); } } } return true; } public boolean runGeneratePropertiesFile(AutomatedInstallData installData, PrintWriter printWriter) { collectInputs(installData); for (Input input : listInputs) { if (input.strVariableName != null) { printWriter.println(input.strVariableName + "="); } } return true; } public boolean runConsole(AutomatedInstallData idata) { boolean processpanel = collectInputs(idata); if (!processpanel) { return true; } boolean status = true; for (Input input : listInputs) { if (TEXT_FIELD.equals(input.strFieldType) || FILE.equals(input.strFieldType) || RULE_FIELD.equals(input.strFieldType)) { status = status && processTextField(input, idata); } else if (COMBO_FIELD.equals(input.strFieldType) || RADIO_FIELD.equals(input.strFieldType)) { status = status && processComboRadioField(input, idata); } else if (CHECK_FIELD.equals(input.strFieldType)) { status = status && processCheckField(input, idata); } else if (STATIC_TEXT.equals(input.strFieldType) || TITLE_FIELD.equals(input.strFieldType) || DIVIDER.equals(input.strFieldType) || SPACE.equals(input.strFieldType)) { status = status && processSimpleField(input, idata); } else if (PASSWORD.equals(input.strFieldType)) { status = status && processPasswordField(input, idata); } } int i = askEndOfConsolePanel(); if (i == 1) { return true; } else if (i == 2) { return false; } else { return runConsole(idata); } } public boolean collectInputs(AutomatedInstallData idata) { listInputs.clear(); IXMLElement spec = null; List<IXMLElement> specElements; String attribute; String dataID; String panelid = idata.getPanelsOrder().get(idata.getCurPanelNumber()).getPanelid(); String instance = Integer.toString(instanceNumber); SpecHelper specHelper = new SpecHelper(); try { specHelper.readSpec(specHelper.getResource(SPEC_FILE_NAME)); } catch (Exception e1) { e1.printStackTrace(); return false; } specElements = specHelper.getSpec().getChildrenNamed(NODE_ID); for (IXMLElement data : specElements) { attribute = data.getAttribute(INSTANCE_IDENTIFIER); dataID = data.getAttribute(PANEL_IDENTIFIER); if (((attribute != null) && instance.equals(attribute)) || ((dataID != null) && (panelid != null) && (panelid.equals(dataID)))) { List<IXMLElement> forPacks = data.getChildrenNamed(SELECTEDPACKS); List<IXMLElement> forOs = data.getChildrenNamed(OS); if (itemRequiredFor(forPacks, idata) && itemRequiredForOs(forOs)) { spec = data; break; } } } if (spec == null) { return false; } List<IXMLElement> fields = spec.getChildrenNamed(FIELD_NODE_ID); for (IXMLElement field : fields) { List<IXMLElement> forPacks = field.getChildrenNamed(SELECTEDPACKS); List<IXMLElement> forOs = field.getChildrenNamed(OS); if (itemRequiredFor(forPacks, idata) && itemRequiredForOs(forOs)) { String conditionid = field.getAttribute(ATTRIBUTE_CONDITIONID_NAME); if (conditionid != null) { // check if condition is fulfilled if (!idata.getRules().isConditionTrue(conditionid, idata.getVariables())) { continue; } } Input in = getInputFromField(field, idata); if (in != null) { listInputs.add(in); } } } return true; } boolean processSimpleField(Input input, AutomatedInstallData idata) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata.getVariables()); try { System.out.println(variableSubstitutor.substitute(input.strText)); } catch (Exception e) { System.out.println(input.strText); } return true; } boolean processPasswordField(Input input, AutomatedInstallData idata) { Password pwd = (Password) input; boolean rtn = false; for (int i = 0; i < pwd.input.length; i++) { rtn = processTextField(pwd.input[i], idata); if (!rtn) { return rtn; } } return rtn; } boolean processTextField(Input input, AutomatedInstallData idata) { String variable = input.strVariableName; String set; String fieldText; if ((variable == null) || (variable.length() == 0)) { return false; } if (input.listChoices.size() == 0) { Debug.trace("Error: no spec element defined in file field"); return false; } set = idata.getVariable(variable); if (set == null) { set = input.strDefaultValue; if (set == null) { set = ""; } } if (!"".equals(set)) { VariableSubstitutor vs = new VariableSubstitutorImpl(idata.getVariables()); try { set = vs.substitute(set); } catch (Exception e) { // ignore } } fieldText = input.listChoices.get(0).strText; System.out.println(fieldText + " [" + set + "] "); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String strIn = br.readLine(); if (!strIn.trim().equals("")) { idata.setVariable(variable, strIn); } else { idata.setVariable(variable, set); } } catch (IOException e) { e.printStackTrace(); } return true; } boolean processComboRadioField(Input input, AutomatedInstallData idata) {// TODO protection if selection not valid and no set value String variable = input.strVariableName; if ((variable == null) || (variable.length() == 0)) { return false; } String currentvariablevalue = idata.getVariable(variable); //If we dont do this, choice with index=0 will always be displayed, no matter what is selected input.iSelectedChoice = -1; boolean userinput = false; // display the description for this combo or radio field if (input.strText != null) { System.out.println(input.strText); } List<Choice> lisChoices = input.listChoices; if (lisChoices.size() == 0) { Debug.trace("Error: no spec element defined in file field"); return false; } if (currentvariablevalue != null) { userinput = true; } for (int i = 0; i < lisChoices.size(); i++) { Choice choice = lisChoices.get(i); String value = choice.strValue; // if the choice value is provided via a property to the process, then // set it as the selected choice, rather than defaulting to what the // spec defines. if (userinput) { if ((value != null) && (value.length() > 0) && (currentvariablevalue.equals(value))) { input.iSelectedChoice = i; } } else { String set = choice.strSet; if (set != null) { if (set != null && !"".equals(set)) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata.getVariables()); set = variableSubstitutor.substitute(set); } if (set.equals(TRUE)) { input.iSelectedChoice = i; } } } System.out.println(i + " [" + (input.iSelectedChoice == i ? "x" : " ") + "] " + (choice.strText != null ? choice.strText : "")); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); boolean bKeepAsking = true; while (bKeepAsking) { System.out.println("input selection:"); String strIn = reader.readLine(); // take default value if default value exists and no user input if (strIn.trim().equals("") && input.iSelectedChoice != -1) { bKeepAsking = false; } int j = -1; try { j = Integer.valueOf(strIn); } catch (Exception ex) { } // take user input if user input is valid if (j >= 0 && j < lisChoices.size()) { input.iSelectedChoice = j; bKeepAsking = false; } } } catch (IOException e) { e.printStackTrace(); } idata.setVariable(variable, input.listChoices.get(input.iSelectedChoice).strValue); return true; } boolean processCheckField(Input input, AutomatedInstallData idata) { String variable = input.strVariableName; if ((variable == null) || (variable.length() == 0)) { return false; } String currentvariablevalue = idata.getVariable(variable); if (currentvariablevalue == null) { currentvariablevalue = ""; } List<Choice> lisChoices = input.listChoices; if (lisChoices.size() == 0) { Debug.trace("Error: no spec element defined in check field"); return false; } Choice choice = null; for (int i = 0; i < lisChoices.size(); i++) { choice = lisChoices.get(i); String value = choice.strValue; if ((value != null) && (value.length() > 0) && (currentvariablevalue.equals(value))) { input.iSelectedChoice = i; } else { String set = input.strDefaultValue; if (set != null) { if (set != null && !"".equals(set)) { VariableSubstitutor vs = new VariableSubstitutorImpl(idata.getVariables()); try { set = vs.substitute(set); } catch (Exception e) { // ignore } } if (set.equals(TRUE)) { input.iSelectedChoice = 1; } } } } System.out.println(" [" + (input.iSelectedChoice == 1 ? "x" : " ") + "] " + (choice.strText != null ? choice.strText : "")); try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); boolean bKeepAsking = true; while (bKeepAsking) { System.out.println("input 1 to select, 0 to deselect:"); String strIn = reader.readLine(); // take default value if default value exists and no user input if (strIn.trim().equals("")) { bKeepAsking = false; } int j = -1; try { j = Integer.valueOf(strIn); } catch (Exception ex) { } // take user input if user input is valid if ((j == 0) || j == 1) { input.iSelectedChoice = j; bKeepAsking = false; } } } catch (IOException e) { e.printStackTrace(); } idata.setVariable(variable, input.listChoices.get(input.iSelectedChoice).strValue); return true; } public Input getInputFromField(IXMLElement field, AutomatedInstallData idata) { String strVariableName = field.getAttribute(VARIABLE); String strFieldType = field.getAttribute(TYPE_ATTRIBUTE); if (TITLE_FIELD.equals(strFieldType)) { String strText = null; strText = field.getAttribute(TEXT); return new Input(strVariableName, null, null, TITLE_FIELD, strText, 0); } if (STATIC_TEXT.equals(strFieldType)) { String strText = null; strText = field.getAttribute(TEXT); return new Input(strVariableName, null, null, STATIC_TEXT, strText, 0); } if (TEXT_FIELD.equals(strFieldType) || FILE.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); if (spec != null) { strText = spec.getAttribute(TEXT); strSet = spec.getAttribute(SET); } if (description != null) { strFieldText = description.getAttribute(TEXT); } choicesList.add(new Choice(strText, null, strSet)); return new Input(strVariableName, strSet, choicesList, strFieldType, strFieldText, 0); } if (RULE_FIELD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); if (spec != null) { strText = spec.getAttribute(TEXT); strSet = spec.getAttribute(SET); } if (description != null) { strFieldText = description.getAttribute(TEXT); } if (strSet != null && spec.getAttribute(LAYOUT) != null) { StringTokenizer layoutTokenizer = new StringTokenizer(spec.getAttribute(LAYOUT)); List<String> listSet = Arrays.asList(new String[layoutTokenizer.countTokens()]); StringTokenizer setTokenizer = new StringTokenizer(strSet); String token; while (setTokenizer.hasMoreTokens()) { token = setTokenizer.nextToken(); if (token.contains(":")) { listSet.set(new Integer(token.substring(0, token.indexOf(":"))), token.substring(token.indexOf(":") + 1)); } } int iCounter = 0; StringBuffer buffer = new StringBuffer(); String strRusultFormat = spec.getAttribute(RESULT_FORMAT); String strSpecialSeparator = spec.getAttribute(SPECIAL_SEPARATOR); while (layoutTokenizer.hasMoreTokens()) { token = layoutTokenizer.nextToken(); if (token.matches(".*:.*:.*")) { buffer.append(listSet.get(iCounter) != null ? listSet.get(iCounter) : ""); iCounter++; } else { if (SPECIAL_SEPARATOR.equals(strRusultFormat)) { buffer.append(strSpecialSeparator); } else if (PLAIN_STRING.equals(strRusultFormat)) { } else // if (DISPLAY_FORMAT.equals(strRusultFormat)) { buffer.append(token); } } } strSet = buffer.toString(); } choicesList.add(new Choice(strText, null, strSet)); return new Input(strVariableName, strSet, choicesList, TEXT_FIELD, strFieldText, 0); } if (COMBO_FIELD.equals(strFieldType) || RADIO_FIELD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; int selection = -1; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); List<IXMLElement> choices = null; if (spec != null) { choices = spec.getChildrenNamed(CHOICE); } if (description != null) { strFieldText = description.getAttribute(TEXT); } for (int i = 0; i < choices.size(); i++) { IXMLElement choice = choices.get(i); String processorClass = choice.getAttribute("processor"); if (processorClass != null && !"".equals(processorClass)) { String choiceValues = ""; try { choiceValues = ((Processor) Class.forName(processorClass).newInstance()) .process(null); } catch (Throwable t) { t.printStackTrace(); } String set = choice.getAttribute(SET); if (set == null) { set = ""; } if (set != null && !"".equals(set)) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata.getVariables()); set = variableSubstitutor.substitute(set); } StringTokenizer tokenizer = new StringTokenizer(choiceValues, ":"); int counter = 0; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String choiceSet = null; if (token.equals(set) ) { choiceSet = "true"; selection = counter; } choicesList.add(new Choice( token, token, choiceSet)); counter++; } } else { String value = choice.getAttribute(VALUE); String set = choice.getAttribute(SET); if (set != null) { if (set != null && !"".equals(set)) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata .getVariables()); set = variableSubstitutor.substitute(set); } if (set.equalsIgnoreCase(TRUE)) { selection = i; } } choicesList.add(new Choice( choice.getAttribute(TEXT), value, set)); } } if (choicesList.size() == 1) { selection = 0; } return new Input(strVariableName, null, choicesList, strFieldType, strFieldText, selection); } if (CHECK_FIELD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; int iSelectedChoice = 0; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); if (spec != null) { strText = spec.getAttribute(TEXT); strSet = spec.getAttribute(SET); choicesList.add(new Choice(strText, spec.getAttribute("false"), null)); choicesList.add(new Choice(strText, spec.getAttribute("true"), null)); if (strSet != null) { if (strSet.equalsIgnoreCase(TRUE)) { iSelectedChoice = 1; } } } else { System.out.println("No spec specified for input of type check"); } if (description != null) { strFieldText = description.getAttribute(TEXT); } return new Input(strVariableName, strSet, choicesList, CHECK_FIELD, strFieldText, iSelectedChoice); } if (SPACE.equals(strFieldType)) { return SPACE_INTPUT_FIELD; } if (DIVIDER.equals(strFieldType)) { return DIVIDER_INPUT_FIELD; } if (PASSWORD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; IXMLElement spec = field.getFirstChildNamed(SPEC); if (spec != null) { List<IXMLElement> pwds = spec.getChildrenNamed(PWD); if (pwds == null || pwds.size() == 0) { System.out.println("No pwd specified in the spec for type password"); return null; } Input[] inputs = new Input[pwds.size()]; for (int i = 0; i < pwds.size(); i++) { IXMLElement pwde = pwds.get(i); strText = pwde.getAttribute(TEXT); strSet = pwde.getAttribute(SET); choicesList.add(new Choice(strText, null, strSet)); inputs[i] = new Input(strVariableName, strSet, choicesList, strFieldType, strFieldText, 0); } return new Password(strFieldType, inputs); } System.out.println("No spec specified for input of type password"); return null; } System.out.println(strFieldType + " field collection not implemented"); return null; } /*--------------------------------------------------------------------------*/ /** * Verifies if an item is required for any of the packs listed. An item is required for a pack * in the list if that pack is actually selected for installation. <br> * <br> * <b>Note:</b><br> * If the list of selected packs is empty then <code>true</code> is always returnd. The same is * true if the <code>packs</code> list is empty. * * @param packs a <code>Vector</code> of <code>String</code>s. Each of the strings denotes a * pack for which an item should be created if the pack is actually installed. * @return <code>true</code> if the item is required for at least one pack in the list, * otherwise returns <code>false</code>. */ /*--------------------------------------------------------------------------*/ /* * $ @design * * The information about the installed packs comes from InstallData.selectedPacks. This assumes * that this panel is presented to the user AFTER the PacksPanel. * -------------------------------------------------------------------------- */ private boolean itemRequiredFor(List<IXMLElement> packs, AutomatedInstallData idata) { String selected; String required; if (packs.size() == 0) { return (true); } // ---------------------------------------------------- // We are getting to this point if any packs have been // specified. This means that there is a possibility // that some UI elements will not get added. This // means that we can not allow to go back to the // PacksPanel, because the process of building the // UI is not reversable. // ---------------------------------------------------- // packsDefined = true; // ---------------------------------------------------- // analyze if the any of the packs for which the item // is required have been selected for installation. // ---------------------------------------------------- for (int i = 0; i < idata.getSelectedPacks().size(); i++) { selected = idata.getSelectedPacks().get(i).name; for (IXMLElement pack : packs) { required = pack.getAttribute(NAME, ""); if (selected.equals(required)) { return (true); } } } return (false); } /** * Verifies if an item is required for the operating system the installer executed. The * configuration for this feature is: <br/> * &lt;os family="unix"/&gt; <br> * <br> * <b>Note:</b><br> * If the list of the os is empty then <code>true</code> is always returnd. * * @param os The <code>Vector</code> of <code>String</code>s. containing the os names * @return <code>true</code> if the item is required for the os, otherwise returns * <code>false</code>. */ public boolean itemRequiredForOs(List<IXMLElement> os) { if (os.size() == 0) { return true; } for (IXMLElement osElement : os) { String family = osElement.getAttribute(FAMILY); boolean match = false; if ("windows".equals(family)) { match = OsVersion.IS_WINDOWS; } else if ("mac".equals(family)) { match = OsVersion.IS_OSX; } else if ("unix".equals(family)) { match = OsVersion.IS_UNIX; } if (match) { return true; } } return false; } public static class Input { public Input(String strFieldType) { this.strFieldType = strFieldType; } public Input(String strVariableName, String strDefaultValue, List<Choice> listChoices, String strFieldType, String strFieldText, int iSelectedChoice) { this.strVariableName = strVariableName; this.strDefaultValue = strDefaultValue; this.listChoices = listChoices; this.strFieldType = strFieldType; this.strText = strFieldText; this.iSelectedChoice = iSelectedChoice; } String strVariableName; String strDefaultValue; List<Choice> listChoices; String strFieldType; String strText; int iSelectedChoice = -1; } public static class Choice { public Choice(String strText, String strValue, String strSet) { this.strText = strText; this.strValue = strValue; this.strSet = strSet; } String strText; String strValue; String strSet; } public static class Password extends Input { public Password(String strFieldType, Input[] input) { super(strFieldType); this.input = input; } Input[] input; } }
izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/UserInputPanelConsoleHelper.java
/* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2002 Jan Blok * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.izforge.izpack.panels.userinput; import com.izforge.izpack.api.adaptator.IXMLElement; import com.izforge.izpack.api.data.AutomatedInstallData; import com.izforge.izpack.api.substitutor.VariableSubstitutor; import com.izforge.izpack.core.substitutor.VariableSubstitutorImpl; import com.izforge.izpack.installer.console.PanelConsole; import com.izforge.izpack.installer.console.PanelConsoleHelper; import com.izforge.izpack.panels.userinput.processor.Processor; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.OsVersion; import com.izforge.izpack.util.helper.SpecHelper; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * The user input panel console helper class. * * @author Mounir El Hajj */ public class UserInputPanelConsoleHelper extends PanelConsoleHelper implements PanelConsole { protected int instanceNumber = 0; private static int instanceCount = 0; private static final String SPEC_FILE_NAME = "userInputSpec.xml"; private static final String NODE_ID = "panel"; private static final String INSTANCE_IDENTIFIER = "order"; protected static final String PANEL_IDENTIFIER = "id"; private static final String FIELD_NODE_ID = "field"; protected static final String ATTRIBUTE_CONDITIONID_NAME = "conditionid"; private static final String VARIABLE = "variable"; private static final String SET = "set"; private static final String TEXT = "txt"; private static final String SPEC = "spec"; private static final String PWD = "pwd"; private static final String TYPE_ATTRIBUTE = "type"; private static final String TEXT_FIELD = "text"; private static final String COMBO_FIELD = "combo"; private static final String STATIC_TEXT = "staticText"; private static final String CHOICE = "choice"; private static final String FILE = "file"; private static final String PASSWORD = "password"; private static final String VALUE = "value"; private static final String RADIO_FIELD = "radio"; private static final String TITLE_FIELD = "title"; private static final String CHECK_FIELD = "check"; private static final String RULE_FIELD = "rule"; private static final String SPACE = "space"; private static final String DIVIDER = "divider"; static final String DISPLAY_FORMAT = "displayFormat"; static final String PLAIN_STRING = "plainString"; static final String SPECIAL_SEPARATOR = "specialSeparator"; static final String LAYOUT = "layout"; static final String RESULT_FORMAT = "resultFormat"; private static final String DESCRIPTION = "description"; private static final String TRUE = "true"; private static final String NAME = "name"; private static final String FAMILY = "family"; private static final String OS = "os"; private static final String SELECTEDPACKS = "createForPack"; private static Input SPACE_INTPUT_FIELD = new Input(SPACE, null, null, SPACE, "\r", 0); private static Input DIVIDER_INPUT_FIELD = new Input(DIVIDER, null, null, DIVIDER, "------------------------------------------", 0); public List<Input> listInputs; public UserInputPanelConsoleHelper() { instanceNumber = instanceCount++; listInputs = new ArrayList<Input>(); } public boolean runConsoleFromProperties(AutomatedInstallData installData, Properties p) { collectInputs(installData); for (Input listInput : listInputs) { String strVariableName = listInput.strVariableName; if (strVariableName != null) { String strVariableValue = p.getProperty(strVariableName); if (strVariableValue != null) { installData.setVariable(strVariableName, strVariableValue); } } } return true; } public boolean runGeneratePropertiesFile(AutomatedInstallData installData, PrintWriter printWriter) { collectInputs(installData); for (Input input : listInputs) { if (input.strVariableName != null) { printWriter.println(input.strVariableName + "="); } } return true; } public boolean runConsole(AutomatedInstallData idata) { boolean processpanel = collectInputs(idata); if (!processpanel) { return true; } boolean status = true; for (Input input : listInputs) { if (TEXT_FIELD.equals(input.strFieldType) || FILE.equals(input.strFieldType) || RULE_FIELD.equals(input.strFieldType)) { status = status && processTextField(input, idata); } else if (COMBO_FIELD.equals(input.strFieldType) || RADIO_FIELD.equals(input.strFieldType)) { status = status && processComboRadioField(input, idata); } else if (CHECK_FIELD.equals(input.strFieldType)) { status = status && processCheckField(input, idata); } else if (STATIC_TEXT.equals(input.strFieldType) || TITLE_FIELD.equals(input.strFieldType) || DIVIDER.equals(input.strFieldType) || SPACE.equals(input.strFieldType)) { status = status && processSimpleField(input, idata); } else if (PASSWORD.equals(input.strFieldType)) { status = status && processPasswordField(input, idata); } } int i = askEndOfConsolePanel(); if (i == 1) { return true; } else if (i == 2) { return false; } else { return runConsole(idata); } } public boolean collectInputs(AutomatedInstallData idata) { listInputs.clear(); IXMLElement spec = null; List<IXMLElement> specElements; String attribute; String dataID; String panelid = idata.getPanelsOrder().get(idata.getCurPanelNumber()).getPanelid(); String instance = Integer.toString(instanceNumber); SpecHelper specHelper = new SpecHelper(); try { specHelper.readSpec(specHelper.getResource(SPEC_FILE_NAME)); } catch (Exception e1) { e1.printStackTrace(); return false; } specElements = specHelper.getSpec().getChildrenNamed(NODE_ID); for (IXMLElement data : specElements) { attribute = data.getAttribute(INSTANCE_IDENTIFIER); dataID = data.getAttribute(PANEL_IDENTIFIER); if (((attribute != null) && instance.equals(attribute)) || ((dataID != null) && (panelid != null) && (panelid.equals(dataID)))) { List<IXMLElement> forPacks = data.getChildrenNamed(SELECTEDPACKS); List<IXMLElement> forOs = data.getChildrenNamed(OS); if (itemRequiredFor(forPacks, idata) && itemRequiredForOs(forOs)) { spec = data; break; } } } if (spec == null) { return false; } List<IXMLElement> fields = spec.getChildrenNamed(FIELD_NODE_ID); for (IXMLElement field : fields) { List<IXMLElement> forPacks = field.getChildrenNamed(SELECTEDPACKS); List<IXMLElement> forOs = field.getChildrenNamed(OS); if (itemRequiredFor(forPacks, idata) && itemRequiredForOs(forOs)) { String conditionid = field.getAttribute(ATTRIBUTE_CONDITIONID_NAME); if (conditionid != null) { // check if condition is fulfilled if (!idata.getRules().isConditionTrue(conditionid, idata.getVariables())) { continue; } } Input in = getInputFromField(field, idata); if (in != null) { listInputs.add(in); } } } return true; } boolean processSimpleField(Input input, AutomatedInstallData idata) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata.getVariables()); try { System.out.println(variableSubstitutor.substitute(input.strText)); } catch (Exception e) { System.out.println(input.strText); } return true; } boolean processPasswordField(Input input, AutomatedInstallData idata) { Password pwd = (Password) input; boolean rtn = false; for (int i = 0; i < pwd.input.length; i++) { rtn = processTextField(pwd.input[i], idata); if (!rtn) { return rtn; } } return rtn; } boolean processTextField(Input input, AutomatedInstallData idata) { String variable = input.strVariableName; String set; String fieldText; if ((variable == null) || (variable.length() == 0)) { return false; } if (input.listChoices.size() == 0) { Debug.trace("Error: no spec element defined in file field"); return false; } set = idata.getVariable(variable); if (set == null) { set = input.strDefaultValue; if (set == null) { set = ""; } } if (!"".equals(set)) { VariableSubstitutor vs = new VariableSubstitutorImpl(idata.getVariables()); try { set = vs.substitute(set); } catch (Exception e) { // ignore } } fieldText = input.listChoices.get(0).strText; System.out.println(fieldText + " [" + set + "] "); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String strIn = br.readLine(); if (!strIn.trim().equals("")) { idata.setVariable(variable, strIn); } else { idata.setVariable(variable, set); } } catch (IOException e) { e.printStackTrace(); } return true; } boolean processComboRadioField(Input input, AutomatedInstallData idata) {// TODO protection if selection not valid and no set value String variable = input.strVariableName; if ((variable == null) || (variable.length() == 0)) { return false; } String currentvariablevalue = idata.getVariable(variable); //If we dont do this, choice with index=0 will always be displayed, no matter what is selected input.iSelectedChoice = -1; boolean userinput = false; // display the description for this combo or radio field if (input.strText != null) { System.out.println(input.strText); } List<Choice> lisChoices = input.listChoices; if (lisChoices.size() == 0) { Debug.trace("Error: no spec element defined in file field"); return false; } if (currentvariablevalue != null) { userinput = true; } for (int i = 0; i < lisChoices.size(); i++) { Choice choice = lisChoices.get(i); String value = choice.strValue; // if the choice value is provided via a property to the process, then // set it as the selected choice, rather than defaulting to what the // spec defines. if (userinput) { if ((value != null) && (value.length() > 0) && (currentvariablevalue.equals(value))) { input.iSelectedChoice = i; } } else { String set = choice.strSet; if (set != null) { if (set != null && !"".equals(set)) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata.getVariables()); set = variableSubstitutor.substitute(set); } if (set.equals(TRUE)) { input.iSelectedChoice = i; } } } System.out.println(i + " [" + (input.iSelectedChoice == i ? "x" : " ") + "] " + (choice.strText != null ? choice.strText : "")); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); boolean bKeepAsking = true; while (bKeepAsking) { System.out.println("input selection:"); String strIn = reader.readLine(); // take default value if default value exists and no user input if (strIn.trim().equals("") && input.iSelectedChoice != -1) { bKeepAsking = false; } int j = -1; try { j = Integer.valueOf(strIn); } catch (Exception ex) { } // take user input if user input is valid if (j >= 0 && j < lisChoices.size()) { input.iSelectedChoice = j; bKeepAsking = false; } } } catch (IOException e) { e.printStackTrace(); } idata.setVariable(variable, input.listChoices.get(input.iSelectedChoice).strValue); return true; } boolean processCheckField(Input input, AutomatedInstallData idata) { String variable = input.strVariableName; if ((variable == null) || (variable.length() == 0)) { return false; } String currentvariablevalue = idata.getVariable(variable); if (currentvariablevalue == null) { currentvariablevalue = ""; } List<Choice> lisChoices = input.listChoices; if (lisChoices.size() == 0) { Debug.trace("Error: no spec element defined in check field"); return false; } Choice choice = null; for (int i = 0; i < lisChoices.size(); i++) { choice = lisChoices.get(i); String value = choice.strValue; if ((value != null) && (value.length() > 0) && (currentvariablevalue.equals(value))) { input.iSelectedChoice = i; } else { String set = input.strDefaultValue; if (set != null) { if (set != null && !"".equals(set)) { VariableSubstitutor vs = new VariableSubstitutorImpl(idata.getVariables()); try { set = vs.substitute(set); } catch (Exception e) { // ignore } } if (set.equals(TRUE)) { input.iSelectedChoice = 1; } } } } System.out.println(" [" + (input.iSelectedChoice == 1 ? "x" : " ") + "] " + (choice.strText != null ? choice.strText : "")); try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); boolean bKeepAsking = true; while (bKeepAsking) { System.out.println("input 1 to select, 0 to deseclect:"); String strIn = reader.readLine(); // take default value if default value exists and no user input if (strIn.trim().equals("")) { bKeepAsking = false; } int j = -1; try { j = Integer.valueOf(strIn); } catch (Exception ex) { } // take user input if user input is valid if ((j == 0) || j == 1) { input.iSelectedChoice = j; bKeepAsking = false; } } } catch (IOException e) { e.printStackTrace(); } idata.setVariable(variable, input.listChoices.get(input.iSelectedChoice).strValue); return true; } public Input getInputFromField(IXMLElement field, AutomatedInstallData idata) { String strVariableName = field.getAttribute(VARIABLE); String strFieldType = field.getAttribute(TYPE_ATTRIBUTE); if (TITLE_FIELD.equals(strFieldType)) { String strText = null; strText = field.getAttribute(TEXT); return new Input(strVariableName, null, null, TITLE_FIELD, strText, 0); } if (STATIC_TEXT.equals(strFieldType)) { String strText = null; strText = field.getAttribute(TEXT); return new Input(strVariableName, null, null, STATIC_TEXT, strText, 0); } if (TEXT_FIELD.equals(strFieldType) || FILE.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); if (spec != null) { strText = spec.getAttribute(TEXT); strSet = spec.getAttribute(SET); } if (description != null) { strFieldText = description.getAttribute(TEXT); } choicesList.add(new Choice(strText, null, strSet)); return new Input(strVariableName, strSet, choicesList, strFieldType, strFieldText, 0); } if (RULE_FIELD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); if (spec != null) { strText = spec.getAttribute(TEXT); strSet = spec.getAttribute(SET); } if (description != null) { strFieldText = description.getAttribute(TEXT); } if (strSet != null && spec.getAttribute(LAYOUT) != null) { StringTokenizer layoutTokenizer = new StringTokenizer(spec.getAttribute(LAYOUT)); List<String> listSet = Arrays.asList(new String[layoutTokenizer.countTokens()]); StringTokenizer setTokenizer = new StringTokenizer(strSet); String token; while (setTokenizer.hasMoreTokens()) { token = setTokenizer.nextToken(); if (token.contains(":")) { listSet.set(new Integer(token.substring(0, token.indexOf(":"))), token.substring(token.indexOf(":") + 1)); } } int iCounter = 0; StringBuffer buffer = new StringBuffer(); String strRusultFormat = spec.getAttribute(RESULT_FORMAT); String strSpecialSeparator = spec.getAttribute(SPECIAL_SEPARATOR); while (layoutTokenizer.hasMoreTokens()) { token = layoutTokenizer.nextToken(); if (token.matches(".*:.*:.*")) { buffer.append(listSet.get(iCounter) != null ? listSet.get(iCounter) : ""); iCounter++; } else { if (SPECIAL_SEPARATOR.equals(strRusultFormat)) { buffer.append(strSpecialSeparator); } else if (PLAIN_STRING.equals(strRusultFormat)) { } else // if (DISPLAY_FORMAT.equals(strRusultFormat)) { buffer.append(token); } } } strSet = buffer.toString(); } choicesList.add(new Choice(strText, null, strSet)); return new Input(strVariableName, strSet, choicesList, TEXT_FIELD, strFieldText, 0); } if (COMBO_FIELD.equals(strFieldType) || RADIO_FIELD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; int selection = -1; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); List<IXMLElement> choices = null; if (spec != null) { choices = spec.getChildrenNamed(CHOICE); } if (description != null) { strFieldText = description.getAttribute(TEXT); } for (int i = 0; i < choices.size(); i++) { IXMLElement choice = choices.get(i); String processorClass = choice.getAttribute("processor"); if (processorClass != null && !"".equals(processorClass)) { String choiceValues = ""; try { choiceValues = ((Processor) Class.forName(processorClass).newInstance()) .process(null); } catch (Throwable t) { t.printStackTrace(); } String set = choice.getAttribute(SET); if (set == null) { set = ""; } if (set != null && !"".equals(set)) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata.getVariables()); set = variableSubstitutor.substitute(set); } StringTokenizer tokenizer = new StringTokenizer(choiceValues, ":"); int counter = 0; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String choiceSet = null; if (token.equals(set) ) { choiceSet = "true"; selection = counter; } choicesList.add(new Choice( token, token, choiceSet)); counter++; } } else { String value = choice.getAttribute(VALUE); String set = choice.getAttribute(SET); if (set != null) { if (set != null && !"".equals(set)) { VariableSubstitutor variableSubstitutor = new VariableSubstitutorImpl(idata .getVariables()); set = variableSubstitutor.substitute(set); } if (set.equalsIgnoreCase(TRUE)) { selection = i; } } choicesList.add(new Choice( choice.getAttribute(TEXT), value, set)); } } if (choicesList.size() == 1) { selection = 0; } return new Input(strVariableName, null, choicesList, strFieldType, strFieldText, selection); } if (CHECK_FIELD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; int iSelectedChoice = 0; IXMLElement spec = field.getFirstChildNamed(SPEC); IXMLElement description = field.getFirstChildNamed(DESCRIPTION); if (spec != null) { strText = spec.getAttribute(TEXT); strSet = spec.getAttribute(SET); choicesList.add(new Choice(strText, spec.getAttribute("false"), null)); choicesList.add(new Choice(strText, spec.getAttribute("true"), null)); if (strSet != null) { if (strSet.equalsIgnoreCase(TRUE)) { iSelectedChoice = 1; } } } else { System.out.println("No spec specified for input of type check"); } if (description != null) { strFieldText = description.getAttribute(TEXT); } return new Input(strVariableName, strSet, choicesList, CHECK_FIELD, strFieldText, iSelectedChoice); } if (SPACE.equals(strFieldType)) { return SPACE_INTPUT_FIELD; } if (DIVIDER.equals(strFieldType)) { return DIVIDER_INPUT_FIELD; } if (PASSWORD.equals(strFieldType)) { List<Choice> choicesList = new ArrayList<Choice>(); String strFieldText = null; String strSet = null; String strText = null; IXMLElement spec = field.getFirstChildNamed(SPEC); if (spec != null) { List<IXMLElement> pwds = spec.getChildrenNamed(PWD); if (pwds == null || pwds.size() == 0) { System.out.println("No pwd specified in the spec for type password"); return null; } Input[] inputs = new Input[pwds.size()]; for (int i = 0; i < pwds.size(); i++) { IXMLElement pwde = pwds.get(i); strText = pwde.getAttribute(TEXT); strSet = pwde.getAttribute(SET); choicesList.add(new Choice(strText, null, strSet)); inputs[i] = new Input(strVariableName, strSet, choicesList, strFieldType, strFieldText, 0); } return new Password(strFieldType, inputs); } System.out.println("No spec specified for input of type password"); return null; } System.out.println(strFieldType + " field collection not implemented"); return null; } /*--------------------------------------------------------------------------*/ /** * Verifies if an item is required for any of the packs listed. An item is required for a pack * in the list if that pack is actually selected for installation. <br> * <br> * <b>Note:</b><br> * If the list of selected packs is empty then <code>true</code> is always returnd. The same is * true if the <code>packs</code> list is empty. * * @param packs a <code>Vector</code> of <code>String</code>s. Each of the strings denotes a * pack for which an item should be created if the pack is actually installed. * @return <code>true</code> if the item is required for at least one pack in the list, * otherwise returns <code>false</code>. */ /*--------------------------------------------------------------------------*/ /* * $ @design * * The information about the installed packs comes from InstallData.selectedPacks. This assumes * that this panel is presented to the user AFTER the PacksPanel. * -------------------------------------------------------------------------- */ private boolean itemRequiredFor(List<IXMLElement> packs, AutomatedInstallData idata) { String selected; String required; if (packs.size() == 0) { return (true); } // ---------------------------------------------------- // We are getting to this point if any packs have been // specified. This means that there is a possibility // that some UI elements will not get added. This // means that we can not allow to go back to the // PacksPanel, because the process of building the // UI is not reversable. // ---------------------------------------------------- // packsDefined = true; // ---------------------------------------------------- // analyze if the any of the packs for which the item // is required have been selected for installation. // ---------------------------------------------------- for (int i = 0; i < idata.getSelectedPacks().size(); i++) { selected = idata.getSelectedPacks().get(i).name; for (IXMLElement pack : packs) { required = pack.getAttribute(NAME, ""); if (selected.equals(required)) { return (true); } } } return (false); } /** * Verifies if an item is required for the operating system the installer executed. The * configuration for this feature is: <br/> * &lt;os family="unix"/&gt; <br> * <br> * <b>Note:</b><br> * If the list of the os is empty then <code>true</code> is always returnd. * * @param os The <code>Vector</code> of <code>String</code>s. containing the os names * @return <code>true</code> if the item is required for the os, otherwise returns * <code>false</code>. */ public boolean itemRequiredForOs(List<IXMLElement> os) { if (os.size() == 0) { return true; } for (IXMLElement osElement : os) { String family = osElement.getAttribute(FAMILY); boolean match = false; if ("windows".equals(family)) { match = OsVersion.IS_WINDOWS; } else if ("mac".equals(family)) { match = OsVersion.IS_OSX; } else if ("unix".equals(family)) { match = OsVersion.IS_UNIX; } if (match) { return true; } } return false; } public static class Input { public Input(String strFieldType) { this.strFieldType = strFieldType; } public Input(String strVariableName, String strDefaultValue, List<Choice> listChoices, String strFieldType, String strFieldText, int iSelectedChoice) { this.strVariableName = strVariableName; this.strDefaultValue = strDefaultValue; this.listChoices = listChoices; this.strFieldType = strFieldType; this.strText = strFieldText; this.iSelectedChoice = iSelectedChoice; } String strVariableName; String strDefaultValue; List<Choice> listChoices; String strFieldType; String strText; int iSelectedChoice = -1; } public static class Choice { public Choice(String strText, String strValue, String strSet) { this.strText = strText; this.strValue = strValue; this.strSet = strSet; } String strText; String strValue; String strSet; } public static class Password extends Input { public Password(String strFieldType, Input[] input) { super(strFieldType); this.input = input; } Input[] input; } }
Fixes a typo (see IZPACK-608).
izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/UserInputPanelConsoleHelper.java
Fixes a typo (see IZPACK-608).
<ide><path>zpack-panel/src/main/java/com/izforge/izpack/panels/userinput/UserInputPanelConsoleHelper.java <ide> <ide> while (bKeepAsking) <ide> { <del> System.out.println("input 1 to select, 0 to deseclect:"); <add> System.out.println("input 1 to select, 0 to deselect:"); <ide> String strIn = reader.readLine(); <ide> // take default value if default value exists and no user input <ide> if (strIn.trim().equals(""))
Java
lgpl-2.1
a4c65769701c069dc0e052b22875301284aeb4a3
0
simoc/mapyrus,simoc/mapyrus,simoc/mapyrus
/* * This file is part of Mapyrus, software for plotting maps. * Copyright (C) 2003 - 2010 Simon Chenery. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package org.mapyrus; import java.awt.Color; import java.awt.Point; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedList; import org.mapyrus.dataset.DatasetFactory; import org.mapyrus.dataset.GeographicDataset; import org.mapyrus.font.StringDimension; import org.mapyrus.image.Bitmap; import org.mapyrus.image.ImageIOWrapper; /** * Contexts for interpretation that are pushed and popped as procedure * blocks are called and return so that changes in a procedure block * are local to that block. */ public class ContextStack { /* * Maximum allowed stacking of contexts. * Any deeper is probably infinite recursion. */ private static final int MAX_STACK_LENGTH = 30; /* * Prefix for internal variables. */ private static final String INTERNAL_VARIABLE_PREFIX = Constants.PROGRAM_NAME + "."; /* * Internal variable names. */ private static final String PATH_VARIABLE = "path"; private static final String WORLDS_VARIABLE = "worlds"; private static final String DATASET_VARIABLE = "dataset"; private static final String PAGE_VARIABLE = "page"; private static final String SCREEN_VARIABLE = "screen"; private static final String IMAGEMAP_VARIABLE = "imagemap"; /* * Stack of contexts, with current context in last slot. */ private LinkedList<Context> m_stack; /* * List of legend keys encountered whilst interpreting statements. */ private LegendEntryList m_legendEntries; /* * Cache of icons we've already used and are likely to use again. */ private LRUCache<String, BufferedImage> m_iconCache; /* * Time at which this context was allocated. */ private long m_startTime; /* * Point clicked in HTML imagemap and passed in HTTP request we are processing. */ private Point m_imagemapPoint; /* * HTTP header to return to HTTP client. */ private String m_HTTPResponse; /** * Create new stack of contexts to manage state as procedure blocks * are called. */ public ContextStack() { m_stack = new LinkedList<Context>(); m_stack.add(new Context()); m_startTime = System.currentTimeMillis(); m_imagemapPoint = null; m_legendEntries = new LegendEntryList(); m_iconCache = new LRUCache<String, BufferedImage>(Constants.ICON_CACHE_SIZE); m_HTTPResponse = HTTPRequest.HTTP_OK_KEYWORD + Constants.LINE_SEPARATOR + HTTPRequest.CONTENT_TYPE_KEYWORD + ": " + MimeTypes.get("html") + Constants.LINE_SEPARATOR; } /** * Get current context from top of stack. * @return current context. */ private Context getCurrentContext() { return((Context)m_stack.getLast()); } /** * Pops current context from stack. * @return number of elements left in stack after pop. */ private int popContext() throws IOException, MapyrusException { int i = m_stack.size(); if (i > 0) { /* * Finish off current context, remove it from stack. */ Context context = (Context)m_stack.removeLast(); i--; int attributesSet = context.closeContext(); /* * If graphics attributes were set in context then set them changed * in the context that is now current so they are set again * here before being used. */ if (i > 0 && attributesSet != 0) getCurrentContext().setAttributesChanged(attributesSet); } return(i); } /** * Pushes copy of context at top of stack onto stack. * This context is later removed with popContext(). * @param blockName is procedure block name containing statements to be executed. */ private void pushContext(String blockName) throws MapyrusException { if (m_stack.size() == MAX_STACK_LENGTH) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.RECURSION)); } m_stack.add(new Context(getCurrentContext(), blockName)); } /** * Set point passed in HTML imagemap request. * @param pt pixel position clicked in image. */ public void setImagemapPoint(Point pt) { m_imagemapPoint = pt; } /** * Sets output file for drawing to. * @param filename name of image file output will be saved to * @param format is image format for saved output * @param width is the page width (in mm). * @param height is the page height (in mm). * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public void setOutputFormat(String format, String filename, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { getCurrentContext().setOutputFormat(format, filename, width, height, extras, stdoutStream); } /** * Sets image for drawing to. * @param image is buffered image to draw into. * @param imageMapWriter is HTML image map to write to. * @param extras contains extra settings for this output. */ public void setOutputFormat(BufferedImage image, PrintWriter imageMapWriter, String extras) throws IOException, MapyrusException { getCurrentContext().setOutputFormat(image, imageMapWriter, extras); } /** * Sets image for drawing to. * @param image is buffered image to draw into. * @param extras contains extra settings for this output. */ public void setOutputFormat(BufferedImage image, String extras) throws IOException, MapyrusException { getCurrentContext().setOutputFormat(image, extras); } /** * Close any open output file being created. */ public void closeOutputFormat() throws IOException, MapyrusException { getCurrentContext().closeOutputFormat(); } /** * Sets linestyle. * @param width is width for lines in millimetres. * @param cap is a BasicStroke end cap value. * @param join is a BasicStroke line join value. * @param phase is offset at which pattern is started. * @param dashes list of dash pattern lengths. */ public void setLinestyle(double width, int cap, int join, double phase, float []dashes) { getCurrentContext().setLinestyle(width, cap, join, phase, dashes); } /** * Sets color. * @param c is new color for drawing. */ public void setColor(Color c) { getCurrentContext().setColor(c); } /** * Sets transparent color blend mode. * @param blend is blend mode. */ public void setBlend(String blend) { getCurrentContext().setBlend(blend); } /** * Get current color. * @return current color. */ public Color getColor() { Color retval = getCurrentContext().getColor(); return(retval); } /** * Sets font for labelling with. * @param name is name of font. * @param size is size for labelling in millimetres. * @param outlineWidth if non-zero, gives line width to use for drawing * outline of each character of labels. * @param lineSpacing spacing between lines in multi-line labels, as * a multiple of the font size. */ public void setFont(String name, double size, double outlineWidth, double lineSpacing) { getCurrentContext().setFont(name, size, outlineWidth, lineSpacing); } /** * Sets horizontal and vertical justification for labelling. * @param code is bit flags of Context.JUSTIFY_* values for justification. */ public void setJustify(int code) { getCurrentContext().setJustify(code); } /** * Sets scaling for subsequent coordinates. * @param factor is new scaling in X and Y axes. */ public void setScaling(double factor) throws MapyrusException { if (factor == 0.0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_SCALING)); else if (factor != 1.0) getCurrentContext().setScaling(factor); } /** * Sets translation for subsequent coordinates. * @param x is new point for origin on X axis. * @param y is new point for origin on Y axis. */ public void setTranslation(double x, double y) { if (x != 0.0 || y != 0.0) getCurrentContext().setTranslation(x, y); } /** * Sets rotation for subsequent coordinates. * @param angle is rotation angle in radians, going anti-clockwise. */ public void setRotation(double angle) { if (angle != 0.0) getCurrentContext().setRotation(angle); } /** * Sets transformation from real world coordinates to page coordinates. * @param wx1 minimum X world coordinate. * @param wy1 minimum Y world coordinate. * @param wx2 maximum X world coordinate. * @param wy2 maximum Y world coordinate. * @param px1 millimetre position on page of wx1. * @param py1 millimetre position on page of wy1. * @param px2 millimetre position on page of wx2, or 0 to use whole page. * @param py2 millimetre position on page of wy2, or 0 to use whole page. * @param units units of world coordinates (WORLD_UNITS_METRES,WORLD_UNITS_FEET, etc.) * @param allowDistortion if true then different scaling in X and Y axes allowed. */ public void setWorlds(double wx1, double wy1, double wx2, double wy2, double px1, double py1, double px2, double py2, int units, boolean allowDistortion) throws MapyrusException { getCurrentContext().setWorlds(wx1, wy1, wx2, wy2, px1, py1, px2, py2, units, allowDistortion); } /** * Gets real world coordinates of the page. */ public Rectangle2D.Double getWorlds() throws MapyrusException { Rectangle2D.Double retval = getCurrentContext().getWorldExtents(); return(retval); } /** * Transform geometry from page coordinates to world coordinates. * @param arg geometry. * @return transformed geometry. */ public Argument transformToWorlds(Argument arg) throws MapyrusException { Argument retval = getCurrentContext().transformToWorlds(arg); return(retval); } /** * Transform geometry from world coordinates to page coordinates. * @param arg geometry. * @return transformed geometry. */ public Argument transformToPage(Argument arg) throws MapyrusException { Argument retval = getCurrentContext().transformToPage(arg); return(retval); } /** * Sets dataset to read from. * @param type is format of dataset, for example, "text". * @param name is name of dataset to open. * @param extras are special options for this dataset type such as database * connection information, or instructions for interpreting data. * @param stdin standard ihput stream of interpreter. */ public void setDataset(String type, String name, String extras, InputStream stdin) throws MapyrusException { GeographicDataset dataset; dataset = DatasetFactory.open(type, name, extras, stdin); getCurrentContext().setDataset(dataset); } /** * Sets file for writing standard output to. * File will automatically be closed when this context is closed. * @param stdout stream to write to. */ public void setStdout(PrintStream stdout) throws IOException { getCurrentContext().setStdout(stdout); } /** * Add point to path. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void moveTo(double x, double y) throws MapyrusException { getCurrentContext().moveTo(x, y); } /** * Add point to path with straight line segment from last point. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void lineTo(double x, double y) throws MapyrusException { getCurrentContext().lineTo(x, y); } /** * Add point to path with straight line segment relative to last point. * @param x X coordinate distance to move, relative to last point. * @param y Y coordinate distance to move, relative to last point. */ public void rlineTo(double x, double y) throws MapyrusException { getCurrentContext().rlineTo(x, y); } /** * Add circular arc to path from last point to a new point, given centre and direction. * @param direction positive for clockwise, negative for anti-clockwise. * @param xCentre X coordinate of centre point of arc. * @param yCentre Y coordinate of centre point of arc. * @param xEnd X coordinate of end point of arc. * @param yEnd Y coordinate of end point of arc. */ public void arcTo(int direction, double xCentre, double yCentre, double xEnd, double yEnd) throws MapyrusException { getCurrentContext().arcTo(direction, xCentre, yCentre, xEnd, yEnd); } /** * Add Bezier curve to path from last point to a new point. * @param xControl1 X coordinate of first Bezier control point. * @param yControl1 Y coordinate of first Bezier control point. * @param xControl2 X coordinate of second Bezier control point. * @param yControl2 Y coordinate of second Bezier control point. * @param xEnd X coordinate of end point of curve. * @param yEnd Y coordinate of end point of curve. */ public void curveTo(double xControl1, double yControl1, double xControl2, double yControl2, double xEnd, double yEnd) throws MapyrusException { getCurrentContext().curveTo(xControl1, yControl1, xControl2, yControl2, xEnd, yEnd); } /** * Add Sine wave curve to path from last point to a new point. * @param x X coordinate of end of path. * @param y Y coordinate of end of path. * @param nRepeats number of repeats of sine wave pattern. * @param amplitude scaling factor for height of sine wave. */ public void sineWaveTo(double x, double y, double nRepeats, double amplitude) throws MapyrusException { getCurrentContext().sineWaveTo(x,y, nRepeats, amplitude); } /** * Adds ellipse to path. * @param xMin minimum X coordinate of rectangle containing ellipse. * @param yMin minimum Y coordinate of rectangle containing ellipse. * @param xMax maximum X coordinate of rectangle containing ellipse. * @param yMax maximum Y coordinate of rectangle containing ellipse. */ public void ellipseTo(double xMin, double yMin, double xMax, double yMax) throws MapyrusException { getCurrentContext().ellipseTo(xMin, yMin, xMax, yMax); } /** * Resets path to empty. */ public void clearPath() { getCurrentContext().clearPath(); } /** * Closes path back to last moveTo point. */ public void closePath() { getCurrentContext().closePath(); } /** * Draws icon on page. * @param filename file containing icon. * @param size size for icon on page in millimetres. */ public void drawIcon(String filename, double size) throws IOException, MapyrusException { BufferedImage icon; boolean isDigits = false; boolean isResource = false; int digitsType = 0; /* * Have we opened icon before and cached it? */ icon = (BufferedImage)m_iconCache.get(filename); if (icon == null) { URL url; /* * Check if icon is "inlined" as hex or binary digits. */ if (filename.length() >= 3) { char c1 = filename.charAt(0); char c2 = Character.toLowerCase(filename.charAt(1)); if (c1 == '#') { isDigits = true; digitsType = Bitmap.HEX_DIGIT_BITMAP; } else if (c1 == '0' && c2 == 'x') { isDigits = true; digitsType = Bitmap.HEX_DIGIT_BITMAP; } else if ((c1 == '0' || c1 == '1') && (c2 == '0' || c2 == '1')) { isDigits = true; digitsType = Bitmap.BINARY_DIGIT_BITMAP; } else if (filename.startsWith("resource:")) { isResource = true; filename = filename.substring(9); } } if (isDigits) { Bitmap bitmap = new Bitmap(filename, digitsType, getCurrentContext().getColor()); icon = bitmap.getBufferedImage(); } else { /* * Load icon from either as a resource from a JAR file, * a URL, or as a plain file. */ try { if (isResource) { ClassLoader loader = this.getClass().getClassLoader(); url = loader.getResource(filename); } else { url = new URL(filename); } icon = ImageIOWrapper.read(url, getCurrentContext().getColor()); } catch (MalformedURLException e) { icon = ImageIOWrapper.read(new File(filename), getCurrentContext().getColor()); } if (icon == null) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + filename); } } /* * Do not cache large icons, load them each time they are needed. * Do not cache an icon given as hex digits as we may want * it in a different color next time. */ if ((!isDigits) && icon.getHeight() * icon.getWidth() <= 128 * 128) m_iconCache.put(filename, icon); } getCurrentContext().drawIcon(icon, size); } /** * Draws geo-referenced image on page. * @param filename geo-referenced image filename. * @param extras extra parameters to control display of image. */ public void drawGeoImage(String filename, String extras) throws IOException, MapyrusException { getCurrentContext().drawGeoImage(filename, extras); } /** * Includes Encsapsulated PostScript file in page. * @param EPS filename. * @param size size for EPS file on page in millimetres. */ public void drawEPS(String filename, double size) throws IOException, MapyrusException { getCurrentContext().drawEPS(filename, size); } /** * Includes Scalable Vector Graphics file in page. * @param SVG filename. * @param size size for SVG file on page in millimetres. */ public void drawSVG(String filename, double size) throws IOException, MapyrusException { getCurrentContext().drawSVG(filename, size); } /** * Add Scalable Vector Graphics code to page. * @param xml XML elements to add to SVG file. */ public void addSVGCode(String xml) throws IOException, MapyrusException { getCurrentContext().addSVGCode(xml); } /** * Includes PDF file in page. * @param PDF filename. * @param page page number in PDF file to display. * @param size size for PDF file on page in millimetres. */ public void drawPDF(String filename, int page, double size) throws IOException, MapyrusException { getCurrentContext().drawPDF(filename, page, size); } /** * Replace path with regularly spaced points along it. * @param spacing is distance between points. * @param offset is starting offset of first point. */ public void samplePath(double spacing, double offset) throws MapyrusException { getCurrentContext().samplePath(spacing, offset); } /** * Replace path defining polygon with parallel stripe * lines covering the polygon. * @param spacing is distance between stripes. * @param angle is angle of stripes, in radians, with zero horizontal. */ public void stripePath(double spacing, double angle) { getCurrentContext().stripePath(spacing, angle); } /** * Shift all coordinates in path shifted by a fixed amount. * @param xShift distance in millimetres to shift X coordinate values. * @param yShift distance in millimetres to shift Y coordinate values. */ public void translatePath(double xShift, double yShift) { getCurrentContext().translatePath(xShift, yShift); } /** * Replace path with new paths at parallel distances to original path. * @param distances list of parallel distances for new paths. */ public void parallelPath(double []distances) throws MapyrusException { getCurrentContext().parallelPath(distances); } /** * Replace path with selected parts of path. * @param offsets offset along original path to select. * @param lengths length of original path to select at each offset. */ public void selectPath(double []offsets, double []lengths) throws MapyrusException { getCurrentContext().selectPath(offsets, lengths); } /** * Reverse direction of path. */ public void reversePath() throws MapyrusException { getCurrentContext().reversePath(); } /** * Replace path defining polygon with a sinkhole point. */ public void createSinkhole() { getCurrentContext().createSinkhole(); } /** * Replace path with path cut to rectangle defined by (x1, y1) and (x2, y2). * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. */ public void guillotine(double x1, double y1, double x2, double y2) throws MapyrusException { getCurrentContext().guillotine(x1, y1, x2, y2); } /** * Mark rectangular area on page (x1, y1) and (x2, y2) as protected. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. */ public void protect(double x1, double y1, double x2, double y2) throws MapyrusException { getCurrentContext().setPageMask(x1, y1, x2, y2, 1); } /** * Mark area on page as protected. * @param geometry area on page to protect. */ public void protect(Argument geometry) throws MapyrusException { getCurrentContext().setPageMask(geometry, 1); } /** * Mark area on page covered by current path as protected. */ public void protect() throws MapyrusException { getCurrentContext().setPageMask(1); } /** * Mark rectangular area on page (x1, y1) and (x2, y2) as unprotected. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. */ public void unprotect(double x1, double y1, double x2, double y2) throws MapyrusException { getCurrentContext().setPageMask(x1, y1, x2, y2, 0); } /** * Mark area on page as unprotected. * @param geometry area on page to unprotect. */ public void unprotect(Argument geometry) throws MapyrusException { getCurrentContext().setPageMask(geometry, 0); } /** * Mark area on page covered by current path as unprotected. */ public void unprotect() throws MapyrusException { getCurrentContext().setPageMask(0); } /** * Determine whether part of a rectangular area of page is protected. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. * @return true if part of this rectangular region is protected. */ public boolean isProtected(double x1, double y1, double x2, double y2) throws MapyrusException { boolean isZero = getCurrentContext().isPageMaskAllZero(x1, y1, x2, y2); return(!isZero); } /** * Determine whether a part of the page is protected. * @param geometry area to check. * @return true if any part of this region is protected. */ public boolean isProtected(Argument geometry) throws MapyrusException { boolean isZero = getCurrentContext().isPageMaskAllZero(geometry); return(!isZero); } /** * Determine whether a part of the page covered by current path is protected. * @return true if any part of path is protected. */ public boolean isProtected() throws MapyrusException { boolean isZero = getCurrentContext().isPageMaskAllZero(); return(!isZero); } /** * Draw currently defined path. * @param xmlAttributes XML attributes to add for SVG output. */ public void stroke(String xmlAttributes) throws IOException, MapyrusException { getCurrentContext().stroke(xmlAttributes); } /** * Fill currently defined path. * @param xmlAttribtes XML attributes to add for SVG output. */ public void fill(String xmlAttributes) throws IOException, MapyrusException { getCurrentContext().fill(xmlAttributes); } /** * Gradient fill current path. Colors at each of the four corners * of the path are defined. Colors will gradually fade * through the area covered by the path to give a smooth change * of color. * @param c1 color for lower left corner of path. * @param c2 color for lower right corner of path. * @param c3 color for upper left corner of path. * @param c4 color for upper right corner of path. * @param c5 color in center of path. */ public void gradientFill(Color c1, Color c2, Color c3, Color c4, Color c5) throws IOException, MapyrusException { getCurrentContext().gradientFill(c1, c2, c3, c4, c5); } /** * Set event script for currently defined path. * @param script commands to run for currently defined path. */ public void setEventScript(String script) throws IOException, MapyrusException { getCurrentContext().setEventScript(script); } /** * Clip to show only area outside currently defined path, * protecting what is inside path. */ public void clipOutside() throws MapyrusException { getCurrentContext().clipOutside(); } /** * Clip to show only area inside currently defined path. */ public void clipInside() { getCurrentContext().clipInside(); } /** * Draw label positioned at current point. * @param label label to draw. */ public void label(String label) throws IOException, MapyrusException { getCurrentContext().label(label); } /** * Draw label along currently defined path. * @param spacing spacing between letters. * @param offset offset along path at which to begin label. * @param label label to draw. */ public void flowLabel(double spacing, double offset, String label) throws IOException, MapyrusException { getCurrentContext().flowLabel(spacing, offset, label); } /** * Draw a table (a grid with a value in each cell) at current path position. * @param extras options for table. * @param list of arrays giving values in each column. */ public void drawTable(String extras, ArrayList columns) throws IOException, MapyrusException { getCurrentContext().drawTable(extras, columns); } /** * Draw a tree of labels at current path position. * @param extras options for tree. * @param tree array argument with tree entries. */ public void drawTree(String extras, Argument tree) throws IOException, MapyrusException { getCurrentContext().drawTree(extras, tree); } /** * Returns the number of moveTo's in path defined in current context. * @return count of moveTo calls made. */ public int getMoveToCount() { int retval = getCurrentContext().getMoveToCount(); return(retval); } /** * Returns the number of lineTo's in path defined in current context. * @return count of lineTo calls made for this path. */ public int getLineToCount() { int retval = getCurrentContext().getLineToCount(); return(retval); } /** * Returns rotation angle for each moveTo point in current path. * @return list of rotation angles. */ public ArrayList getMoveToRotations() { return(getCurrentContext().getMoveToRotations()); } /** * Returns coordinates for each each moveTo point in current path * @return list of Point2D.Float objects. */ public ArrayList getMoveTos() throws MapyrusException { return(getCurrentContext().getMoveTos()); } /** * Returns height and width of a string, drawn to current page with current font. * @param s string to calculate dimensions for. * @return height and width of string in millimetres. */ public StringDimension getStringDimension(String s) throws MapyrusException { StringDimension retval; try { retval = getCurrentContext().getStringDimension(s, true); } catch (IOException e) { throw new MapyrusException(e.getMessage()); } return(retval); } /** * Get resolution of page. * @return page resolution in millimetres. */ public double getResolution() throws MapyrusException { double retval = getCurrentContext().getResolution(); return(retval); } /** * Return next row from dataset. * @return field values for next row. */ public Row fetchRow() throws MapyrusException { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_DATASET)); return(dataset.fetchRow()); } /** * Return names of fields in current dataset. * @return names of fields. */ public String []getDatasetFieldNames() throws MapyrusException { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_DATASET)); String []retval = dataset.getFieldNames(); return(retval); } /** * Get stream that standard output is currently being sent to. * @return standard output stream. */ public PrintStream getStdout() { return(getCurrentContext().getStdout()); } /** * Returns one component of a bounding box. * @param part the information to be taken from the bounding box, "min.x", "width", etc. * @param bounds the bounding box to be queried * @return part of the information from bounding box, or null if part is unknown. */ private Argument getBoundingBoxVariable(String part, Rectangle2D bounds) { Argument retval; if (bounds == null) retval = Argument.numericZero; else if (part.equals("min.x")) retval = new Argument(bounds.getMinX()); else if (part.equals("min.y")) retval = new Argument(bounds.getMinY()); else if (part.equals("max.x")) retval = new Argument(bounds.getMaxX()); else if (part.equals("max.y")) retval = new Argument(bounds.getMaxY()); else if (part.equals("center.x") || part.equals("centre.x")) retval = new Argument(bounds.getCenterX()); else if (part.equals("center.y") || part.equals("centre.y")) retval = new Argument(bounds.getCenterY()); else if (part.equals("width")) retval = new Argument(bounds.getWidth()); else if (part.equals("height")) retval = new Argument(bounds.getHeight()); else retval = null; return(retval); } /** * Create string argument from two digit number. * @param i number to create string from. * @return argument containing value i. */ private Argument setTwoDigitNumber(int i) { Argument retval; if (i >= 10) retval = new Argument(Argument.STRING, Integer.toString(i)); else retval = new Argument(Argument.STRING, "0" + Integer.toString(i)); return(retval); } /** * Returns value of a variable. * @param varName variable name to lookup. * @param interpreterFilename name of file being interpreted. * @return value of variable, or null if it is not defined. */ public Argument getVariableValue(String varName, String interpreterFilename) throws MapyrusException { Argument retval = null; String sub; char c; double d; int i; Rectangle2D bounds; if (varName.startsWith(INTERNAL_VARIABLE_PREFIX) && varName.length() > INTERNAL_VARIABLE_PREFIX.length() && (!varName.equals(HTTPRequest.HTTP_HEADER_ARRAY))) { c = varName.charAt(INTERNAL_VARIABLE_PREFIX.length()); /* * Return internal/system variable. */ if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "fetch.more")) { Dataset dataset = getCurrentContext().getDataset(); if (dataset != null && dataset.hasMoreRows()) retval = Argument.numericOne; else retval = Argument.numericZero; } else if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "fetch.count")) { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) retval = Argument.numericZero; else retval = new Argument(dataset.getFetchCount()); } else if (c == 't' && varName.equals(INTERNAL_VARIABLE_PREFIX + "timer")) { /* * The elapsed time in seconds since this context was created * at the beginning of interpreting a file. */ retval = new Argument((System.currentTimeMillis() - m_startTime) / 1000.0); } else if (c == 't' && varName.startsWith(INTERNAL_VARIABLE_PREFIX + "time.")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + "time.".length()); GregorianCalendar calendar = new GregorianCalendar(); if (sub.equals("hour")) retval = setTwoDigitNumber(calendar.get(Calendar.HOUR_OF_DAY)); else if (sub.equals("minute")) retval = setTwoDigitNumber(calendar.get(Calendar.MINUTE)); else if (sub.equals("second")) retval = setTwoDigitNumber(calendar.get(Calendar.SECOND)); else if (sub.equals("day")) retval = setTwoDigitNumber(calendar.get(Calendar.DAY_OF_MONTH)); else if (sub.equals("day.name")) { SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); retval = new Argument(Argument.STRING, sdf.format(calendar.getTime())); } else if (sub.equals("month")) retval = setTwoDigitNumber(calendar.get(Calendar.MONTH) + 1); else if (sub.equals("month.name")) { SimpleDateFormat sdf = new SimpleDateFormat("MMMM"); retval = new Argument(Argument.STRING, sdf.format(calendar.getTime())); } else if (sub.equals("week.of.year")) retval = new Argument(calendar.get(Calendar.WEEK_OF_YEAR)); else if (sub.equals("day.of.week")) { int dayOfWeek; /* * Convert Java Calendar values for days into values 1-7, * with Monday=1 like in cron(1) tasks. */ int cd = calendar.get(Calendar.DAY_OF_WEEK); if (cd == Calendar.MONDAY) dayOfWeek = 1; else if (cd == Calendar.TUESDAY) dayOfWeek = 2; else if (cd == Calendar.WEDNESDAY) dayOfWeek = 3; else if (cd == Calendar.THURSDAY) dayOfWeek = 4; else if (cd == Calendar.FRIDAY) dayOfWeek = 5; else if (cd == Calendar.SATURDAY) dayOfWeek = 6; else dayOfWeek = 7; retval = new Argument(dayOfWeek); } else if (sub.equals("year")) retval = new Argument(calendar.get(Calendar.YEAR)); else if (sub.equals("stamp")) retval = new Argument(Argument.STRING, calendar.getTime().toString()); else retval = null; } else if (c == 'v' && varName.equals(INTERNAL_VARIABLE_PREFIX + "version")) { retval = new Argument(Argument.STRING, Constants.getVersion()); } else if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "freeMemory")) { retval = new Argument(Runtime.getRuntime().freeMemory()); } else if (c == 't' && varName.equals(INTERNAL_VARIABLE_PREFIX + "totalMemory")) { retval = new Argument(Runtime.getRuntime().totalMemory()); } else if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "filename")) { retval = new Argument(Argument.STRING, interpreterFilename); } else if (c == 'r' && varName.equals(INTERNAL_VARIABLE_PREFIX + "rotation")) { retval = new Argument(Math.toDegrees(getCurrentContext().getRotation())); } else if (c == 's' && varName.equals(INTERNAL_VARIABLE_PREFIX + "scale")) { retval = new Argument(getCurrentContext().getScaling()); } else if (c == 'k' && varName.equals(INTERNAL_VARIABLE_PREFIX + "key.count")) { retval = new Argument(m_legendEntries.size()); } else if (c == 'k' && varName.equals(INTERNAL_VARIABLE_PREFIX + "key.next")) { LegendEntry top = m_legendEntries.first(); if (top == null) retval = Argument.emptyString; else retval = new Argument(Argument.STRING, top.getBlockName()); } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + PAGE_VARIABLE + ".")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + PAGE_VARIABLE.length() + 1); if (sub.equals("width")) retval = new Argument(getCurrentContext().getPageWidth()); else if (sub.equals("height")) retval = new Argument(getCurrentContext().getPageHeight()); else if (sub.equals("format")) retval = new Argument(Argument.STRING, getCurrentContext().getPageFormat()); else if (sub.equals("resolution.mm")) retval = new Argument(getCurrentContext().getResolution()); else if (sub.equals("resolution.dpi")) { retval = new Argument(Constants.MM_PER_INCH / getCurrentContext().getResolution()); } else retval = null; } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + SCREEN_VARIABLE + ".")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + SCREEN_VARIABLE.length() + 1); if (sub.equals("width")) retval = new Argument(Constants.getScreenWidth()); else if (sub.equals("height")) retval = new Argument(Constants.getScreenHeight()); else if (sub.equals("resolution.dpi")) retval = new Argument(Constants.getScreenResolution()); else if (sub.equals("resolution.mm")) { retval = new Argument(Constants.MM_PER_INCH / Constants.getScreenResolution()); } else retval = null; } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + PATH_VARIABLE + ".")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + PATH_VARIABLE.length() + 1); if (sub.equals("length")) retval = new Argument(getCurrentContext().getPathLength()); else if (sub.equals("area")) retval = new Argument(getCurrentContext().getPathArea()); else if (sub.equals("centroid.x")) retval = new Argument(getCurrentContext().getPathCentroid().getX()); else if (sub.equals("centroid.y")) retval = new Argument(getCurrentContext().getPathCentroid().getY()); else if (sub.equals("start.x")) retval = new Argument(getCurrentContext().getPathStartPoint().getX()); else if (sub.equals("start.y")) retval = new Argument(getCurrentContext().getPathStartPoint().getY()); else if (sub.equals("end.x")) retval = new Argument(getCurrentContext().getPathEndPoint().getX()); else if (sub.equals("end.y")) retval = new Argument(getCurrentContext().getPathEndPoint().getY()); else if (sub.equals("start.angle")) { double radians = getCurrentContext().getPathStartAngle(); retval = new Argument(Math.toDegrees(radians)); } else if (sub.equals("end.angle")) { double radians = getCurrentContext().getPathEndAngle(); retval = new Argument(Math.toDegrees(radians)); } else { bounds = getCurrentContext().getBounds2D(); retval = getBoundingBoxVariable(sub, bounds); } } else if (varName.equals(INTERNAL_VARIABLE_PREFIX + PATH_VARIABLE)) { retval = getCurrentContext().getPathArgument(); } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + WORLDS_VARIABLE + ".")) { bounds = getCurrentContext().getWorldExtents(); sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + WORLDS_VARIABLE.length() + 1); if (sub.equals("scale")) { retval = new Argument(getCurrentContext().getWorldScale()); } else { retval = getBoundingBoxVariable(sub, bounds); } } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + DATASET_VARIABLE + ".")) { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) { /* * None of these variables are meaningful if there is * no dataset defined. */ retval = Argument.emptyString; } else { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + DATASET_VARIABLE.length() + 1); if (sub.equals("projection")) { String projection = dataset.getProjection(); if (projection == null) retval = Argument.emptyString; else retval = new Argument(Argument.STRING, projection); } else if (sub.equals("fieldnames")) { String []fieldNames = dataset.getFieldNames(); retval = new Argument(); for (i = 0; i < fieldNames.length; i++) { retval.addHashMapEntry(String.valueOf(i + 1), new Argument(Argument.STRING, fieldNames[i])); } } else { Rectangle2D.Double worlds; worlds = dataset.getWorlds(); retval = getBoundingBoxVariable(sub, worlds); } } } else if (varName.equals(INTERNAL_VARIABLE_PREFIX + IMAGEMAP_VARIABLE + ".x")) { if (m_imagemapPoint == null) retval = Argument.numericMinusOne; else retval = new Argument(m_imagemapPoint.x); } else if (varName.equals(INTERNAL_VARIABLE_PREFIX + IMAGEMAP_VARIABLE + ".y")) { if (m_imagemapPoint == null) retval = Argument.numericMinusOne; else retval = new Argument(m_imagemapPoint.y); } } else { Context context = (Context)(m_stack.getLast()); if (m_stack.size() > 1 && context.hasLocalScope(varName)) { /* * Lookup local variable in current context. */ retval = context.getVariableValue(varName); } else { /* * Variable not defined in current context, is * it set as a global in the first context instead? */ context = (Context)(m_stack.getFirst()); retval = context.getVariableValue(varName); String property = null; try { if (retval == null) { try { /* * Variable not defined by user. Is it set * as a system property or in environment? */ property = System.getProperty(varName); } catch (SecurityException e) { /* * We cannot access variable as a property so * consider it to be undefined. */ } try { if (property == null) property = System.getenv(varName); } catch (SecurityException e) { /* * We cannot access variable from environment so * consider it to be undefined. */ } if (property != null) { /* * Try to convert it to a number. */ d = Double.parseDouble(property); retval = new Argument(d); } } } catch (NumberFormatException e) { /* * System property was found but it is a * string, not a number. */ retval = new Argument(Argument.STRING, property); } } } return(retval); } /** * Indicates that a variable in the current context is to have local scope, * defined in current context only and not accessible by any other context. * @param varName name of variable to be treated as global */ public void setLocalScope(String varName) throws MapyrusException { getCurrentContext().setLocalScope(varName); } /** * Define a variable in context, * replacing any existing variable of the same name. * @param varName name of variable to define. * @param value is value for this variable */ public void defineVariable(String varName, Argument value) { Context currentContext = getCurrentContext(); Context c; /* * Define variable in first (global) context * unless defined local. */ if (currentContext.hasLocalScope(varName)) c = currentContext; else c = (Context)(m_stack.getFirst()); c.defineVariable(varName, value); } /** * Define an key-value entry in a hashmap in context, * replacing any existing entry with the same key. * @param hashMapName name of hashmap to add entry to. * @param key is key to add. * @param value is value to add. */ public void defineHashMapEntry(String hashMapName, String key, Argument value) { Context currentContext = getCurrentContext(); Context c; /* * Define variable in first (global) context * unless defined local. */ if (currentContext.hasLocalScope(hashMapName)) c = currentContext; else c = (Context)(m_stack.getFirst()); c.defineHashMapEntry(hashMapName, key, value); } /** * Add entry for a legend. * @param description description text for legend entry. * @param type legend type LegendEntryList.(POINT|LINE|BOX)_ENTRY. * @param legendArgs arguments to procedure block when creating legend. * @param legendArgIndex start index for legendArgs argument. * @param nLegendArgs is number of arguments to procedure block. */ public void addLegendEntry(String description, int type, Argument []legendArgs, int legendArgIndex, int nLegendArgs) { String blockName = getCurrentContext().getBlockName(); /* * Ignore legend entries defined outside of a procedure block. */ if (blockName != null) { m_legendEntries.add(blockName, legendArgs, legendArgIndex, nLegendArgs, type, description); } } /** * Return list of procedures for which legend entries are to be drawn. * @return legend entry list. */ public LegendEntryList getLegendEntries() { return(m_legendEntries); } /** * Set HTTP header to return for current HTTP request. * @param response HTTP header to return. */ public void setHTTPReponse(String response) { m_HTTPResponse = response; } /** * Get HTTP header to return for current HTTP request. * @return HTTP header. */ public String getHTTPResponse() { return(m_HTTPResponse); } /** * Save current context so that it can be restored later with restoreState. * @param name of procedure block that saved state will run. */ public void saveState(String blockName) throws MapyrusException { pushContext(blockName); } /** * Restore context to state before saveState was called. */ public void restoreState() throws IOException, MapyrusException { popContext(); } /** * Pops all contexts from stack that were pushed with saveState. * A ContextStack cannot be used again after this call. */ public void closeContextStack() throws IOException, MapyrusException { int nContexts = 0; try { do { nContexts = popContext(); } while (nContexts > 0); } catch (IOException e) { /* * Force all remaining contexts to be closed too. */ do { try { nContexts = popContext(); } catch (IOException e1) { } catch (MapyrusException e2) { } } while (nContexts > 0); throw e; } catch (MapyrusException e) { /* * Force all remaining contexts to be closed too. */ do { try { nContexts = popContext(); } catch (IOException e1) { } catch (MapyrusException e2) { } } while (nContexts > 0); throw e; } } }
src/org/mapyrus/ContextStack.java
/* * This file is part of Mapyrus, software for plotting maps. * Copyright (C) 2003 - 2010 Simon Chenery. * * Mapyrus is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Mapyrus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Mapyrus; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * @(#) $Id$ */ package org.mapyrus; import java.awt.Color; import java.awt.Point; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedList; import org.mapyrus.dataset.DatasetFactory; import org.mapyrus.dataset.GeographicDataset; import org.mapyrus.font.StringDimension; import org.mapyrus.image.Bitmap; import org.mapyrus.image.ImageIOWrapper; /** * Contexts for interpretation that are pushed and popped as procedure * blocks are called and return so that changes in a procedure block * are local to that block. */ public class ContextStack { /* * Maximum allowed stacking of contexts. * Any deeper is probably infinite recursion. */ private static final int MAX_STACK_LENGTH = 30; /* * Prefix for internal variables. */ private static final String INTERNAL_VARIABLE_PREFIX = Constants.PROGRAM_NAME + "."; /* * Internal variable names. */ private static final String PATH_VARIABLE = "path"; private static final String WORLDS_VARIABLE = "worlds"; private static final String DATASET_VARIABLE = "dataset"; private static final String PAGE_VARIABLE = "page"; private static final String SCREEN_VARIABLE = "screen"; private static final String IMAGEMAP_VARIABLE = "imagemap"; /* * Stack of contexts, with current context in last slot. */ private LinkedList<Context> m_stack; /* * List of legend keys encountered whilst interpreting statements. */ private LegendEntryList m_legendEntries; /* * Cache of icons we've already used and are likely to use again. */ private LRUCache<String, BufferedImage> m_iconCache; /* * Time at which this context was allocated. */ private long m_startTime; /* * Point clicked in HTML imagemap and passed in HTTP request we are processing. */ private Point m_imagemapPoint; /* * HTTP header to return to HTTP client. */ private String m_HTTPResponse; /** * Create new stack of contexts to manage state as procedure blocks * are called. */ public ContextStack() { m_stack = new LinkedList<Context>(); m_stack.add(new Context()); m_startTime = System.currentTimeMillis(); m_imagemapPoint = null; m_legendEntries = new LegendEntryList(); m_iconCache = new LRUCache<String, BufferedImage>(Constants.ICON_CACHE_SIZE); m_HTTPResponse = HTTPRequest.HTTP_OK_KEYWORD + Constants.LINE_SEPARATOR + HTTPRequest.CONTENT_TYPE_KEYWORD + ": " + MimeTypes.get("html") + Constants.LINE_SEPARATOR; } /** * Get current context from top of stack. * @return current context. */ private Context getCurrentContext() { return((Context)m_stack.getLast()); } /** * Pops current context from stack. * @return number of elements left in stack after pop. */ private int popContext() throws IOException, MapyrusException { int i = m_stack.size(); if (i > 0) { /* * Finish off current context, remove it from stack. */ Context context = (Context)m_stack.removeLast(); i--; int attributesSet = context.closeContext(); /* * If graphics attributes were set in context then set them changed * in the context that is now current so they are set again * here before being used. */ if (i > 0 && attributesSet != 0) getCurrentContext().setAttributesChanged(attributesSet); } return(i); } /** * Pushes copy of context at top of stack onto stack. * This context is later removed with popContext(). * @param blockName is procedure block name containing statements to be executed. */ private void pushContext(String blockName) throws MapyrusException { if (m_stack.size() == MAX_STACK_LENGTH) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.RECURSION)); } m_stack.add(new Context(getCurrentContext(), blockName)); } /** * Set point passed in HTML imagemap request. * @param pt pixel position clicked in image. */ public void setImagemapPoint(Point pt) { m_imagemapPoint = pt; } /** * Sets output file for drawing to. * @param filename name of image file output will be saved to * @param format is image format for saved output * @param width is the page width (in mm). * @param height is the page height (in mm). * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public void setOutputFormat(String format, String filename, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { getCurrentContext().setOutputFormat(format, filename, width, height, extras, stdoutStream); } /** * Sets image for drawing to. * @param image is buffered image to draw into. * @param imageMapWriter is HTML image map to write to. * @param extras contains extra settings for this output. */ public void setOutputFormat(BufferedImage image, PrintWriter imageMapWriter, String extras) throws IOException, MapyrusException { getCurrentContext().setOutputFormat(image, imageMapWriter, extras); } /** * Sets image for drawing to. * @param image is buffered image to draw into. * @param extras contains extra settings for this output. */ public void setOutputFormat(BufferedImage image, String extras) throws IOException, MapyrusException { getCurrentContext().setOutputFormat(image, extras); } /** * Close any open output file being created. */ public void closeOutputFormat() throws IOException, MapyrusException { getCurrentContext().closeOutputFormat(); } /** * Sets linestyle. * @param width is width for lines in millimetres. * @param cap is a BasicStroke end cap value. * @param join is a BasicStroke line join value. * @param phase is offset at which pattern is started. * @param dashes list of dash pattern lengths. */ public void setLinestyle(double width, int cap, int join, double phase, float []dashes) { getCurrentContext().setLinestyle(width, cap, join, phase, dashes); } /** * Sets color. * @param c is new color for drawing. */ public void setColor(Color c) { getCurrentContext().setColor(c); } /** * Sets transparent color blend mode. * @param blend is blend mode. */ public void setBlend(String blend) { getCurrentContext().setBlend(blend); } /** * Get current color. * @return current color. */ public Color getColor() { Color retval = getCurrentContext().getColor(); return(retval); } /** * Sets font for labelling with. * @param name is name of font. * @param size is size for labelling in millimetres. * @param outlineWidth if non-zero, gives line width to use for drawing * outline of each character of labels. * @param lineSpacing spacing between lines in multi-line labels, as * a multiple of the font size. */ public void setFont(String name, double size, double outlineWidth, double lineSpacing) { getCurrentContext().setFont(name, size, outlineWidth, lineSpacing); } /** * Sets horizontal and vertical justification for labelling. * @param code is bit flags of Context.JUSTIFY_* values for justification. */ public void setJustify(int code) { getCurrentContext().setJustify(code); } /** * Sets scaling for subsequent coordinates. * @param factor is new scaling in X and Y axes. */ public void setScaling(double factor) throws MapyrusException { if (factor == 0.0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_SCALING)); else if (factor != 1.0) getCurrentContext().setScaling(factor); } /** * Sets translation for subsequent coordinates. * @param x is new point for origin on X axis. * @param y is new point for origin on Y axis. */ public void setTranslation(double x, double y) { if (x != 0.0 || y != 0.0) getCurrentContext().setTranslation(x, y); } /** * Sets rotation for subsequent coordinates. * @param angle is rotation angle in radians, going anti-clockwise. */ public void setRotation(double angle) { if (angle != 0.0) getCurrentContext().setRotation(angle); } /** * Sets transformation from real world coordinates to page coordinates. * @param wx1 minimum X world coordinate. * @param wy1 minimum Y world coordinate. * @param wx2 maximum X world coordinate. * @param wy2 maximum Y world coordinate. * @param px1 millimetre position on page of wx1. * @param py1 millimetre position on page of wy1. * @param px2 millimetre position on page of wx2, or 0 to use whole page. * @param py2 millimetre position on page of wy2, or 0 to use whole page. * @param units units of world coordinates (WORLD_UNITS_METRES,WORLD_UNITS_FEET, etc.) * @param allowDistortion if true then different scaling in X and Y axes allowed. */ public void setWorlds(double wx1, double wy1, double wx2, double wy2, double px1, double py1, double px2, double py2, int units, boolean allowDistortion) throws MapyrusException { getCurrentContext().setWorlds(wx1, wy1, wx2, wy2, px1, py1, px2, py2, units, allowDistortion); } /** * Transform geometry from page coordinates to world coordinates. * @param arg geometry. * @return transformed geometry. */ public Argument transformToWorlds(Argument arg) throws MapyrusException { Argument retval = getCurrentContext().transformToWorlds(arg); return(retval); } /** * Transform geometry from world coordinates to page coordinates. * @param arg geometry. * @return transformed geometry. */ public Argument transformToPage(Argument arg) throws MapyrusException { Argument retval = getCurrentContext().transformToPage(arg); return(retval); } /** * Sets dataset to read from. * @param type is format of dataset, for example, "text". * @param name is name of dataset to open. * @param extras are special options for this dataset type such as database * connection information, or instructions for interpreting data. * @param stdin standard ihput stream of interpreter. */ public void setDataset(String type, String name, String extras, InputStream stdin) throws MapyrusException { GeographicDataset dataset; dataset = DatasetFactory.open(type, name, extras, stdin); getCurrentContext().setDataset(dataset); } /** * Sets file for writing standard output to. * File will automatically be closed when this context is closed. * @param stdout stream to write to. */ public void setStdout(PrintStream stdout) throws IOException { getCurrentContext().setStdout(stdout); } /** * Add point to path. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void moveTo(double x, double y) throws MapyrusException { getCurrentContext().moveTo(x, y); } /** * Add point to path with straight line segment from last point. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void lineTo(double x, double y) throws MapyrusException { getCurrentContext().lineTo(x, y); } /** * Add point to path with straight line segment relative to last point. * @param x X coordinate distance to move, relative to last point. * @param y Y coordinate distance to move, relative to last point. */ public void rlineTo(double x, double y) throws MapyrusException { getCurrentContext().rlineTo(x, y); } /** * Add circular arc to path from last point to a new point, given centre and direction. * @param direction positive for clockwise, negative for anti-clockwise. * @param xCentre X coordinate of centre point of arc. * @param yCentre Y coordinate of centre point of arc. * @param xEnd X coordinate of end point of arc. * @param yEnd Y coordinate of end point of arc. */ public void arcTo(int direction, double xCentre, double yCentre, double xEnd, double yEnd) throws MapyrusException { getCurrentContext().arcTo(direction, xCentre, yCentre, xEnd, yEnd); } /** * Add Bezier curve to path from last point to a new point. * @param xControl1 X coordinate of first Bezier control point. * @param yControl1 Y coordinate of first Bezier control point. * @param xControl2 X coordinate of second Bezier control point. * @param yControl2 Y coordinate of second Bezier control point. * @param xEnd X coordinate of end point of curve. * @param yEnd Y coordinate of end point of curve. */ public void curveTo(double xControl1, double yControl1, double xControl2, double yControl2, double xEnd, double yEnd) throws MapyrusException { getCurrentContext().curveTo(xControl1, yControl1, xControl2, yControl2, xEnd, yEnd); } /** * Add Sine wave curve to path from last point to a new point. * @param x X coordinate of end of path. * @param y Y coordinate of end of path. * @param nRepeats number of repeats of sine wave pattern. * @param amplitude scaling factor for height of sine wave. */ public void sineWaveTo(double x, double y, double nRepeats, double amplitude) throws MapyrusException { getCurrentContext().sineWaveTo(x,y, nRepeats, amplitude); } /** * Adds ellipse to path. * @param xMin minimum X coordinate of rectangle containing ellipse. * @param yMin minimum Y coordinate of rectangle containing ellipse. * @param xMax maximum X coordinate of rectangle containing ellipse. * @param yMax maximum Y coordinate of rectangle containing ellipse. */ public void ellipseTo(double xMin, double yMin, double xMax, double yMax) throws MapyrusException { getCurrentContext().ellipseTo(xMin, yMin, xMax, yMax); } /** * Resets path to empty. */ public void clearPath() { getCurrentContext().clearPath(); } /** * Closes path back to last moveTo point. */ public void closePath() { getCurrentContext().closePath(); } /** * Draws icon on page. * @param filename file containing icon. * @param size size for icon on page in millimetres. */ public void drawIcon(String filename, double size) throws IOException, MapyrusException { BufferedImage icon; boolean isDigits = false; boolean isResource = false; int digitsType = 0; /* * Have we opened icon before and cached it? */ icon = (BufferedImage)m_iconCache.get(filename); if (icon == null) { URL url; /* * Check if icon is "inlined" as hex or binary digits. */ if (filename.length() >= 3) { char c1 = filename.charAt(0); char c2 = Character.toLowerCase(filename.charAt(1)); if (c1 == '#') { isDigits = true; digitsType = Bitmap.HEX_DIGIT_BITMAP; } else if (c1 == '0' && c2 == 'x') { isDigits = true; digitsType = Bitmap.HEX_DIGIT_BITMAP; } else if ((c1 == '0' || c1 == '1') && (c2 == '0' || c2 == '1')) { isDigits = true; digitsType = Bitmap.BINARY_DIGIT_BITMAP; } else if (filename.startsWith("resource:")) { isResource = true; filename = filename.substring(9); } } if (isDigits) { Bitmap bitmap = new Bitmap(filename, digitsType, getCurrentContext().getColor()); icon = bitmap.getBufferedImage(); } else { /* * Load icon from either as a resource from a JAR file, * a URL, or as a plain file. */ try { if (isResource) { ClassLoader loader = this.getClass().getClassLoader(); url = loader.getResource(filename); } else { url = new URL(filename); } icon = ImageIOWrapper.read(url, getCurrentContext().getColor()); } catch (MalformedURLException e) { icon = ImageIOWrapper.read(new File(filename), getCurrentContext().getColor()); } if (icon == null) { throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_FORMAT) + ": " + filename); } } /* * Do not cache large icons, load them each time they are needed. * Do not cache an icon given as hex digits as we may want * it in a different color next time. */ if ((!isDigits) && icon.getHeight() * icon.getWidth() <= 128 * 128) m_iconCache.put(filename, icon); } getCurrentContext().drawIcon(icon, size); } /** * Draws geo-referenced image on page. * @param filename geo-referenced image filename. * @param extras extra parameters to control display of image. */ public void drawGeoImage(String filename, String extras) throws IOException, MapyrusException { getCurrentContext().drawGeoImage(filename, extras); } /** * Includes Encsapsulated PostScript file in page. * @param EPS filename. * @param size size for EPS file on page in millimetres. */ public void drawEPS(String filename, double size) throws IOException, MapyrusException { getCurrentContext().drawEPS(filename, size); } /** * Includes Scalable Vector Graphics file in page. * @param SVG filename. * @param size size for SVG file on page in millimetres. */ public void drawSVG(String filename, double size) throws IOException, MapyrusException { getCurrentContext().drawSVG(filename, size); } /** * Add Scalable Vector Graphics code to page. * @param xml XML elements to add to SVG file. */ public void addSVGCode(String xml) throws IOException, MapyrusException { getCurrentContext().addSVGCode(xml); } /** * Includes PDF file in page. * @param PDF filename. * @param page page number in PDF file to display. * @param size size for PDF file on page in millimetres. */ public void drawPDF(String filename, int page, double size) throws IOException, MapyrusException { getCurrentContext().drawPDF(filename, page, size); } /** * Replace path with regularly spaced points along it. * @param spacing is distance between points. * @param offset is starting offset of first point. */ public void samplePath(double spacing, double offset) throws MapyrusException { getCurrentContext().samplePath(spacing, offset); } /** * Replace path defining polygon with parallel stripe * lines covering the polygon. * @param spacing is distance between stripes. * @param angle is angle of stripes, in radians, with zero horizontal. */ public void stripePath(double spacing, double angle) { getCurrentContext().stripePath(spacing, angle); } /** * Shift all coordinates in path shifted by a fixed amount. * @param xShift distance in millimetres to shift X coordinate values. * @param yShift distance in millimetres to shift Y coordinate values. */ public void translatePath(double xShift, double yShift) { getCurrentContext().translatePath(xShift, yShift); } /** * Replace path with new paths at parallel distances to original path. * @param distances list of parallel distances for new paths. */ public void parallelPath(double []distances) throws MapyrusException { getCurrentContext().parallelPath(distances); } /** * Replace path with selected parts of path. * @param offsets offset along original path to select. * @param lengths length of original path to select at each offset. */ public void selectPath(double []offsets, double []lengths) throws MapyrusException { getCurrentContext().selectPath(offsets, lengths); } /** * Reverse direction of path. */ public void reversePath() throws MapyrusException { getCurrentContext().reversePath(); } /** * Replace path defining polygon with a sinkhole point. */ public void createSinkhole() { getCurrentContext().createSinkhole(); } /** * Replace path with path cut to rectangle defined by (x1, y1) and (x2, y2). * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. */ public void guillotine(double x1, double y1, double x2, double y2) throws MapyrusException { getCurrentContext().guillotine(x1, y1, x2, y2); } /** * Mark rectangular area on page (x1, y1) and (x2, y2) as protected. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. */ public void protect(double x1, double y1, double x2, double y2) throws MapyrusException { getCurrentContext().setPageMask(x1, y1, x2, y2, 1); } /** * Mark area on page as protected. * @param geometry area on page to protect. */ public void protect(Argument geometry) throws MapyrusException { getCurrentContext().setPageMask(geometry, 1); } /** * Mark area on page covered by current path as protected. */ public void protect() throws MapyrusException { getCurrentContext().setPageMask(1); } /** * Mark rectangular area on page (x1, y1) and (x2, y2) as unprotected. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. */ public void unprotect(double x1, double y1, double x2, double y2) throws MapyrusException { getCurrentContext().setPageMask(x1, y1, x2, y2, 0); } /** * Mark area on page as unprotected. * @param geometry area on page to unprotect. */ public void unprotect(Argument geometry) throws MapyrusException { getCurrentContext().setPageMask(geometry, 0); } /** * Mark area on page covered by current path as unprotected. */ public void unprotect() throws MapyrusException { getCurrentContext().setPageMask(0); } /** * Determine whether part of a rectangular area of page is protected. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. * @return true if part of this rectangular region is protected. */ public boolean isProtected(double x1, double y1, double x2, double y2) throws MapyrusException { boolean isZero = getCurrentContext().isPageMaskAllZero(x1, y1, x2, y2); return(!isZero); } /** * Determine whether a part of the page is protected. * @param geometry area to check. * @return true if any part of this region is protected. */ public boolean isProtected(Argument geometry) throws MapyrusException { boolean isZero = getCurrentContext().isPageMaskAllZero(geometry); return(!isZero); } /** * Determine whether a part of the page covered by current path is protected. * @return true if any part of path is protected. */ public boolean isProtected() throws MapyrusException { boolean isZero = getCurrentContext().isPageMaskAllZero(); return(!isZero); } /** * Draw currently defined path. * @param xmlAttributes XML attributes to add for SVG output. */ public void stroke(String xmlAttributes) throws IOException, MapyrusException { getCurrentContext().stroke(xmlAttributes); } /** * Fill currently defined path. * @param xmlAttribtes XML attributes to add for SVG output. */ public void fill(String xmlAttributes) throws IOException, MapyrusException { getCurrentContext().fill(xmlAttributes); } /** * Gradient fill current path. Colors at each of the four corners * of the path are defined. Colors will gradually fade * through the area covered by the path to give a smooth change * of color. * @param c1 color for lower left corner of path. * @param c2 color for lower right corner of path. * @param c3 color for upper left corner of path. * @param c4 color for upper right corner of path. * @param c5 color in center of path. */ public void gradientFill(Color c1, Color c2, Color c3, Color c4, Color c5) throws IOException, MapyrusException { getCurrentContext().gradientFill(c1, c2, c3, c4, c5); } /** * Set event script for currently defined path. * @param script commands to run for currently defined path. */ public void setEventScript(String script) throws IOException, MapyrusException { getCurrentContext().setEventScript(script); } /** * Clip to show only area outside currently defined path, * protecting what is inside path. */ public void clipOutside() throws MapyrusException { getCurrentContext().clipOutside(); } /** * Clip to show only area inside currently defined path. */ public void clipInside() { getCurrentContext().clipInside(); } /** * Draw label positioned at current point. * @param label label to draw. */ public void label(String label) throws IOException, MapyrusException { getCurrentContext().label(label); } /** * Draw label along currently defined path. * @param spacing spacing between letters. * @param offset offset along path at which to begin label. * @param label label to draw. */ public void flowLabel(double spacing, double offset, String label) throws IOException, MapyrusException { getCurrentContext().flowLabel(spacing, offset, label); } /** * Draw a table (a grid with a value in each cell) at current path position. * @param extras options for table. * @param list of arrays giving values in each column. */ public void drawTable(String extras, ArrayList columns) throws IOException, MapyrusException { getCurrentContext().drawTable(extras, columns); } /** * Draw a tree of labels at current path position. * @param extras options for tree. * @param tree array argument with tree entries. */ public void drawTree(String extras, Argument tree) throws IOException, MapyrusException { getCurrentContext().drawTree(extras, tree); } /** * Returns the number of moveTo's in path defined in current context. * @return count of moveTo calls made. */ public int getMoveToCount() { int retval = getCurrentContext().getMoveToCount(); return(retval); } /** * Returns the number of lineTo's in path defined in current context. * @return count of lineTo calls made for this path. */ public int getLineToCount() { int retval = getCurrentContext().getLineToCount(); return(retval); } /** * Returns rotation angle for each moveTo point in current path. * @return list of rotation angles. */ public ArrayList getMoveToRotations() { return(getCurrentContext().getMoveToRotations()); } /** * Returns coordinates for each each moveTo point in current path * @return list of Point2D.Float objects. */ public ArrayList getMoveTos() throws MapyrusException { return(getCurrentContext().getMoveTos()); } /** * Returns height and width of a string, drawn to current page with current font. * @param s string to calculate dimensions for. * @return height and width of string in millimetres. */ public StringDimension getStringDimension(String s) throws MapyrusException { StringDimension retval; try { retval = getCurrentContext().getStringDimension(s, true); } catch (IOException e) { throw new MapyrusException(e.getMessage()); } return(retval); } /** * Get resolution of page. * @return page resolution in millimetres. */ public double getResolution() throws MapyrusException { double retval = getCurrentContext().getResolution(); return(retval); } /** * Return next row from dataset. * @return field values for next row. */ public Row fetchRow() throws MapyrusException { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_DATASET)); return(dataset.fetchRow()); } /** * Return names of fields in current dataset. * @return names of fields. */ public String []getDatasetFieldNames() throws MapyrusException { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_DATASET)); String []retval = dataset.getFieldNames(); return(retval); } /** * Get stream that standard output is currently being sent to. * @return standard output stream. */ public PrintStream getStdout() { return(getCurrentContext().getStdout()); } /** * Returns one component of a bounding box. * @param part the information to be taken from the bounding box, "min.x", "width", etc. * @param bounds the bounding box to be queried * @return part of the information from bounding box, or null if part is unknown. */ private Argument getBoundingBoxVariable(String part, Rectangle2D bounds) { Argument retval; if (bounds == null) retval = Argument.numericZero; else if (part.equals("min.x")) retval = new Argument(bounds.getMinX()); else if (part.equals("min.y")) retval = new Argument(bounds.getMinY()); else if (part.equals("max.x")) retval = new Argument(bounds.getMaxX()); else if (part.equals("max.y")) retval = new Argument(bounds.getMaxY()); else if (part.equals("center.x") || part.equals("centre.x")) retval = new Argument(bounds.getCenterX()); else if (part.equals("center.y") || part.equals("centre.y")) retval = new Argument(bounds.getCenterY()); else if (part.equals("width")) retval = new Argument(bounds.getWidth()); else if (part.equals("height")) retval = new Argument(bounds.getHeight()); else retval = null; return(retval); } /** * Create string argument from two digit number. * @param i number to create string from. * @return argument containing value i. */ private Argument setTwoDigitNumber(int i) { Argument retval; if (i >= 10) retval = new Argument(Argument.STRING, Integer.toString(i)); else retval = new Argument(Argument.STRING, "0" + Integer.toString(i)); return(retval); } /** * Returns value of a variable. * @param varName variable name to lookup. * @param interpreterFilename name of file being interpreted. * @return value of variable, or null if it is not defined. */ public Argument getVariableValue(String varName, String interpreterFilename) throws MapyrusException { Argument retval = null; String sub; char c; double d; int i; Rectangle2D bounds; if (varName.startsWith(INTERNAL_VARIABLE_PREFIX) && varName.length() > INTERNAL_VARIABLE_PREFIX.length() && (!varName.equals(HTTPRequest.HTTP_HEADER_ARRAY))) { c = varName.charAt(INTERNAL_VARIABLE_PREFIX.length()); /* * Return internal/system variable. */ if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "fetch.more")) { Dataset dataset = getCurrentContext().getDataset(); if (dataset != null && dataset.hasMoreRows()) retval = Argument.numericOne; else retval = Argument.numericZero; } else if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "fetch.count")) { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) retval = Argument.numericZero; else retval = new Argument(dataset.getFetchCount()); } else if (c == 't' && varName.equals(INTERNAL_VARIABLE_PREFIX + "timer")) { /* * The elapsed time in seconds since this context was created * at the beginning of interpreting a file. */ retval = new Argument((System.currentTimeMillis() - m_startTime) / 1000.0); } else if (c == 't' && varName.startsWith(INTERNAL_VARIABLE_PREFIX + "time.")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + "time.".length()); GregorianCalendar calendar = new GregorianCalendar(); if (sub.equals("hour")) retval = setTwoDigitNumber(calendar.get(Calendar.HOUR_OF_DAY)); else if (sub.equals("minute")) retval = setTwoDigitNumber(calendar.get(Calendar.MINUTE)); else if (sub.equals("second")) retval = setTwoDigitNumber(calendar.get(Calendar.SECOND)); else if (sub.equals("day")) retval = setTwoDigitNumber(calendar.get(Calendar.DAY_OF_MONTH)); else if (sub.equals("day.name")) { SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); retval = new Argument(Argument.STRING, sdf.format(calendar.getTime())); } else if (sub.equals("month")) retval = setTwoDigitNumber(calendar.get(Calendar.MONTH) + 1); else if (sub.equals("month.name")) { SimpleDateFormat sdf = new SimpleDateFormat("MMMM"); retval = new Argument(Argument.STRING, sdf.format(calendar.getTime())); } else if (sub.equals("week.of.year")) retval = new Argument(calendar.get(Calendar.WEEK_OF_YEAR)); else if (sub.equals("day.of.week")) { int dayOfWeek; /* * Convert Java Calendar values for days into values 1-7, * with Monday=1 like in cron(1) tasks. */ int cd = calendar.get(Calendar.DAY_OF_WEEK); if (cd == Calendar.MONDAY) dayOfWeek = 1; else if (cd == Calendar.TUESDAY) dayOfWeek = 2; else if (cd == Calendar.WEDNESDAY) dayOfWeek = 3; else if (cd == Calendar.THURSDAY) dayOfWeek = 4; else if (cd == Calendar.FRIDAY) dayOfWeek = 5; else if (cd == Calendar.SATURDAY) dayOfWeek = 6; else dayOfWeek = 7; retval = new Argument(dayOfWeek); } else if (sub.equals("year")) retval = new Argument(calendar.get(Calendar.YEAR)); else if (sub.equals("stamp")) retval = new Argument(Argument.STRING, calendar.getTime().toString()); else retval = null; } else if (c == 'v' && varName.equals(INTERNAL_VARIABLE_PREFIX + "version")) { retval = new Argument(Argument.STRING, Constants.getVersion()); } else if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "freeMemory")) { retval = new Argument(Runtime.getRuntime().freeMemory()); } else if (c == 't' && varName.equals(INTERNAL_VARIABLE_PREFIX + "totalMemory")) { retval = new Argument(Runtime.getRuntime().totalMemory()); } else if (c == 'f' && varName.equals(INTERNAL_VARIABLE_PREFIX + "filename")) { retval = new Argument(Argument.STRING, interpreterFilename); } else if (c == 'r' && varName.equals(INTERNAL_VARIABLE_PREFIX + "rotation")) { retval = new Argument(Math.toDegrees(getCurrentContext().getRotation())); } else if (c == 's' && varName.equals(INTERNAL_VARIABLE_PREFIX + "scale")) { retval = new Argument(getCurrentContext().getScaling()); } else if (c == 'k' && varName.equals(INTERNAL_VARIABLE_PREFIX + "key.count")) { retval = new Argument(m_legendEntries.size()); } else if (c == 'k' && varName.equals(INTERNAL_VARIABLE_PREFIX + "key.next")) { LegendEntry top = m_legendEntries.first(); if (top == null) retval = Argument.emptyString; else retval = new Argument(Argument.STRING, top.getBlockName()); } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + PAGE_VARIABLE + ".")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + PAGE_VARIABLE.length() + 1); if (sub.equals("width")) retval = new Argument(getCurrentContext().getPageWidth()); else if (sub.equals("height")) retval = new Argument(getCurrentContext().getPageHeight()); else if (sub.equals("format")) retval = new Argument(Argument.STRING, getCurrentContext().getPageFormat()); else if (sub.equals("resolution.mm")) retval = new Argument(getCurrentContext().getResolution()); else if (sub.equals("resolution.dpi")) { retval = new Argument(Constants.MM_PER_INCH / getCurrentContext().getResolution()); } else retval = null; } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + SCREEN_VARIABLE + ".")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + SCREEN_VARIABLE.length() + 1); if (sub.equals("width")) retval = new Argument(Constants.getScreenWidth()); else if (sub.equals("height")) retval = new Argument(Constants.getScreenHeight()); else if (sub.equals("resolution.dpi")) retval = new Argument(Constants.getScreenResolution()); else if (sub.equals("resolution.mm")) { retval = new Argument(Constants.MM_PER_INCH / Constants.getScreenResolution()); } else retval = null; } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + PATH_VARIABLE + ".")) { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + PATH_VARIABLE.length() + 1); if (sub.equals("length")) retval = new Argument(getCurrentContext().getPathLength()); else if (sub.equals("area")) retval = new Argument(getCurrentContext().getPathArea()); else if (sub.equals("centroid.x")) retval = new Argument(getCurrentContext().getPathCentroid().getX()); else if (sub.equals("centroid.y")) retval = new Argument(getCurrentContext().getPathCentroid().getY()); else if (sub.equals("start.x")) retval = new Argument(getCurrentContext().getPathStartPoint().getX()); else if (sub.equals("start.y")) retval = new Argument(getCurrentContext().getPathStartPoint().getY()); else if (sub.equals("end.x")) retval = new Argument(getCurrentContext().getPathEndPoint().getX()); else if (sub.equals("end.y")) retval = new Argument(getCurrentContext().getPathEndPoint().getY()); else if (sub.equals("start.angle")) { double radians = getCurrentContext().getPathStartAngle(); retval = new Argument(Math.toDegrees(radians)); } else if (sub.equals("end.angle")) { double radians = getCurrentContext().getPathEndAngle(); retval = new Argument(Math.toDegrees(radians)); } else { bounds = getCurrentContext().getBounds2D(); retval = getBoundingBoxVariable(sub, bounds); } } else if (varName.equals(INTERNAL_VARIABLE_PREFIX + PATH_VARIABLE)) { retval = getCurrentContext().getPathArgument(); } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + WORLDS_VARIABLE + ".")) { bounds = getCurrentContext().getWorldExtents(); sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + WORLDS_VARIABLE.length() + 1); if (sub.equals("scale")) { retval = new Argument(getCurrentContext().getWorldScale()); } else { retval = getBoundingBoxVariable(sub, bounds); } } else if (varName.startsWith(INTERNAL_VARIABLE_PREFIX + DATASET_VARIABLE + ".")) { Dataset dataset = getCurrentContext().getDataset(); if (dataset == null) { /* * None of these variables are meaningful if there is * no dataset defined. */ retval = Argument.emptyString; } else { sub = varName.substring(INTERNAL_VARIABLE_PREFIX.length() + DATASET_VARIABLE.length() + 1); if (sub.equals("projection")) { String projection = dataset.getProjection(); if (projection == null) retval = Argument.emptyString; else retval = new Argument(Argument.STRING, projection); } else if (sub.equals("fieldnames")) { String []fieldNames = dataset.getFieldNames(); retval = new Argument(); for (i = 0; i < fieldNames.length; i++) { retval.addHashMapEntry(String.valueOf(i + 1), new Argument(Argument.STRING, fieldNames[i])); } } else { Rectangle2D.Double worlds; worlds = dataset.getWorlds(); retval = getBoundingBoxVariable(sub, worlds); } } } else if (varName.equals(INTERNAL_VARIABLE_PREFIX + IMAGEMAP_VARIABLE + ".x")) { if (m_imagemapPoint == null) retval = Argument.numericMinusOne; else retval = new Argument(m_imagemapPoint.x); } else if (varName.equals(INTERNAL_VARIABLE_PREFIX + IMAGEMAP_VARIABLE + ".y")) { if (m_imagemapPoint == null) retval = Argument.numericMinusOne; else retval = new Argument(m_imagemapPoint.y); } } else { Context context = (Context)(m_stack.getLast()); if (m_stack.size() > 1 && context.hasLocalScope(varName)) { /* * Lookup local variable in current context. */ retval = context.getVariableValue(varName); } else { /* * Variable not defined in current context, is * it set as a global in the first context instead? */ context = (Context)(m_stack.getFirst()); retval = context.getVariableValue(varName); String property = null; try { if (retval == null) { try { /* * Variable not defined by user. Is it set * as a system property or in environment? */ property = System.getProperty(varName); } catch (SecurityException e) { /* * We cannot access variable as a property so * consider it to be undefined. */ } try { if (property == null) property = System.getenv(varName); } catch (SecurityException e) { /* * We cannot access variable from environment so * consider it to be undefined. */ } if (property != null) { /* * Try to convert it to a number. */ d = Double.parseDouble(property); retval = new Argument(d); } } } catch (NumberFormatException e) { /* * System property was found but it is a * string, not a number. */ retval = new Argument(Argument.STRING, property); } } } return(retval); } /** * Indicates that a variable in the current context is to have local scope, * defined in current context only and not accessible by any other context. * @param varName name of variable to be treated as global */ public void setLocalScope(String varName) throws MapyrusException { getCurrentContext().setLocalScope(varName); } /** * Define a variable in context, * replacing any existing variable of the same name. * @param varName name of variable to define. * @param value is value for this variable */ public void defineVariable(String varName, Argument value) { Context currentContext = getCurrentContext(); Context c; /* * Define variable in first (global) context * unless defined local. */ if (currentContext.hasLocalScope(varName)) c = currentContext; else c = (Context)(m_stack.getFirst()); c.defineVariable(varName, value); } /** * Define an key-value entry in a hashmap in context, * replacing any existing entry with the same key. * @param hashMapName name of hashmap to add entry to. * @param key is key to add. * @param value is value to add. */ public void defineHashMapEntry(String hashMapName, String key, Argument value) { Context currentContext = getCurrentContext(); Context c; /* * Define variable in first (global) context * unless defined local. */ if (currentContext.hasLocalScope(hashMapName)) c = currentContext; else c = (Context)(m_stack.getFirst()); c.defineHashMapEntry(hashMapName, key, value); } /** * Add entry for a legend. * @param description description text for legend entry. * @param type legend type LegendEntryList.(POINT|LINE|BOX)_ENTRY. * @param legendArgs arguments to procedure block when creating legend. * @param legendArgIndex start index for legendArgs argument. * @param nLegendArgs is number of arguments to procedure block. */ public void addLegendEntry(String description, int type, Argument []legendArgs, int legendArgIndex, int nLegendArgs) { String blockName = getCurrentContext().getBlockName(); /* * Ignore legend entries defined outside of a procedure block. */ if (blockName != null) { m_legendEntries.add(blockName, legendArgs, legendArgIndex, nLegendArgs, type, description); } } /** * Return list of procedures for which legend entries are to be drawn. * @return legend entry list. */ public LegendEntryList getLegendEntries() { return(m_legendEntries); } /** * Set HTTP header to return for current HTTP request. * @param response HTTP header to return. */ public void setHTTPReponse(String response) { m_HTTPResponse = response; } /** * Get HTTP header to return for current HTTP request. * @return HTTP header. */ public String getHTTPResponse() { return(m_HTTPResponse); } /** * Save current context so that it can be restored later with restoreState. * @param name of procedure block that saved state will run. */ public void saveState(String blockName) throws MapyrusException { pushContext(blockName); } /** * Restore context to state before saveState was called. */ public void restoreState() throws IOException, MapyrusException { popContext(); } /** * Pops all contexts from stack that were pushed with saveState. * A ContextStack cannot be used again after this call. */ public void closeContextStack() throws IOException, MapyrusException { int nContexts = 0; try { do { nContexts = popContext(); } while (nContexts > 0); } catch (IOException e) { /* * Force all remaining contexts to be closed too. */ do { try { nContexts = popContext(); } catch (IOException e1) { } catch (MapyrusException e2) { } } while (nContexts > 0); throw e; } catch (MapyrusException e) { /* * Force all remaining contexts to be closed too. */ do { try { nContexts = popContext(); } catch (IOException e1) { } catch (MapyrusException e2) { } } while (nContexts > 0); throw e; } } }
Add getWorlds().
src/org/mapyrus/ContextStack.java
Add getWorlds().
<ide><path>rc/org/mapyrus/ContextStack.java <ide> { <ide> getCurrentContext().setWorlds(wx1, wy1, wx2, wy2, px1, py1, px2, py2, <ide> units, allowDistortion); <add> } <add> <add> /** <add> * Gets real world coordinates of the page. <add> */ <add> public Rectangle2D.Double getWorlds() throws MapyrusException <add> { <add> Rectangle2D.Double retval = getCurrentContext().getWorldExtents(); <add> return(retval); <ide> } <ide> <ide> /**
Java
apache-2.0
c440c26a70c1ba57d4d1b636c746d8772d8af290
0
smgoller/geode,davinash/geode,masaki-yamakawa/geode,davebarnes97/geode,davinash/geode,masaki-yamakawa/geode,smgoller/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,davebarnes97/geode,davinash/geode,smgoller/geode,masaki-yamakawa/geode,smgoller/geode,jdeppe-pivotal/geode,davebarnes97/geode,davebarnes97/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,davinash/geode,davebarnes97/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,davebarnes97/geode,davinash/geode,smgoller/geode,davinash/geode,davinash/geode,jdeppe-pivotal/geode,smgoller/geode,smgoller/geode,davebarnes97/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.partitioned; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializable; import org.apache.geode.DataSerializer; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.InterestPolicy; import org.apache.geode.cache.LowMemoryException; import org.apache.geode.cache.Region; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.ProfileListener; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.BucketAdvisor; import org.apache.geode.internal.cache.BucketAdvisor.BucketProfile; import org.apache.geode.internal.cache.BucketAdvisor.ServerBucketProfile; import org.apache.geode.internal.cache.BucketPersistenceAdvisor; import org.apache.geode.internal.cache.BucketRegion; import org.apache.geode.internal.cache.BucketServerLocation66; import org.apache.geode.internal.cache.CacheDistributionAdvisor; import org.apache.geode.internal.cache.FixedPartitionAttributesImpl; import org.apache.geode.internal.cache.InternalRegionArguments; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.PartitionedRegionStats; import org.apache.geode.internal.cache.ProxyBucketRegion; import org.apache.geode.internal.cache.control.MemoryThresholds; import org.apache.geode.internal.cache.control.ResourceAdvisor; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LogMarker; public class RegionAdvisor extends CacheDistributionAdvisor { private static final Logger logger = LogService.getLogger(); /** * Number of threads allowed to concurrently volunteer for bucket primary. */ public static final short VOLUNTEERING_THREAD_COUNT = Integer .getInteger(DistributionConfig.GEMFIRE_PREFIX + "RegionAdvisor.volunteeringThreadCount", 1) .shortValue(); /** * Non-thread safe queue for volunteering for primary bucket. Each BucketAdvisor for this PR uses * this queue. The thread that uses this queue is a waiting pool thread. Any thread using this * queue must synchronize on this queue. */ private final Queue<Runnable> volunteeringQueue = new ConcurrentLinkedQueue<>(); /** * Semaphore with {@link #VOLUNTEERING_THREAD_COUNT} number of permits to control number of * threads volunteering for bucket primaries. */ private final Semaphore volunteeringSemaphore = new Semaphore(VOLUNTEERING_THREAD_COUNT); private volatile int lastActiveProfiles = 0; private volatile int numDataStores = 0; protected volatile ProxyBucketRegion[] buckets; private Queue<QueuedBucketProfile> preInitQueue; private final Object preInitQueueMonitor = new Object(); private ConcurrentHashMap<Integer, Set<ServerBucketProfile>> clientBucketProfilesMap; private RegionAdvisor(PartitionedRegion region) { super(region); synchronized (preInitQueueMonitor) { preInitQueue = new ConcurrentLinkedQueue<>(); } clientBucketProfilesMap = new ConcurrentHashMap<>(); } public static RegionAdvisor createRegionAdvisor(PartitionedRegion region) { RegionAdvisor advisor = new RegionAdvisor(region); advisor.initialize(); return advisor; } public PartitionedRegionStats getPartitionedRegionStats() { return getPartitionedRegion().getPrStats(); } public synchronized void initializeRegionAdvisor() { if (buckets != null) { return; } PartitionedRegion p = getPartitionedRegion(); int numBuckets = p.getAttributes().getPartitionAttributes().getTotalNumBuckets(); ProxyBucketRegion[] bucs = new ProxyBucketRegion[numBuckets]; InternalRegionArguments args = new InternalRegionArguments(); args.setPartitionedRegionAdvisor(this); for (int i = 0; i < bucs.length; i++) { bucs[i] = new ProxyBucketRegion(i, p, args); bucs[i].initialize(); } buckets = bucs; } /** * Process those profiles which were received during the initialization period. It is safe to * process these profiles potentially out of order due to the profiles version which is * established on the sender. */ public void processProfilesQueuedDuringInitialization() { synchronized (preInitQueueMonitor) { Iterator pi = preInitQueue.iterator(); boolean finishedInitQueue = false; try { while (pi.hasNext()) { Object o = pi.next(); QueuedBucketProfile qbp = (QueuedBucketProfile) o; if (!qbp.isRemoval) { if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "applying queued profile addition for bucket {}", qbp.bucketId); } getBucket(qbp.bucketId).getBucketAdvisor().putProfile(qbp.bucketProfile); } else if (qbp.memberDeparted || !getDistributionManager().isCurrentMember(qbp.memberId)) { boolean crashed; if (qbp.memberDeparted) { crashed = qbp.crashed; } else { // TODO not necessarily accurate, but how important is this? crashed = !stillInView(qbp.memberId); } if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "applying queued member departure for all buckets for {}", qbp.memberId); } for (ProxyBucketRegion bucket : buckets) { BucketAdvisor ba = bucket.getBucketAdvisor(); ba.removeId(qbp.memberId, crashed, qbp.destroyed, qbp.fromMembershipListener); } // for } else { // apply removal for member still in the view if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "applying queued profile removal for all buckets for {}", qbp.memberId); } for (int i = 0; i < buckets.length; i++) { BucketAdvisor ba = buckets[i].getBucketAdvisor(); int serial = qbp.serials[i]; if (serial != ILLEGAL_SERIAL) { ba.removeIdWithSerial(qbp.memberId, serial, qbp.destroyed); } } // for } // apply removal for member still in the view } // while finishedInitQueue = true; } finally { preInitQueue = null; // prevent further additions to the queue preInitQueueMonitor.notifyAll(); if (!finishedInitQueue && !getAdvisee().getCancelCriterion().isCancelInProgress()) { logger.error("Failed to process all queued BucketProfiles for {}", getAdvisee()); } } } } @Override protected Profile instantiateProfile(InternalDistributedMember memberId, int version) { return new PartitionProfile(memberId, version); } /** * Returns the {@link #volunteeringQueue} used to queue primary volunteering tasks by this PR's * BucketAdvisors. * * @return the volunteering queue for use by this PR's BucketAdvisors */ public Queue<Runnable> getVolunteeringQueue() { return volunteeringQueue; } /** * Returns the {@link #volunteeringSemaphore} for controlling the number of threads that this PR's * BucketAdvisors are allowed to use for volunteering to be primary. * * @return the semaphore for controlling number of volunteering threads */ public Semaphore getVolunteeringSemaphore() { return volunteeringSemaphore; } /** * Returns an unmodifiable map of bucket IDs to locations hosting the bucket. */ public Map<Integer, List<BucketServerLocation66>> getAllClientBucketProfiles() { Map<Integer, List<BucketServerLocation66>> bucketToServerLocations = new HashMap<>(); for (Integer bucketId : clientBucketProfilesMap.keySet()) { ArrayList<BucketServerLocation66> clientBucketProfiles = new ArrayList<>(); for (BucketProfile profile : clientBucketProfilesMap.get(bucketId)) { if (profile.isHosting) { ServerBucketProfile cProfile = (ServerBucketProfile) profile; Set<BucketServerLocation66> bucketServerLocations = cProfile.getBucketServerLocations(); // Either we can make BucketServeLocation having ServerLocation with them // Or we can create bucketServerLocation as it is by iterating over the set of servers clientBucketProfiles.addAll(bucketServerLocations); } } bucketToServerLocations.put(bucketId, clientBucketProfiles); } if (getPartitionedRegion().isDataStore()) { for (Integer bucketId : getPartitionedRegion().getDataStore().getAllLocalBucketIds()) { BucketProfile profile = getBucketAdvisor(bucketId).getLocalProfile(); if (logger.isDebugEnabled()) { logger.debug("The local profile is : {}", profile); } if (profile != null) { List<BucketServerLocation66> clientBucketProfiles = bucketToServerLocations.computeIfAbsent(bucketId, k -> new ArrayList<>()); if ((profile instanceof ServerBucketProfile) && profile.isHosting) { ServerBucketProfile cProfile = (ServerBucketProfile) profile; Set<BucketServerLocation66> bucketServerLocations = cProfile.getBucketServerLocations(); // Either we can make BucketServeLocation having ServerLocation with // them // Or we can create bucketServerLocation as it is by iterating over // the set of servers clientBucketProfiles.removeAll(bucketServerLocations); clientBucketProfiles.addAll(bucketServerLocations); } } } } return bucketToServerLocations; } public ConcurrentHashMap<Integer, Set<ServerBucketProfile>> getAllClientBucketProfilesTest() { ConcurrentHashMap<Integer, Set<ServerBucketProfile>> map = new ConcurrentHashMap<>(); Map<Integer, List<BucketServerLocation66>> testMap = new HashMap<>(getAllClientBucketProfiles()); for (Integer bucketId : testMap.keySet()) { Set<ServerBucketProfile> parr = new HashSet<>(clientBucketProfilesMap.get(bucketId)); map.put(bucketId, parr); } if (getPartitionedRegion().isDataStore()) { for (Integer bucketId : getPartitionedRegion().getDataStore().getAllLocalBucketIds()) { BucketProfile profile = getBucketAdvisor(bucketId).getLocalProfile(); if ((profile instanceof ServerBucketProfile) && profile.isHosting) { map.get(bucketId).add((ServerBucketProfile) profile); } } } if (logger.isDebugEnabled()) { logger.debug("This maps is sksk {} and size is {}", map, map.keySet().size()); } return map; } public Set<ServerBucketProfile> getClientBucketProfiles(Integer bucketId) { return clientBucketProfilesMap.get(bucketId); } public void setClientBucketProfiles(Integer bucketId, Set<ServerBucketProfile> profiles) { clientBucketProfilesMap.put(bucketId, Collections.unmodifiableSet(profiles)); } /** * Close the bucket advisors, releasing any locks for primary buckets */ public void closeBucketAdvisors() { if (buckets != null) { for (ProxyBucketRegion pbr : buckets) { pbr.close(); } } } /** * Close the adviser and all bucket advisors. */ @Override public void close() { super.close(); if (buckets != null) { for (ProxyBucketRegion bucket : buckets) { bucket.close(); } } } @Override public boolean removeId(ProfileId memberId, boolean crashed, boolean regionDestroyed, boolean fromMembershipListener) { // It's important that we remove member from the bucket advisors first // Calling super.removeId triggers redundancy satisfaction, so the bucket // advisors must have up to data information at that point. boolean removeBuckets = true; synchronized (preInitQueueMonitor) { if (preInitQueue != null) { // Queue profile during pre-initialization QueuedBucketProfile qbf = new QueuedBucketProfile((InternalDistributedMember) memberId, crashed, regionDestroyed, fromMembershipListener); preInitQueue.add(qbf); removeBuckets = false; } } // synchronized if (removeBuckets && buckets != null) { for (ProxyBucketRegion pbr : buckets) { BucketAdvisor pbra = pbr.getBucketAdvisor(); boolean shouldSync = false; Profile profile = null; InternalDistributedMember mbr = null; if (memberId instanceof InternalDistributedMember) { mbr = (InternalDistributedMember) memberId; shouldSync = pbra.shouldSyncForCrashedMember(mbr); if (shouldSync) { profile = pbr.getBucketAdvisor().getProfile(memberId); } } boolean removed = pbr.getBucketAdvisor().removeId(memberId, crashed, regionDestroyed, fromMembershipListener); if (removed && shouldSync) { pbra.syncForCrashedMember(mbr, profile); } } } boolean removedId; removedId = super.removeId(memberId, crashed, regionDestroyed, fromMembershipListener); if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeId: removing member from region {}: {}; removed = {}; crashed = {}", getPartitionedRegion().getName(), memberId, removedId, crashed); } return removedId; } /** * Clear the knowledge of given member from this advisor. In particular, clear the knowledge of * remote Bucket locations so that we avoid sending partition messages to buckets that will soon * be destroyed. * * @param memberId member that has closed the region * @param prSerial serial number of this partitioned region * @param serials serial numbers of buckets that need to be removed */ public void removeIdAndBuckets(InternalDistributedMember memberId, int prSerial, int[] serials, boolean regionDestroyed) { if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeIdAndBuckets: removing member from region {}: {}; buckets = ({}) serials", getPartitionedRegion().getName(), memberId, (serials == null ? "null" : serials.length)); } synchronized (preInitQueueMonitor) { if (preInitQueue != null) { // Queue profile during pre-initialization QueuedBucketProfile qbf = new QueuedBucketProfile(memberId, serials, regionDestroyed); preInitQueue.add(qbf); return; } } // OK, apply the update NOW if (buckets != null) { Objects.requireNonNull(serials); if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeIdAndBuckets: removing buckets for member{};{}", memberId, this); } for (int i = 0; i < buckets.length; i++) { int s = serials[i]; if (s != ILLEGAL_SERIAL) { if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeIdAndBuckets: removing bucket #{} serial {}", i, s); } buckets[i].getBucketAdvisor().removeIdWithSerial(memberId, s, regionDestroyed); } } super.removeIdWithSerial(memberId, prSerial, regionDestroyed); } } /** * Iterates over all buckets and marks them sick if the given member hosts the bucket. * * @param sick true if the bucket should be marked sick, false if healthy */ public void markBucketsOnMember(DistributedMember member, boolean sick) { // The health profile exchange at cache level should take care of preInitQueue if (buckets == null) { return; } for (int i = 0; i < buckets.length; i++) { if (sick && !buckets[i].getBucketOwners().contains(member)) { continue; } buckets[i].setBucketSick(member, sick); if (logger.isDebugEnabled()) { logger.debug("Marked bucket ({}) {}", getPartitionedRegion().bucketStringForLogs(i), (buckets[i].isBucketSick() ? "sick" : "healthy")); } } } public void updateBucketStatus(int bucketId, DistributedMember member, boolean profileRemoved) { if (profileRemoved) { buckets[bucketId].setBucketSick(member, false); } else { ResourceAdvisor advisor = getPartitionedRegion().getCache().getResourceAdvisor(); boolean sick = advisor.adviseCriticalMembers().contains(member); if (logger.isDebugEnabled()) { logger.debug("updateBucketStatus:({}):member:{}:sick:{}", getPartitionedRegion().bucketStringForLogs(bucketId), member, sick); } buckets[bucketId].setBucketSick(member, sick); } } /** * throws LowMemoryException if the given bucket is hosted on a member which has crossed the * ResourceManager threshold. * * @param key for bucketId used in exception */ public void checkIfBucketSick(final int bucketId, final Object key) throws LowMemoryException { if (MemoryThresholds.isLowMemoryExceptionDisabled()) { return; } if (buckets[bucketId].isBucketSick()) { Set<DistributedMember> sm = buckets[bucketId].getSickMembers(); if (sm.isEmpty()) { // check again as this list is obtained under synchronization // fixes bug 50845 return; } if (logger.isDebugEnabled()) { logger.debug("For bucket {} sick members are {}.", getPartitionedRegion().bucketStringForLogs(bucketId), sm); } throw new LowMemoryException(String.format( "PartitionedRegion: %s cannot process operation on key %s because members %s are running low on memory", getPartitionedRegion().getFullPath(), key, sm), sm); } } /** * Profile information for a remote counterpart. */ public static class PartitionProfile extends CacheProfile { /** * The number of Mb the VM is allowed to use for the PR * {@link PartitionedRegion#getLocalMaxMemory()} */ public int localMaxMemory; /** * A data store is a VM that has a non-zero local max memory, Since the localMaxMemory is * already sent, there is no need to send this state as it's implied in localMaxMemory */ public transient boolean isDataStore = false; /** * requiresNotification determines whether a member needs to be notified of cache operations so * that cache listeners and other hooks can be engaged * * @since GemFire 5.1 */ public boolean requiresNotification = false; /** * Track the number of buckets this data store may have, implies isDataStore == true This value * is NOT sent directly but updated when {@link org.apache.geode.internal.cache.BucketAdvisor}s * receive updates */ public transient short numBuckets = 0; /** * represents the list of the fixed partitions defined for this region. */ public List<FixedPartitionAttributesImpl> fixedPAttrs; // Indicate the status of shutdown request public int shutDownAllStatus = PartitionedRegion.RUNNING_MODE; /** for internal use, required for DataSerializer.readObject */ public PartitionProfile() {} public PartitionProfile(InternalDistributedMember memberId, int version) { super(memberId, version); isPartitioned = true; } @Override protected int getIntInfo() { int s = super.getIntInfo(); if (requiresNotification) s |= REQUIRES_NOTIFICATION_MASK; return s; } @Override protected void setIntInfo(int s) { super.setIntInfo(s); requiresNotification = (s & REQUIRES_NOTIFICATION_MASK) != 0; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); localMaxMemory = in.readInt(); isDataStore = localMaxMemory > 0; fixedPAttrs = DataSerializer.readObject(in); shutDownAllStatus = in.readInt(); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeInt(localMaxMemory); DataSerializer.writeObject(fixedPAttrs, out); out.writeInt(shutDownAllStatus); } @Override public StringBuilder getToStringHeader() { return new StringBuilder("RegionAdvisor.PartitionProfile"); } @Override public void fillInToString(StringBuilder sb) { super.fillInToString(sb); sb.append("; isDataStore=").append(isDataStore).append("; requiresNotification=") .append(requiresNotification).append("; localMaxMemory=").append(localMaxMemory) .append("; numBuckets=").append(numBuckets); if (fixedPAttrs != null) { sb.append("; FixedPartitionAttributes=").append(fixedPAttrs); } sb.append("; filterProfile=").append(filterProfile); sb.append("; shutDownAllStatus=").append(shutDownAllStatus); } @Override public int getDSFID() { return PARTITION_PROFILE; } } // end class PartitionProfile public int getNumDataStores() { final int numProfs = getNumProfiles(); if (lastActiveProfiles != numProfs) { numDataStores = adviseDataStore().size(); lastActiveProfiles = numProfs; } return numDataStores; } public Set<InternalDistributedMember> adviseDataStore() { return adviseDataStore(false); } /** * Returns the set of data stores that have finished initialization. */ public Set<InternalDistributedMember> adviseInitializedDataStore() { return adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; return p.isDataStore && (!p.dataPolicy.withPersistence() || p.regionInitialized); } return false; }); } /** * Returns the set of members that are not arrived at specified shutDownAll status */ private Set<InternalDistributedMember> adviseNotAtShutDownAllStatus(final int status) { return adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; return p.isDataStore && p.shutDownAllStatus < status; } return false; }); } public void waitForProfileStatus(int status) { ProfileShutdownListener listener = new ProfileShutdownListener(); addProfileChangeListener(listener); try { int memberNum; String regionName = getPartitionedRegion().getFullPath(); do { Region pr = getPartitionedRegion().getCache().getRegion(regionName); if (pr == null || pr.isDestroyed()) break; Set members = adviseNotAtShutDownAllStatus(status); memberNum = members.size(); if (memberNum > 0) { if (logger.isDebugEnabled()) { logger.debug("waitForProfileStatus {} at PR:{}, expecting {} members: {}", status, getPartitionedRegion().getFullPath(), memberNum, members); } listener.waitForChange(); } } while (memberNum > 0); } finally { removeProfileChangeListener(listener); } } /** * Return a real Set if set to true, which can be modified * * @param realHashSet true if a real set is needed * @return depending on the realHashSet value may be a HashSet */ public Set<InternalDistributedMember> adviseDataStore(boolean realHashSet) { Set<InternalDistributedMember> s = adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; return p.isDataStore; } return false; }); if (realHashSet) { if (s == Collections.EMPTY_SET) { s = new HashSet<>(); } } if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "adviseDataStore returning {} from {}", s, toStringWithProfiles()); } return s; } /** * return the set of the distributed members on which the given partition name is defined. * */ public Set<InternalDistributedMember> adviseFixedPartitionDataStores(final String partitionName) { Set<InternalDistributedMember> s = adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are // Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; if (p.fixedPAttrs != null) { for (FixedPartitionAttributesImpl fpa : p.fixedPAttrs) { if (fpa.getPartitionName().equals(partitionName)) { return true; } } } } return false; }); if (s == Collections.EMPTY_SET) { s = new HashSet<>(); } if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "adviseFixedPartitionDataStore returning {} from {}", s, toStringWithProfiles()); } return s; } /** * return a distributed members on which the primary partition for given bucket is defined * */ public InternalDistributedMember adviseFixedPrimaryPartitionDataStore(final int bucketId) { final List<InternalDistributedMember> fixedPartitionDataStore = new ArrayList<>(1); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; if (p.fixedPAttrs != null) { for (FixedPartitionAttributesImpl fpa : p.fixedPAttrs) { if (fpa.isPrimary() && fpa.hasBucket(bucketId)) { fixedPartitionDataStore.add(0, p.getDistributedMember()); return true; } } } } return false; }); if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "adviseFixedPartitionDataStore returning {} from {}", fixedPartitionDataStore, toStringWithProfiles()); } if (fixedPartitionDataStore.isEmpty()) { return null; } return fixedPartitionDataStore.get(0); } /** * Returns the list of all remote FixedPartitionAttributes defined across all members for the * given partitioned region * * @return list of all partitions(primary as well as secondary) defined on remote nodes */ public List<FixedPartitionAttributesImpl> adviseAllFixedPartitionAttributes() { final List<FixedPartitionAttributesImpl> allFPAs = new ArrayList<>(); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { final PartitionProfile pp = (PartitionProfile) profile; if (pp.fixedPAttrs != null) { allFPAs.addAll(pp.fixedPAttrs); return true; } } return false; }); return allFPAs; } /** * Returns the list of all FixedPartitionAttributes defined across all members of given * partitioned region for a given FixedPartitionAttributes * * @return the list of same partitions defined on other nodes(can be primary or secondary) */ public List<FixedPartitionAttributesImpl> adviseSameFPAs(final FixedPartitionAttributesImpl fpa) { final List<FixedPartitionAttributesImpl> sameFPAs = new ArrayList<>(); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { final PartitionProfile pp = (PartitionProfile) profile; List<FixedPartitionAttributesImpl> fpaList = pp.fixedPAttrs; if (fpaList != null) { int index = fpaList.indexOf(fpa); if (index != -1) { sameFPAs.add(fpaList.get(index)); } return true; } } return false; }); return sameFPAs; } /** * Returns the list of all remote primary FixedPartitionAttributes defined across members for the * given partitioned region * * @return list of all primary partitions defined on remote nodes */ public List<FixedPartitionAttributesImpl> adviseRemotePrimaryFPAs() { final List<FixedPartitionAttributesImpl> remotePrimaryFPAs = new ArrayList<>(); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { final PartitionProfile pp = (PartitionProfile) profile; List<FixedPartitionAttributesImpl> fpaList = pp.fixedPAttrs; if (fpaList != null) { for (FixedPartitionAttributesImpl fpa : fpaList) { if (fpa.isPrimary()) { remotePrimaryFPAs.add(fpa); return true; } } } } return false; }); return remotePrimaryFPAs; } public Set<InternalDistributedMember> adviseAllPRNodes() { return adviseFilter(profile -> { CacheProfile prof = (CacheProfile) profile; return prof.isPartitioned; }); } Set adviseAllServersWithInterest() { return adviseFilter(profile -> { CacheProfile prof = (CacheProfile) profile; return prof.hasCacheServer && prof.filterProfile != null && prof.filterProfile.hasInterest(); }); } @Immutable private static final Filter prServerWithInterestFilter = profile -> { CacheProfile prof = (CacheProfile) profile; return prof.isPartitioned && prof.hasCacheServer && prof.filterProfile != null && prof.filterProfile.hasInterest(); }; public boolean hasPRServerWithInterest() { return satisfiesFilter(prServerWithInterestFilter); } /** * return the set of all members who must receive operation notifications * * @since GemFire 5.1 */ public Set<InternalDistributedMember> adviseRequiresNotification() { return adviseFilter(profile -> { if (profile instanceof PartitionProfile) { PartitionProfile prof = (PartitionProfile) profile; if (prof.isPartitioned) { if (prof.hasCacheListener) { InterestPolicy pol = prof.subscriptionAttributes.getInterestPolicy(); if (pol == InterestPolicy.ALL) { return true; } } return prof.requiresNotification; } } return false; }); } @Override public synchronized boolean putProfile(Profile p) { CacheProfile profile = (CacheProfile) p; PartitionedRegion pr = getPartitionedRegion(); if (profile.hasCacheLoader) { pr.setHaveCacheLoader(); } // don't keep FilterProfiles around in accessors. They're needed only for // routing messages in data stors if (profile.filterProfile != null) { if (!pr.isDataStore()) { profile.filterProfile = null; } } return super.putProfile(profile); } public PartitionProfile getPartitionProfile(InternalDistributedMember id) { return (PartitionProfile) getProfile(id); } public boolean isPrimaryForBucket(int bucketId) { if (buckets == null) { return false; } return buckets[bucketId].isPrimary(); } /** * Returns true if the bucket is currently being hosted locally. Note that as soon as this call * returns, this datastore may begin to host the bucket, thus two calls in a row may be different. * * @param bucketId the index of the bucket to check * @return true if the bucket is currently being hosted locally */ public boolean isBucketLocal(int bucketId) { if (buckets == null) { return false; } return buckets[bucketId].getHostedBucketRegion() != null; } public boolean areBucketsInitialized() { return buckets != null; } /** * Returns the real BucketRegion if it's currently locally hosted. Otherwise the ProxyBucketRegion * is returned. Note that this member may be in the process of hosting the real bucket. Until that * has completed, getBucket will continue to return the ProxyBucketRegion. * * @param bucketId the index of the bucket to retrieve * @return the bucket identified by bucketId */ public Bucket getBucket(int bucketId) { ProxyBucketRegion pbr = buckets[bucketId]; Bucket ret = pbr.getHostedBucketRegion(); if (ret != null) { return ret; } else { return pbr; } } /** * Returns the BucketAdvisor for the specified bucket. * * @param bucketId the index of the bucket to retrieve the advisor for * @return the bucket advisor identified by bucketId */ public BucketAdvisor getBucketAdvisor(int bucketId) { ProxyBucketRegion pbr = buckets[bucketId]; Bucket ret = pbr.getHostedBucketRegion(); if (ret != null) { return ret.getBucketAdvisor(); } else { return pbr.getBucketAdvisor(); } } public Map<Integer, BucketAdvisor> getAllBucketAdvisors() { Map<Integer, BucketAdvisor> map = new HashMap<>(); for (ProxyBucketRegion pbr : buckets) { Bucket ret = pbr.getHostedBucketRegion(); if (ret != null) { map.put(ret.getId(), ret.getBucketAdvisor()); } } return map; } /** * * @return array of serial numbers for buckets created locally */ public int[] getBucketSerials() { if (buckets == null) { return new int[0]; } int[] result = new int[buckets.length]; for (int i = 0; i < result.length; i++) { ProxyBucketRegion pbr = buckets[i]; Bucket b = pbr.getCreatedBucketRegion(); if (b == null) { result[i] = ILLEGAL_SERIAL; } else { result[i] = b.getSerialNumber(); } } return result; } /** * Returns the bucket identified by bucketId after waiting for initialization to finish processing * queued profiles. Call synchronizes and waits on {@link #preInitQueueMonitor}. * * @param bucketId the bucket identifier * @return the bucket identified by bucketId * @throws org.apache.geode.distributed.DistributedSystemDisconnectedException if interrupted for * shutdown cancellation */ public Bucket getBucketPostInit(int bucketId) { synchronized (preInitQueueMonitor) { boolean interrupted = false; try { while (preInitQueue != null) { try { preInitQueueMonitor.wait(); // spurious wakeup ok } catch (InterruptedException e) { interrupted = true; getAdvisee().getCancelCriterion().checkCancelInProgress(e); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } return getBucket(bucketId); } /** * Get the most recent primary node for the bucketId. Returns null if no primary can be found * within {@link DistributionConfig#getMemberTimeout}. * * @return the Node managing the primary copy of the bucket */ public InternalDistributedMember getPrimaryMemberForBucket(int bucketId) { Bucket b = buckets[bucketId]; return b.getBucketAdvisor().getPrimary(); } /** * Return the node favored for reading for the given bucket * * @param bucketId the bucket we want to read * @return the member, possibly null if no member is available */ public InternalDistributedMember getPreferredNode(int bucketId) { Bucket b = buckets[bucketId]; return b.getBucketAdvisor().getPreferredNode(); } public boolean isStorageAssignedForBucket(int bucketId) { return buckets[bucketId].getBucketRedundancy() >= 0; } /** * @param bucketId the bucket to check redundancy on * @param minRedundancy the amount of expected redundancy; ignored if wait is false * @param wait true if caller wants us to wait for redundancy * @return true if redundancy on given bucket is detected */ public boolean isStorageAssignedForBucket(int bucketId, int minRedundancy, boolean wait) { if (!wait) { return isStorageAssignedForBucket(bucketId); } else { return buckets[bucketId].getBucketAdvisor().waitForRedundancy(minRedundancy); } } /** * Get the redundancy of the this bucket, taking into account the local bucket, if any. * * @return number of redundant copies for a given bucket, or -1 if there are no instances of the * bucket. */ public int getBucketRedundancy(int bucketId) { return buckets[bucketId].getBucketRedundancy(); } /** * Return the set of all members who currently own the bucket, including the local owner, if * applicable * * @return a set of {@link InternalDistributedMember}s that own the bucket */ public Set<InternalDistributedMember> getBucketOwners(int bucketId) { return buckets[bucketId].getBucketOwners(); } /** * Return the set of buckets which have storage assigned * * @return set of Integer bucketIds */ public Set<Integer> getBucketSet() { return new BucketSet(); } public ProxyBucketRegion[] getProxyBucketArray() { return buckets; } private class BucketSet extends AbstractSet<Integer> { final ProxyBucketRegion[] pbrs; BucketSet() { pbrs = buckets; } /* * Note: The consistency between size(), hasNext() and next() is weak, meaning that the state of * the backing Set may change causing more or less elements to be available after calling size() */ @Override public int size() { return pbrs.length; } @Override public Iterator<Integer> iterator() { return new BucketSetIterator(); } class BucketSetIterator implements Iterator<Integer> { private int currentItem = -1; @Override public void remove() { throw new UnsupportedOperationException(); } /* * Note: The consistency guarantee between hasNext() and next() is weak. It's possible * hasNext() will return true and a following call to next() may throw NoSuchElementException * (due to loss of bucket storage). Its also equally possible for hasNext() to return false * and a subsequent call to next() will return a valid bucketid. */ @Override public boolean hasNext() { if (getPartitionedRegion().isFixedPartitionedRegion()) { if (currentItem + 1 < pbrs.length) { int possibleBucketId = currentItem; boolean bucketExists = false; List<FixedPartitionAttributesImpl> fpaList = adviseAllFixedPartitionAttributes(); List<FixedPartitionAttributesImpl> localFpas = getPartitionedRegion().getFixedPartitionAttributesImpl(); if (localFpas != null) { fpaList.addAll(localFpas); } while (++possibleBucketId < pbrs.length && !bucketExists) { for (FixedPartitionAttributesImpl fpa : fpaList) { if (fpa.hasBucket(possibleBucketId)) { bucketExists = true; break; } } } return bucketExists; } else { return false; } } else { return currentItem + 1 < pbrs.length; } } @Override public Integer next() { if (++currentItem < pbrs.length) { if (isStorageAssignedForBucket(currentItem)) { return currentItem; } else { if (getPartitionedRegion().isFixedPartitionedRegion()) { boolean bucketExists = false; List<FixedPartitionAttributesImpl> fpaList = adviseAllFixedPartitionAttributes(); List<FixedPartitionAttributesImpl> localFpas = getPartitionedRegion().getFixedPartitionAttributesImpl(); if (localFpas != null) { fpaList.addAll(localFpas); } do { for (FixedPartitionAttributesImpl fpa : fpaList) { if (fpa.hasBucket(currentItem)) { bucketExists = true; break; } } if (!bucketExists) { currentItem++; } } while (currentItem < pbrs.length && !bucketExists); if (bucketExists) { getPartitionedRegion().createBucket(currentItem, 0, null); return currentItem; } } else { getPartitionedRegion().createBucket(currentItem, 0, null); return currentItem; } } } throw new NoSuchElementException(); } } } /** * Obtain the ordered {@link ArrayList} of data stores limited to those specified in the provided * memberFilter. * * @param memberFilter the set of members allowed to be in the list. * @return a list of DataStoreBuckets */ public ArrayList<DataStoreBuckets> adviseFilteredDataStores( final Set<InternalDistributedMember> memberFilter) { final HashMap<InternalDistributedMember, Integer> memberToPrimaryCount = new HashMap<>(); for (ProxyBucketRegion pbr : buckets) { // quick dirty check InternalDistributedMember p = pbr.getBucketAdvisor().basicGetPrimaryMember(); if (p != null) { memberToPrimaryCount.merge(p, 1, Integer::sum); } } final ArrayList<DataStoreBuckets> ds = new ArrayList<>(memberFilter.size()); adviseFilter(profile -> { if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; if (memberFilter.contains(p.getDistributedMember())) { Integer priCount = memberToPrimaryCount.get(p.getDistributedMember()); int primaryCount = 0; if (priCount != null) { primaryCount = priCount; } ds.add(new DataStoreBuckets(p.getDistributedMember(), p.numBuckets, primaryCount, p.localMaxMemory)); } } return false; }); return ds; } public void incrementBucketCount(Profile p) { PartitionProfile pp = (PartitionProfile) getProfile(p.getDistributedMember()); if (pp != null) { pp.numBuckets++; } } public void decrementsBucketCount(Profile p) { PartitionProfile pp = (PartitionProfile) getProfile(p.getDistributedMember()); if (pp != null) { pp.numBuckets--; if (pp.numBuckets < 0) { pp.numBuckets = 0; } } } /** * Dumps out all profiles in this advisor AND all buckets. Callers should check for debug enabled. * * @param infoMsg prefix message to log */ @Override public void dumpProfiles(String infoMsg) { if (logger.isDebugEnabled()) { logger.debug("[dumpProfiles] dumping {}", toStringWithProfiles()); } // 1st dump all profiles for this RegionAdvisor super.dumpProfiles(infoMsg); // 2nd dump all profiles for each BucketAdvisor ProxyBucketRegion[] pbrs = buckets; if (pbrs == null) { return; } for (ProxyBucketRegion pbr : pbrs) { pbr.getBucketAdvisor().dumpProfiles(infoMsg); BucketPersistenceAdvisor persistentAdvisor = pbr.getPersistenceAdvisor(); if (persistentAdvisor != null) { persistentAdvisor.dump(infoMsg); } } } public void notPrimary(int bucketId, InternalDistributedMember wasPrimary) { ProxyBucketRegion b = buckets[bucketId]; b.getBucketAdvisor().notPrimary(wasPrimary); } /** * Find the set of members which own primary buckets, including the local member * * @return set of InternalDistributedMember ids */ public Set advisePrimaryOwners() { ProxyBucketRegion[] bucs = buckets; HashSet<InternalDistributedMember> hs = new HashSet<>(); for (int i = 0; i < bucs.length; i++) { if (isStorageAssignedForBucket(i)) { InternalDistributedMember mem = bucs[i].getBucketAdvisor().getPrimary(); if (mem != null) { hs.add(mem); } } } return hs; } /** * A visitor interface for the buckets of this region used by * {@link RegionAdvisor#accept(BucketVisitor, Object)}. */ public interface BucketVisitor<T> { /** * Visit a given {@link ProxyBucketRegion} accumulating the results in the given aggregate. * Returns false when the visit has to be terminated. */ boolean visit(RegionAdvisor advisor, ProxyBucketRegion pbr, T aggregate); } /** * Invoke the given {@link BucketVisitor} on all the {@link ProxyBucketRegion} s exiting when the * {@link BucketVisitor#visit} method returns false. * * @param <T> the type of object used for aggregation of results * @param visitor the {@link BucketVisitor} to use for the visit * @param aggregate an aggregate object that will be used to for aggregation of results by the * {@link BucketVisitor#visit} method; this allows the {@link BucketVisitor} to not * maintain any state so that in most situations a global static object encapsulating the * required behaviour will work * * @return true when the full visit completed, and false if it was terminated due to * {@link BucketVisitor#visit} returning false */ public <T> boolean accept(BucketVisitor<T> visitor, T aggregate) { final ProxyBucketRegion[] bucs = buckets; Objects.requireNonNull(bucs); for (ProxyBucketRegion pbr : bucs) { if (!visitor.visit(this, pbr, aggregate)) { return false; } } return true; } public PartitionedRegion getPartitionedRegion() { return (PartitionedRegion) getAdvisee(); } /** * Update or create a bucket's meta-data If this advisor has not completed initialization, upon * return the profile will be enqueued for processing during initialization, otherwise the profile * will be immediately processed. This architecture limits the blockage of threads during * initialization. * * @param bucketId the unique identifier of the bucket * @param profile the bucket meta-data from a particular member with the bucket */ void putBucketProfile(int bucketId, BucketProfile profile) { synchronized (preInitQueueMonitor) { if (preInitQueue != null) { // Queue profile during pre-initialization QueuedBucketProfile qbf = new QueuedBucketProfile(bucketId, profile); preInitQueue.add(qbf); return; } } // Directly process profile post-initialization getBucket(bucketId).getBucketAdvisor().putProfile(profile); } static class QueuedBucketProfile { protected final int bucketId; final BucketProfile bucketProfile; /** true means that this member has departed the view */ protected final boolean memberDeparted; /** true means that this profile needs to be removed */ final boolean isRemoval; /** true means that the peer crashed */ protected final boolean crashed; /** * true means that this QueuedBucketProfile was created because of MembershipListener invocation */ final boolean fromMembershipListener; protected final boolean destroyed; protected final InternalDistributedMember memberId; final int[] serials; /** * Queue up an addition * * @param bId the bucket being added * @param p the profile to add */ QueuedBucketProfile(int bId, BucketProfile p) { bucketId = bId; bucketProfile = p; isRemoval = false; crashed = false; memberDeparted = false; memberId = null; serials = null; destroyed = false; fromMembershipListener = false; } /** * Queue up a removal due to member leaving the view * * @param mbr the member being removed */ QueuedBucketProfile(InternalDistributedMember mbr, boolean crashed, boolean destroyed, boolean fromMembershipListener) { bucketId = 0; bucketProfile = null; isRemoval = true; this.crashed = crashed; memberDeparted = true; memberId = mbr; serials = null; this.destroyed = destroyed; this.fromMembershipListener = fromMembershipListener; } /** * Queue up a removal due to region destroy * * @param mbr the member being removed * @param serials the serials it had */ QueuedBucketProfile(InternalDistributedMember mbr, int[] serials, boolean destroyed) { bucketId = 0; bucketProfile = null; isRemoval = true; crashed = false; memberDeparted = false; memberId = mbr; this.serials = serials; this.destroyed = destroyed; fromMembershipListener = false; } } public Set<InternalDistributedMember> adviseBucketProfileExchange() { return adviseDataStore(); } public long adviseTotalMemoryAllocation() { final AtomicLong total = new AtomicLong(); adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; total.addAndGet(p.localMaxMemory); } return false; }); return total.get(); } /** * Returns the total number of buckets created anywhere in the distributed system for this * partitioned region. * * @return the total number of buckets created anywhere for this PR */ public int getCreatedBucketsCount() { final ProxyBucketRegion[] bucs = buckets; if (bucs == null) { return 0; } int createdBucketsCount = 0; for (ProxyBucketRegion buc : bucs) { if (buc.getBucketOwnersCount() > 0) { createdBucketsCount++; } } return createdBucketsCount; } /** * Returns a possibly null list of this advisor's real bucket profiles. A real bucket profile is * one that for a bucket that actually has storage in this vm. * * @return a list of BucketProfileAndId instances; may be null * @since GemFire 5.5 */ public ArrayList getBucketRegionProfiles() { final ProxyBucketRegion[] bucs = buckets; if (bucs == null) { return null; } ArrayList<BucketProfileAndId> result = new ArrayList<>(bucs.length); for (int i = 0; i < bucs.length; i++) { // Fix for 41436 - we need to include buckets that are still initializing here // we must start including buckets in this list *before* those buckets exchange // profiles. BucketRegion br = bucs[i].getCreatedBucketRegion(); if (br != null) { result.add(new BucketProfileAndId(br.getProfile(), i)); } } if (result.size() == 0) { result = null; } return result; } /** * Takes a list of BucketProfileAndId and adds them to thsi advisors proxy buckets. * * @since GemFire 5.5 */ public void putBucketRegionProfiles(ArrayList<BucketProfileAndId> l) { for (BucketProfileAndId bp : l) { int id = bp.getId(); getBucket(id).getBucketAdvisor().putProfile(bp.getBucketProfile()); } } /** * return true if the given member has this advisor's partitioned region */ public boolean hasPartitionedRegion(InternalDistributedMember profileId) { if (getDistributionManager().getId().equals(profileId)) { return true; } return (getProfile(profileId) != null); } @Override protected void profileRemoved(Profile profile) { if (logger.isDebugEnabled()) { logger.debug("RA: removing profile {}", profile); } if (getAdvisee() instanceof PartitionedRegion) { ((PartitionedRegion) getAdvisee()).removeCriticalMember(profile.peerMemberId); } if (buckets != null) { for (ProxyBucketRegion bucket : buckets) { bucket.getBucketAdvisor().checkForLostPrimaryElector(profile); } } } public static class BucketProfileAndId implements DataSerializable { private static final long serialVersionUID = 332892607792421553L; /* final */ private int id; // bid = bucket id /* final */ private BucketProfile bp; private boolean isServerBucketProfile = false; public BucketProfileAndId(Profile bp, int id) { this.id = id; this.bp = (BucketProfile) bp; if (bp instanceof ServerBucketProfile) isServerBucketProfile = true; } public BucketProfileAndId() {} public int getId() { return id; } BucketProfile getBucketProfile() { return bp; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { id = in.readInt(); isServerBucketProfile = in.readBoolean(); if (isServerBucketProfile) bp = new ServerBucketProfile(); else bp = new BucketProfile(); InternalDataSerializer.invokeFromData(bp, in); } @Override public void toData(DataOutput out) throws IOException { out.writeInt(id); out.writeBoolean(isServerBucketProfile); InternalDataSerializer.invokeToData(bp, out); } @Override public String toString() { return "BucketProfileAndId (profile=" + bp + "; id=" + id + ")"; } } // profile listener to monitor remote member unexpected leave during shutdownAll private class ProfileShutdownListener implements ProfileListener { ProfileShutdownListener() { } private boolean profileChanged = false; void waitForChange() { Region pr = getPartitionedRegion(); synchronized (this) { while (!profileChanged && pr != null && !pr.isDestroyed()) { // the advisee might have been destroyed due to initialization failure try { wait(1000); } catch (InterruptedException ignored) { } } profileChanged = false; } } @Override public void profileCreated(Profile profile) { profileUpdated(profile); } @Override public void profileRemoved(Profile profile, boolean regionDestroyed) { // if a profile is gone, notify synchronized (this) { profileChanged = true; notifyAll(); } } @Override public void profileUpdated(Profile profile) { // when updated, notify the loop in GFC to check the list again synchronized (this) { profileChanged = true; notifyAll(); } } } }
geode-core/src/main/java/org/apache/geode/internal/cache/partitioned/RegionAdvisor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.partitioned; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import org.apache.logging.log4j.Logger; import org.apache.geode.DataSerializable; import org.apache.geode.DataSerializer; import org.apache.geode.annotations.Immutable; import org.apache.geode.cache.InterestPolicy; import org.apache.geode.cache.LowMemoryException; import org.apache.geode.cache.Region; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.ProfileListener; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.internal.Assert; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.BucketAdvisor; import org.apache.geode.internal.cache.BucketAdvisor.BucketProfile; import org.apache.geode.internal.cache.BucketAdvisor.ServerBucketProfile; import org.apache.geode.internal.cache.BucketPersistenceAdvisor; import org.apache.geode.internal.cache.BucketRegion; import org.apache.geode.internal.cache.BucketServerLocation66; import org.apache.geode.internal.cache.CacheDistributionAdvisor; import org.apache.geode.internal.cache.FixedPartitionAttributesImpl; import org.apache.geode.internal.cache.InternalRegionArguments; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.internal.cache.PartitionedRegionStats; import org.apache.geode.internal.cache.ProxyBucketRegion; import org.apache.geode.internal.cache.control.MemoryThresholds; import org.apache.geode.internal.cache.control.ResourceAdvisor; import org.apache.geode.internal.logging.LogService; import org.apache.geode.internal.logging.log4j.LogMarker; public class RegionAdvisor extends CacheDistributionAdvisor { private static final Logger logger = LogService.getLogger(); /** * Number of threads allowed to concurrently volunteer for bucket primary. */ public static final short VOLUNTEERING_THREAD_COUNT = Integer .getInteger(DistributionConfig.GEMFIRE_PREFIX + "RegionAdvisor.volunteeringThreadCount", 1) .shortValue(); /** * Non-thread safe queue for volunteering for primary bucket. Each BucketAdvisor for this PR uses * this queue. The thread that uses this queue is a waiting pool thread. Any thread using this * queue must synchronize on this queue. */ private final Queue<Runnable> volunteeringQueue = new ConcurrentLinkedQueue<>(); /** * Semaphore with {@link #VOLUNTEERING_THREAD_COUNT} number of permits to control number of * threads volunteering for bucket primaries. */ private final Semaphore volunteeringSemaphore = new Semaphore(VOLUNTEERING_THREAD_COUNT); private volatile int lastActiveProfiles = 0; private volatile int numDataStores = 0; protected volatile ProxyBucketRegion[] buckets; private Queue<QueuedBucketProfile> preInitQueue; private final Object preInitQueueMonitor = new Object(); private ConcurrentHashMap<Integer, Set<ServerBucketProfile>> clientBucketProfilesMap; private RegionAdvisor(PartitionedRegion region) { super(region); synchronized (preInitQueueMonitor) { preInitQueue = new ConcurrentLinkedQueue<>(); } clientBucketProfilesMap = new ConcurrentHashMap<>(); } public static RegionAdvisor createRegionAdvisor(PartitionedRegion region) { RegionAdvisor advisor = new RegionAdvisor(region); advisor.initialize(); return advisor; } public PartitionedRegionStats getPartitionedRegionStats() { return getPartitionedRegion().getPrStats(); } public synchronized void initializeRegionAdvisor() { if (buckets != null) { return; } PartitionedRegion p = getPartitionedRegion(); int numBuckets = p.getAttributes().getPartitionAttributes().getTotalNumBuckets(); ProxyBucketRegion[] bucs = new ProxyBucketRegion[numBuckets]; InternalRegionArguments args = new InternalRegionArguments(); args.setPartitionedRegionAdvisor(this); for (int i = 0; i < bucs.length; i++) { bucs[i] = new ProxyBucketRegion(i, p, args); bucs[i].initialize(); } buckets = bucs; } /** * Process those profiles which were received during the initialization period. It is safe to * process these profiles potentially out of order due to the profiles version which is * established on the sender. */ public void processProfilesQueuedDuringInitialization() { synchronized (preInitQueueMonitor) { Iterator pi = preInitQueue.iterator(); boolean finishedInitQueue = false; try { while (pi.hasNext()) { Object o = pi.next(); QueuedBucketProfile qbp = (QueuedBucketProfile) o; if (!qbp.isRemoval) { if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "applying queued profile addition for bucket {}", qbp.bucketId); } getBucket(qbp.bucketId).getBucketAdvisor().putProfile(qbp.bucketProfile); } else if (qbp.memberDeparted || !getDistributionManager().isCurrentMember(qbp.memberId)) { boolean crashed; if (qbp.memberDeparted) { crashed = qbp.crashed; } else { // TODO not necessarily accurate, but how important is this? crashed = !stillInView(qbp.memberId); } if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "applying queued member departure for all buckets for {}", qbp.memberId); } for (ProxyBucketRegion bucket : buckets) { BucketAdvisor ba = bucket.getBucketAdvisor(); ba.removeId(qbp.memberId, crashed, qbp.destroyed, qbp.fromMembershipListener); } // for } else { // apply removal for member still in the view if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "applying queued profile removal for all buckets for {}", qbp.memberId); } for (int i = 0; i < buckets.length; i++) { BucketAdvisor ba = buckets[i].getBucketAdvisor(); int serial = qbp.serials[i]; if (serial != ILLEGAL_SERIAL) { ba.removeIdWithSerial(qbp.memberId, serial, qbp.destroyed); } } // for } // apply removal for member still in the view } // while finishedInitQueue = true; } finally { preInitQueue = null; // prevent further additions to the queue preInitQueueMonitor.notifyAll(); if (!finishedInitQueue && !getAdvisee().getCancelCriterion().isCancelInProgress()) { logger.error("Failed to process all queued BucketProfiles for {}", getAdvisee()); } } } } @Override protected Profile instantiateProfile(InternalDistributedMember memberId, int version) { return new PartitionProfile(memberId, version); } /** * Returns the {@link #volunteeringQueue} used to queue primary volunteering tasks by this PR's * BucketAdvisors. * * @return the volunteering queue for use by this PR's BucketAdvisors */ public Queue<Runnable> getVolunteeringQueue() { return volunteeringQueue; } /** * Returns the {@link #volunteeringSemaphore} for controlling the number of threads that this PR's * BucketAdvisors are allowed to use for volunteering to be primary. * * @return the semaphore for controlling number of volunteering threads */ public Semaphore getVolunteeringSemaphore() { return volunteeringSemaphore; } /** * Returns an unmodifiable map of bucket IDs to locations hosting the bucket. */ public Map<Integer, List<BucketServerLocation66>> getAllClientBucketProfiles() { Map<Integer, List<BucketServerLocation66>> bucketToServerLocations = new HashMap<>(); for (Integer bucketId : clientBucketProfilesMap.keySet()) { ArrayList<BucketServerLocation66> clientBucketProfiles = new ArrayList<>(); for (BucketProfile profile : clientBucketProfilesMap.get(bucketId)) { if (profile.isHosting) { ServerBucketProfile cProfile = (ServerBucketProfile) profile; Set<BucketServerLocation66> bucketServerLocations = cProfile.getBucketServerLocations(); // Either we can make BucketServeLocation having ServerLocation with them // Or we can create bucketServerLocation as it is by iterating over the set of servers clientBucketProfiles.addAll(bucketServerLocations); } } bucketToServerLocations.put(bucketId, clientBucketProfiles); } if (getPartitionedRegion().isDataStore()) { for (Integer bucketId : getPartitionedRegion().getDataStore().getAllLocalBucketIds()) { BucketProfile profile = getBucketAdvisor(bucketId).getLocalProfile(); if (logger.isDebugEnabled()) { logger.debug("The local profile is : {}", profile); } if (profile != null) { List<BucketServerLocation66> clientBucketProfiles = bucketToServerLocations.computeIfAbsent(bucketId, k -> new ArrayList<>()); if ((profile instanceof ServerBucketProfile) && profile.isHosting) { ServerBucketProfile cProfile = (ServerBucketProfile) profile; Set<BucketServerLocation66> bucketServerLocations = cProfile.getBucketServerLocations(); // Either we can make BucketServeLocation having ServerLocation with // them // Or we can create bucketServerLocation as it is by iterating over // the set of servers clientBucketProfiles.removeAll(bucketServerLocations); clientBucketProfiles.addAll(bucketServerLocations); } } } } return bucketToServerLocations; } public ConcurrentHashMap<Integer, Set<ServerBucketProfile>> getAllClientBucketProfilesTest() { ConcurrentHashMap<Integer, Set<ServerBucketProfile>> map = new ConcurrentHashMap<>(); Map<Integer, List<BucketServerLocation66>> testMap = new HashMap<>(getAllClientBucketProfiles()); for (Integer bucketId : testMap.keySet()) { Set<ServerBucketProfile> parr = new HashSet<>(clientBucketProfilesMap.get(bucketId)); map.put(bucketId, parr); } if (getPartitionedRegion().isDataStore()) { for (Integer bucketId : getPartitionedRegion().getDataStore().getAllLocalBucketIds()) { BucketProfile profile = getBucketAdvisor(bucketId).getLocalProfile(); if ((profile instanceof ServerBucketProfile) && profile.isHosting) { map.get(bucketId).add((ServerBucketProfile) profile); } } } if (logger.isDebugEnabled()) { logger.debug("This maps is sksk {} and size is {}", map, map.keySet().size()); } return map; } public Set<ServerBucketProfile> getClientBucketProfiles(Integer bucketId) { return clientBucketProfilesMap.get(bucketId); } public void setClientBucketProfiles(Integer bucketId, Set<ServerBucketProfile> profiles) { clientBucketProfilesMap.put(bucketId, Collections.unmodifiableSet(profiles)); } /** * Close the bucket advisors, releasing any locks for primary buckets */ public void closeBucketAdvisors() { if (buckets != null) { for (ProxyBucketRegion pbr : buckets) { pbr.close(); } } } /** * Close the adviser and all bucket advisors. */ @Override public void close() { super.close(); if (buckets != null) { for (ProxyBucketRegion bucket : buckets) { bucket.close(); } } } @Override public boolean removeId(ProfileId memberId, boolean crashed, boolean regionDestroyed, boolean fromMembershipListener) { // It's important that we remove member from the bucket advisors first // Calling super.removeId triggers redundancy satisfaction, so the bucket // advisors must have up to data information at that point. boolean removeBuckets = true; synchronized (preInitQueueMonitor) { if (preInitQueue != null) { // Queue profile during pre-initialization QueuedBucketProfile qbf = new QueuedBucketProfile((InternalDistributedMember) memberId, crashed, regionDestroyed, fromMembershipListener); preInitQueue.add(qbf); removeBuckets = false; } } // synchronized if (removeBuckets && buckets != null) { for (ProxyBucketRegion pbr : buckets) { BucketAdvisor pbra = pbr.getBucketAdvisor(); boolean shouldSync = false; Profile profile = null; InternalDistributedMember mbr = null; if (memberId instanceof InternalDistributedMember) { mbr = (InternalDistributedMember) memberId; shouldSync = pbra.shouldSyncForCrashedMember(mbr); if (shouldSync) { profile = pbr.getBucketAdvisor().getProfile(memberId); } } boolean removed = pbr.getBucketAdvisor().removeId(memberId, crashed, regionDestroyed, fromMembershipListener); if (removed && shouldSync) { pbra.syncForCrashedMember(mbr, profile); } } } boolean removedId; removedId = super.removeId(memberId, crashed, regionDestroyed, fromMembershipListener); if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeId: removing member from region {}: {}; removed = {}; crashed = {}", getPartitionedRegion().getName(), memberId, removedId, crashed); } return removedId; } /** * Clear the knowledge of given member from this advisor. In particular, clear the knowledge of * remote Bucket locations so that we avoid sending partition messages to buckets that will soon * be destroyed. * * @param memberId member that has closed the region * @param prSerial serial number of this partitioned region * @param serials serial numbers of buckets that need to be removed */ public void removeIdAndBuckets(InternalDistributedMember memberId, int prSerial, int[] serials, boolean regionDestroyed) { if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeIdAndBuckets: removing member from region {}: {}; buckets = ({}) serials", getPartitionedRegion().getName(), memberId, (serials == null ? "null" : serials.length)); } synchronized (preInitQueueMonitor) { if (preInitQueue != null) { // Queue profile during pre-initialization QueuedBucketProfile qbf = new QueuedBucketProfile(memberId, serials, regionDestroyed); preInitQueue.add(qbf); return; } } // OK, apply the update NOW if (buckets != null) { Objects.requireNonNull(serials); if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeIdAndBuckets: removing buckets for member{};{}", memberId, this); } for (int i = 0; i < buckets.length; i++) { int s = serials[i]; if (s != ILLEGAL_SERIAL) { if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "RegionAdvisor#removeIdAndBuckets: removing bucket #{} serial {}", i, s); } buckets[i].getBucketAdvisor().removeIdWithSerial(memberId, s, regionDestroyed); } } super.removeIdWithSerial(memberId, prSerial, regionDestroyed); } } /** * Iterates over all buckets and marks them sick if the given member hosts the bucket. * * @param sick true if the bucket should be marked sick, false if healthy */ public void markBucketsOnMember(DistributedMember member, boolean sick) { // The health profile exchange at cache level should take care of preInitQueue if (buckets == null) { return; } for (int i = 0; i < buckets.length; i++) { if (sick && !buckets[i].getBucketOwners().contains(member)) { continue; } buckets[i].setBucketSick(member, sick); if (logger.isDebugEnabled()) { logger.debug("Marked bucket ({}) {}", getPartitionedRegion().bucketStringForLogs(i), (buckets[i].isBucketSick() ? "sick" : "healthy")); } } } public void updateBucketStatus(int bucketId, DistributedMember member, boolean profileRemoved) { if (profileRemoved) { buckets[bucketId].setBucketSick(member, false); } else { ResourceAdvisor advisor = getPartitionedRegion().getCache().getResourceAdvisor(); boolean sick = advisor.adviseCriticalMembers().contains(member); if (logger.isDebugEnabled()) { logger.debug("updateBucketStatus:({}):member:{}:sick:{}", getPartitionedRegion().bucketStringForLogs(bucketId), member, sick); } buckets[bucketId].setBucketSick(member, sick); } } /** * throws LowMemoryException if the given bucket is hosted on a member which has crossed the * ResourceManager threshold. * * @param key for bucketId used in exception */ public void checkIfBucketSick(final int bucketId, final Object key) throws LowMemoryException { if (MemoryThresholds.isLowMemoryExceptionDisabled()) { return; } assert buckets != null; assert buckets[bucketId] != null; if (buckets[bucketId].isBucketSick()) { Set<DistributedMember> sm = buckets[bucketId].getSickMembers(); if (sm.isEmpty()) { // check again as this list is obtained under synchronization // fixes bug 50845 return; } if (logger.isDebugEnabled()) { logger.debug("For bucket {} sick members are {}.", getPartitionedRegion().bucketStringForLogs(bucketId), sm); } throw new LowMemoryException(String.format( "PartitionedRegion: %s cannot process operation on key %s because members %s are running low on memory", getPartitionedRegion().getFullPath(), key, sm), sm); } } /** * Profile information for a remote counterpart. */ public static class PartitionProfile extends CacheProfile { /** * The number of Mb the VM is allowed to use for the PR * {@link PartitionedRegion#getLocalMaxMemory()} */ public int localMaxMemory; /** * A data store is a VM that has a non-zero local max memory, Since the localMaxMemory is * already sent, there is no need to send this state as it's implied in localMaxMemory */ public transient boolean isDataStore = false; /** * requiresNotification determines whether a member needs to be notified of cache operations so * that cache listeners and other hooks can be engaged * * @since GemFire 5.1 */ public boolean requiresNotification = false; /** * Track the number of buckets this data store may have, implies isDataStore == true This value * is NOT sent directly but updated when {@link org.apache.geode.internal.cache.BucketAdvisor}s * receive updates */ public transient short numBuckets = 0; /** * represents the list of the fixed partitions defined for this region. */ public List<FixedPartitionAttributesImpl> fixedPAttrs; // Indicate the status of shutdown request public int shutDownAllStatus = PartitionedRegion.RUNNING_MODE; /** for internal use, required for DataSerializer.readObject */ public PartitionProfile() {} public PartitionProfile(InternalDistributedMember memberId, int version) { super(memberId, version); isPartitioned = true; } @Override protected int getIntInfo() { int s = super.getIntInfo(); if (requiresNotification) s |= REQUIRES_NOTIFICATION_MASK; return s; } @Override protected void setIntInfo(int s) { super.setIntInfo(s); requiresNotification = (s & REQUIRES_NOTIFICATION_MASK) != 0; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); localMaxMemory = in.readInt(); isDataStore = localMaxMemory > 0; fixedPAttrs = DataSerializer.readObject(in); shutDownAllStatus = in.readInt(); } @Override public void toData(DataOutput out) throws IOException { super.toData(out); out.writeInt(localMaxMemory); DataSerializer.writeObject(fixedPAttrs, out); out.writeInt(shutDownAllStatus); } @Override public StringBuilder getToStringHeader() { return new StringBuilder("RegionAdvisor.PartitionProfile"); } @Override public void fillInToString(StringBuilder sb) { super.fillInToString(sb); sb.append("; isDataStore=").append(isDataStore).append("; requiresNotification=") .append(requiresNotification).append("; localMaxMemory=").append(localMaxMemory) .append("; numBuckets=").append(numBuckets); if (fixedPAttrs != null) { sb.append("; FixedPartitionAttributes=").append(fixedPAttrs); } sb.append("; filterProfile=").append(filterProfile); sb.append("; shutDownAllStatus=").append(shutDownAllStatus); } @Override public int getDSFID() { return PARTITION_PROFILE; } } // end class PartitionProfile public int getNumDataStores() { final int numProfs = getNumProfiles(); if (lastActiveProfiles != numProfs) { numDataStores = adviseDataStore().size(); lastActiveProfiles = numProfs; } return numDataStores; } public Set<InternalDistributedMember> adviseDataStore() { return adviseDataStore(false); } /** * Returns the set of data stores that have finished initialization. */ public Set<InternalDistributedMember> adviseInitializedDataStore() { return adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; return p.isDataStore && (!p.dataPolicy.withPersistence() || p.regionInitialized); } return false; }); } /** * Returns the set of members that are not arrived at specified shutDownAll status */ private Set<InternalDistributedMember> adviseNotAtShutDownAllStatus(final int status) { return adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; return p.isDataStore && p.shutDownAllStatus < status; } return false; }); } public void waitForProfileStatus(int status) { ProfileShutdownListener listener = new ProfileShutdownListener(); addProfileChangeListener(listener); try { int memberNum; String regionName = getPartitionedRegion().getFullPath(); do { Region pr = getPartitionedRegion().getCache().getRegion(regionName); if (pr == null || pr.isDestroyed()) break; Set members = adviseNotAtShutDownAllStatus(status); memberNum = members.size(); if (memberNum > 0) { if (logger.isDebugEnabled()) { logger.debug("waitForProfileStatus {} at PR:{}, expecting {} members: {}", status, getPartitionedRegion().getFullPath(), memberNum, members); } listener.waitForChange(); } } while (memberNum > 0); } finally { removeProfileChangeListener(listener); } } /** * Return a real Set if set to true, which can be modified * * @param realHashSet true if a real set is needed * @return depending on the realHashSet value may be a HashSet */ public Set<InternalDistributedMember> adviseDataStore(boolean realHashSet) { Set<InternalDistributedMember> s = adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; return p.isDataStore; } return false; }); if (realHashSet) { if (s == Collections.EMPTY_SET) { s = new HashSet<>(); } } if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "adviseDataStore returning {} from {}", s, toStringWithProfiles()); } return s; } /** * return the set of the distributed members on which the given partition name is defined. * */ public Set<InternalDistributedMember> adviseFixedPartitionDataStores(final String partitionName) { Set<InternalDistributedMember> s = adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are // Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; if (p.fixedPAttrs != null) { for (FixedPartitionAttributesImpl fpa : p.fixedPAttrs) { if (fpa.getPartitionName().equals(partitionName)) { return true; } } } } return false; }); if (s == Collections.EMPTY_SET) { s = new HashSet<>(); } if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "adviseFixedPartitionDataStore returning {} from {}", s, toStringWithProfiles()); } return s; } /** * return a distributed members on which the primary partition for given bucket is defined * */ public InternalDistributedMember adviseFixedPrimaryPartitionDataStore(final int bucketId) { final List<InternalDistributedMember> fixedPartitionDataStore = new ArrayList<>(1); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; if (p.fixedPAttrs != null) { for (FixedPartitionAttributesImpl fpa : p.fixedPAttrs) { if (fpa.isPrimary() && fpa.hasBucket(bucketId)) { fixedPartitionDataStore.add(0, p.getDistributedMember()); return true; } } } } return false; }); if (logger.isTraceEnabled(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE)) { logger.trace(LogMarker.DISTRIBUTION_ADVISOR_VERBOSE, "adviseFixedPartitionDataStore returning {} from {}", fixedPartitionDataStore, toStringWithProfiles()); } if (fixedPartitionDataStore.isEmpty()) { return null; } return fixedPartitionDataStore.get(0); } /** * Returns the list of all remote FixedPartitionAttributes defined across all members for the * given partitioned region * * @return list of all partitions(primary as well as secondary) defined on remote nodes */ public List<FixedPartitionAttributesImpl> adviseAllFixedPartitionAttributes() { final List<FixedPartitionAttributesImpl> allFPAs = new ArrayList<>(); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { final PartitionProfile pp = (PartitionProfile) profile; if (pp.fixedPAttrs != null) { allFPAs.addAll(pp.fixedPAttrs); return true; } } return false; }); return allFPAs; } /** * Returns the list of all FixedPartitionAttributes defined across all members of given * partitioned region for a given FixedPartitionAttributes * * @return the list of same partitions defined on other nodes(can be primary or secondary) */ public List<FixedPartitionAttributesImpl> adviseSameFPAs(final FixedPartitionAttributesImpl fpa) { final List<FixedPartitionAttributesImpl> sameFPAs = new ArrayList<>(); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { final PartitionProfile pp = (PartitionProfile) profile; List<FixedPartitionAttributesImpl> fpaList = pp.fixedPAttrs; if (fpaList != null) { int index = fpaList.indexOf(fpa); if (index != -1) { sameFPAs.add(fpaList.get(index)); } return true; } } return false; }); return sameFPAs; } /** * Returns the list of all remote primary FixedPartitionAttributes defined across members for the * given partitioned region * * @return list of all primary partitions defined on remote nodes */ public List<FixedPartitionAttributesImpl> adviseRemotePrimaryFPAs() { final List<FixedPartitionAttributesImpl> remotePrimaryFPAs = new ArrayList<>(); fetchProfiles(profile -> { if (profile instanceof PartitionProfile) { final PartitionProfile pp = (PartitionProfile) profile; List<FixedPartitionAttributesImpl> fpaList = pp.fixedPAttrs; if (fpaList != null) { for (FixedPartitionAttributesImpl fpa : fpaList) { if (fpa.isPrimary()) { remotePrimaryFPAs.add(fpa); return true; } } } } return false; }); return remotePrimaryFPAs; } public Set<InternalDistributedMember> adviseAllPRNodes() { return adviseFilter(profile -> { CacheProfile prof = (CacheProfile) profile; return prof.isPartitioned; }); } Set adviseAllServersWithInterest() { return adviseFilter(profile -> { CacheProfile prof = (CacheProfile) profile; return prof.hasCacheServer && prof.filterProfile != null && prof.filterProfile.hasInterest(); }); } @Immutable private static final Filter prServerWithInterestFilter = profile -> { CacheProfile prof = (CacheProfile) profile; return prof.isPartitioned && prof.hasCacheServer && prof.filterProfile != null && prof.filterProfile.hasInterest(); }; public boolean hasPRServerWithInterest() { return satisfiesFilter(prServerWithInterestFilter); } /** * return the set of all members who must receive operation notifications * * @since GemFire 5.1 */ public Set<InternalDistributedMember> adviseRequiresNotification() { return adviseFilter(profile -> { if (profile instanceof PartitionProfile) { PartitionProfile prof = (PartitionProfile) profile; if (prof.isPartitioned) { if (prof.hasCacheListener) { InterestPolicy pol = prof.subscriptionAttributes.getInterestPolicy(); if (pol == InterestPolicy.ALL) { return true; } } return prof.requiresNotification; } } return false; }); } @Override public synchronized boolean putProfile(Profile p) { assert p instanceof CacheProfile; CacheProfile profile = (CacheProfile) p; PartitionedRegion pr = getPartitionedRegion(); if (profile.hasCacheLoader) { pr.setHaveCacheLoader(); } // don't keep FilterProfiles around in accessors. They're needed only for // routing messages in data stors if (profile.filterProfile != null) { if (!pr.isDataStore()) { profile.filterProfile = null; } } return super.putProfile(profile); } public PartitionProfile getPartitionProfile(InternalDistributedMember id) { return (PartitionProfile) getProfile(id); } public boolean isPrimaryForBucket(int bucketId) { if (buckets == null) { return false; } return buckets[bucketId].isPrimary(); } /** * Returns true if the bucket is currently being hosted locally. Note that as soon as this call * returns, this datastore may begin to host the bucket, thus two calls in a row may be different. * * @param bucketId the index of the bucket to check * @return true if the bucket is currently being hosted locally */ public boolean isBucketLocal(int bucketId) { if (buckets == null) { return false; } return buckets[bucketId].getHostedBucketRegion() != null; } public boolean areBucketsInitialized() { return buckets != null; } /** * Returns the real BucketRegion if it's currently locally hosted. Otherwise the ProxyBucketRegion * is returned. Note that this member may be in the process of hosting the real bucket. Until that * has completed, getBucket will continue to return the ProxyBucketRegion. * * @param bucketId the index of the bucket to retrieve * @return the bucket identified by bucketId */ public Bucket getBucket(int bucketId) { Assert.assertTrue(buckets != null); ProxyBucketRegion pbr = buckets[bucketId]; Bucket ret = pbr.getHostedBucketRegion(); if (ret != null) { return ret; } else { return pbr; } } /** * Returns the BucketAdvisor for the specified bucket. * * @param bucketId the index of the bucket to retrieve the advisor for * @return the bucket advisor identified by bucketId */ public BucketAdvisor getBucketAdvisor(int bucketId) { Assert.assertTrue(buckets != null); ProxyBucketRegion pbr = buckets[bucketId]; Bucket ret = pbr.getHostedBucketRegion(); if (ret != null) { return ret.getBucketAdvisor(); } else { return pbr.getBucketAdvisor(); } } public Map<Integer, BucketAdvisor> getAllBucketAdvisors() { Assert.assertTrue(buckets != null); Map<Integer, BucketAdvisor> map = new HashMap<>(); for (ProxyBucketRegion pbr : buckets) { Bucket ret = pbr.getHostedBucketRegion(); if (ret != null) { map.put(ret.getId(), ret.getBucketAdvisor()); } } return map; } /** * * @return array of serial numbers for buckets created locally */ public int[] getBucketSerials() { if (buckets == null) { return new int[0]; } int[] result = new int[buckets.length]; for (int i = 0; i < result.length; i++) { ProxyBucketRegion pbr = buckets[i]; Bucket b = pbr.getCreatedBucketRegion(); if (b == null) { result[i] = ILLEGAL_SERIAL; } else { result[i] = b.getSerialNumber(); } } return result; } /** * Returns the bucket identified by bucketId after waiting for initialization to finish processing * queued profiles. Call synchronizes and waits on {@link #preInitQueueMonitor}. * * @param bucketId the bucket identifier * @return the bucket identified by bucketId * @throws org.apache.geode.distributed.DistributedSystemDisconnectedException if interrupted for * shutdown cancellation */ public Bucket getBucketPostInit(int bucketId) { synchronized (preInitQueueMonitor) { boolean interrupted = false; try { while (preInitQueue != null) { try { preInitQueueMonitor.wait(); // spurious wakeup ok } catch (InterruptedException e) { interrupted = true; getAdvisee().getCancelCriterion().checkCancelInProgress(e); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } return getBucket(bucketId); } /** * Get the most recent primary node for the bucketId. Returns null if no primary can be found * within {@link DistributionConfig#getMemberTimeout}. * * @return the Node managing the primary copy of the bucket */ public InternalDistributedMember getPrimaryMemberForBucket(int bucketId) { Assert.assertTrue(buckets != null); Bucket b = buckets[bucketId]; return b.getBucketAdvisor().getPrimary(); } /** * Return the node favored for reading for the given bucket * * @param bucketId the bucket we want to read * @return the member, possibly null if no member is available */ public InternalDistributedMember getPreferredNode(int bucketId) { Assert.assertTrue(buckets != null); Bucket b = buckets[bucketId]; return b.getBucketAdvisor().getPreferredNode(); } public boolean isStorageAssignedForBucket(int bucketId) { Assert.assertTrue(buckets != null); return buckets[bucketId].getBucketRedundancy() >= 0; } /** * @param bucketId the bucket to check redundancy on * @param minRedundancy the amount of expected redundancy; ignored if wait is false * @param wait true if caller wants us to wait for redundancy * @return true if redundancy on given bucket is detected */ public boolean isStorageAssignedForBucket(int bucketId, int minRedundancy, boolean wait) { if (!wait) { return isStorageAssignedForBucket(bucketId); } else { Assert.assertTrue(buckets != null); return buckets[bucketId].getBucketAdvisor().waitForRedundancy(minRedundancy); } } /** * Get the redundancy of the this bucket, taking into account the local bucket, if any. * * @return number of redundant copies for a given bucket, or -1 if there are no instances of the * bucket. */ public int getBucketRedundancy(int bucketId) { Assert.assertTrue(buckets != null); return buckets[bucketId].getBucketRedundancy(); } /** * Return the set of all members who currently own the bucket, including the local owner, if * applicable * * @return a set of {@link InternalDistributedMember}s that own the bucket */ public Set<InternalDistributedMember> getBucketOwners(int bucketId) { Assert.assertTrue(buckets != null); return buckets[bucketId].getBucketOwners(); } /** * Return the set of buckets which have storage assigned * * @return set of Integer bucketIds */ public Set<Integer> getBucketSet() { Assert.assertTrue(buckets != null); return new BucketSet(); } public ProxyBucketRegion[] getProxyBucketArray() { return buckets; } private class BucketSet extends AbstractSet<Integer> { final ProxyBucketRegion[] pbrs; BucketSet() { pbrs = buckets; Assert.assertTrue(pbrs != null); } /* * Note: The consistency between size(), hasNext() and next() is weak, meaning that the state of * the backing Set may change causing more or less elements to be available after calling size() */ @Override public int size() { return pbrs.length; } @Override public Iterator<Integer> iterator() { return new BucketSetIterator(); } class BucketSetIterator implements Iterator<Integer> { private int currentItem = -1; @Override public void remove() { throw new UnsupportedOperationException(); } /* * Note: The consistency guarantee between hasNext() and next() is weak. It's possible * hasNext() will return true and a following call to next() may throw NoSuchElementException * (due to loss of bucket storage). Its also equally possible for hasNext() to return false * and a subsequent call to next() will return a valid bucketid. */ @Override public boolean hasNext() { if (getPartitionedRegion().isFixedPartitionedRegion()) { if (currentItem + 1 < pbrs.length) { int possibleBucketId = currentItem; boolean bucketExists = false; List<FixedPartitionAttributesImpl> fpaList = adviseAllFixedPartitionAttributes(); List<FixedPartitionAttributesImpl> localFpas = getPartitionedRegion().getFixedPartitionAttributesImpl(); if (localFpas != null) { fpaList.addAll(localFpas); } while (++possibleBucketId < pbrs.length && !bucketExists) { for (FixedPartitionAttributesImpl fpa : fpaList) { if (fpa.hasBucket(possibleBucketId)) { bucketExists = true; break; } } } return bucketExists; } else { return false; } } else { return currentItem + 1 < pbrs.length; } } @Override public Integer next() { if (++currentItem < pbrs.length) { if (isStorageAssignedForBucket(currentItem)) { return currentItem; } else { if (getPartitionedRegion().isFixedPartitionedRegion()) { boolean bucketExists = false; List<FixedPartitionAttributesImpl> fpaList = adviseAllFixedPartitionAttributes(); List<FixedPartitionAttributesImpl> localFpas = getPartitionedRegion().getFixedPartitionAttributesImpl(); if (localFpas != null) { fpaList.addAll(localFpas); } do { for (FixedPartitionAttributesImpl fpa : fpaList) { if (fpa.hasBucket(currentItem)) { bucketExists = true; break; } } if (!bucketExists) { currentItem++; } } while (currentItem < pbrs.length && !bucketExists); if (bucketExists) { getPartitionedRegion().createBucket(currentItem, 0, null); return currentItem; } } else { getPartitionedRegion().createBucket(currentItem, 0, null); return currentItem; } } } throw new NoSuchElementException(); } } } /** * Obtain the ordered {@link ArrayList} of data stores limited to those specified in the provided * memberFilter. * * @param memberFilter the set of members allowed to be in the list. * @return a list of DataStoreBuckets */ public ArrayList<DataStoreBuckets> adviseFilteredDataStores( final Set<InternalDistributedMember> memberFilter) { final HashMap<InternalDistributedMember, Integer> memberToPrimaryCount = new HashMap<>(); for (ProxyBucketRegion pbr : buckets) { // quick dirty check InternalDistributedMember p = pbr.getBucketAdvisor().basicGetPrimaryMember(); if (p != null) { memberToPrimaryCount.merge(p, 1, Integer::sum); } } final ArrayList<DataStoreBuckets> ds = new ArrayList<>(memberFilter.size()); adviseFilter(profile -> { if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; if (memberFilter.contains(p.getDistributedMember())) { Integer priCount = memberToPrimaryCount.get(p.getDistributedMember()); int primaryCount = 0; if (priCount != null) { primaryCount = priCount; } ds.add(new DataStoreBuckets(p.getDistributedMember(), p.numBuckets, primaryCount, p.localMaxMemory)); } } return false; }); return ds; } public void incrementBucketCount(Profile p) { PartitionProfile pp = (PartitionProfile) getProfile(p.getDistributedMember()); if (pp != null) { Assert.assertTrue(pp.isDataStore); pp.numBuckets++; } } public void decrementsBucketCount(Profile p) { PartitionProfile pp = (PartitionProfile) getProfile(p.getDistributedMember()); if (pp != null) { Assert.assertTrue(pp.isDataStore); pp.numBuckets--; if (pp.numBuckets < 0) { pp.numBuckets = 0; } } } /** * Dumps out all profiles in this advisor AND all buckets. Callers should check for debug enabled. * * @param infoMsg prefix message to log */ @Override public void dumpProfiles(String infoMsg) { if (logger.isDebugEnabled()) { logger.debug("[dumpProfiles] dumping {}", toStringWithProfiles()); } // 1st dump all profiles for this RegionAdvisor super.dumpProfiles(infoMsg); // 2nd dump all profiles for each BucketAdvisor ProxyBucketRegion[] pbrs = buckets; if (pbrs == null) { return; } for (ProxyBucketRegion pbr : pbrs) { pbr.getBucketAdvisor().dumpProfiles(infoMsg); BucketPersistenceAdvisor persistentAdvisor = pbr.getPersistenceAdvisor(); if (persistentAdvisor != null) { persistentAdvisor.dump(infoMsg); } } } public void notPrimary(int bucketId, InternalDistributedMember wasPrimary) { Assert.assertTrue(buckets != null); ProxyBucketRegion b = buckets[bucketId]; b.getBucketAdvisor().notPrimary(wasPrimary); } /** * Find the set of members which own primary buckets, including the local member * * @return set of InternalDistributedMember ids */ public Set advisePrimaryOwners() { Assert.assertTrue(buckets != null); ProxyBucketRegion[] bucs = buckets; HashSet<InternalDistributedMember> hs = new HashSet<>(); for (int i = 0; i < bucs.length; i++) { if (isStorageAssignedForBucket(i)) { InternalDistributedMember mem = bucs[i].getBucketAdvisor().getPrimary(); if (mem != null) { hs.add(mem); } } } return hs; } /** * A visitor interface for the buckets of this region used by * {@link RegionAdvisor#accept(BucketVisitor, Object)}. */ public interface BucketVisitor<T> { /** * Visit a given {@link ProxyBucketRegion} accumulating the results in the given aggregate. * Returns false when the visit has to be terminated. */ boolean visit(RegionAdvisor advisor, ProxyBucketRegion pbr, T aggregate); } /** * Invoke the given {@link BucketVisitor} on all the {@link ProxyBucketRegion} s exiting when the * {@link BucketVisitor#visit} method returns false. * * @param <T> the type of object used for aggregation of results * @param visitor the {@link BucketVisitor} to use for the visit * @param aggregate an aggregate object that will be used to for aggregation of results by the * {@link BucketVisitor#visit} method; this allows the {@link BucketVisitor} to not * maintain any state so that in most situations a global static object encapsulating the * required behaviour will work * * @return true when the full visit completed, and false if it was terminated due to * {@link BucketVisitor#visit} returning false */ public <T> boolean accept(BucketVisitor<T> visitor, T aggregate) { final ProxyBucketRegion[] bucs = buckets; Objects.requireNonNull(bucs); for (ProxyBucketRegion pbr : bucs) { if (!visitor.visit(this, pbr, aggregate)) { return false; } } return true; } public PartitionedRegion getPartitionedRegion() { return (PartitionedRegion) getAdvisee(); } /** * Update or create a bucket's meta-data If this advisor has not completed initialization, upon * return the profile will be enqueued for processing during initialization, otherwise the profile * will be immediately processed. This architecture limits the blockage of threads during * initialization. * * @param bucketId the unique identifier of the bucket * @param profile the bucket meta-data from a particular member with the bucket */ void putBucketProfile(int bucketId, BucketProfile profile) { synchronized (preInitQueueMonitor) { if (preInitQueue != null) { // Queue profile during pre-initialization QueuedBucketProfile qbf = new QueuedBucketProfile(bucketId, profile); preInitQueue.add(qbf); return; } } // Directly process profile post-initialization getBucket(bucketId).getBucketAdvisor().putProfile(profile); } static class QueuedBucketProfile { protected final int bucketId; final BucketProfile bucketProfile; /** true means that this member has departed the view */ protected final boolean memberDeparted; /** true means that this profile needs to be removed */ final boolean isRemoval; /** true means that the peer crashed */ protected final boolean crashed; /** * true means that this QueuedBucketProfile was created because of MembershipListener invocation */ final boolean fromMembershipListener; protected final boolean destroyed; protected final InternalDistributedMember memberId; final int[] serials; /** * Queue up an addition * * @param bId the bucket being added * @param p the profile to add */ QueuedBucketProfile(int bId, BucketProfile p) { bucketId = bId; bucketProfile = p; isRemoval = false; crashed = false; memberDeparted = false; memberId = null; serials = null; destroyed = false; fromMembershipListener = false; } /** * Queue up a removal due to member leaving the view * * @param mbr the member being removed */ QueuedBucketProfile(InternalDistributedMember mbr, boolean crashed, boolean destroyed, boolean fromMembershipListener) { bucketId = 0; bucketProfile = null; isRemoval = true; this.crashed = crashed; memberDeparted = true; memberId = mbr; serials = null; this.destroyed = destroyed; this.fromMembershipListener = fromMembershipListener; } /** * Queue up a removal due to region destroy * * @param mbr the member being removed * @param serials the serials it had */ QueuedBucketProfile(InternalDistributedMember mbr, int[] serials, boolean destroyed) { bucketId = 0; bucketProfile = null; isRemoval = true; crashed = false; memberDeparted = false; memberId = mbr; this.serials = serials; this.destroyed = destroyed; fromMembershipListener = false; } } public Set<InternalDistributedMember> adviseBucketProfileExchange() { return adviseDataStore(); } public long adviseTotalMemoryAllocation() { final AtomicLong total = new AtomicLong(); adviseFilter(profile -> { // probably not needed as all profiles for a partitioned region are Partition profiles if (profile instanceof PartitionProfile) { PartitionProfile p = (PartitionProfile) profile; total.addAndGet(p.localMaxMemory); } return false; }); return total.get(); } /** * Returns the total number of buckets created anywhere in the distributed system for this * partitioned region. * * @return the total number of buckets created anywhere for this PR */ public int getCreatedBucketsCount() { final ProxyBucketRegion[] bucs = buckets; if (bucs == null) { return 0; } int createdBucketsCount = 0; for (ProxyBucketRegion buc : bucs) { if (buc.getBucketOwnersCount() > 0) { createdBucketsCount++; } } return createdBucketsCount; } /** * Returns a possibly null list of this advisor's real bucket profiles. A real bucket profile is * one that for a bucket that actually has storage in this vm. * * @return a list of BucketProfileAndId instances; may be null * @since GemFire 5.5 */ public ArrayList getBucketRegionProfiles() { final ProxyBucketRegion[] bucs = buckets; if (bucs == null) { return null; } ArrayList<BucketProfileAndId> result = new ArrayList<>(bucs.length); for (int i = 0; i < bucs.length; i++) { // Fix for 41436 - we need to include buckets that are still initializing here // we must start including buckets in this list *before* those buckets exchange // profiles. BucketRegion br = bucs[i].getCreatedBucketRegion(); if (br != null) { result.add(new BucketProfileAndId(br.getProfile(), i)); } } if (result.size() == 0) { result = null; } return result; } /** * Takes a list of BucketProfileAndId and adds them to thsi advisors proxy buckets. * * @since GemFire 5.5 */ public void putBucketRegionProfiles(ArrayList<BucketProfileAndId> l) { for (BucketProfileAndId bp : l) { int id = bp.getId(); getBucket(id).getBucketAdvisor().putProfile(bp.getBucketProfile()); } } /** * return true if the given member has this advisor's partitioned region */ public boolean hasPartitionedRegion(InternalDistributedMember profileId) { if (getDistributionManager().getId().equals(profileId)) { return true; } return (getProfile(profileId) != null); } @Override protected void profileRemoved(Profile profile) { if (logger.isDebugEnabled()) { logger.debug("RA: removing profile {}", profile); } if (getAdvisee() instanceof PartitionedRegion) { ((PartitionedRegion) getAdvisee()).removeCriticalMember(profile.peerMemberId); } if (buckets != null) { for (ProxyBucketRegion bucket : buckets) { bucket.getBucketAdvisor().checkForLostPrimaryElector(profile); } } } public static class BucketProfileAndId implements DataSerializable { private static final long serialVersionUID = 332892607792421553L; /* final */ private int id; // bid = bucket id /* final */ private BucketProfile bp; private boolean isServerBucketProfile = false; public BucketProfileAndId(Profile bp, int id) { this.id = id; this.bp = (BucketProfile) bp; if (bp instanceof ServerBucketProfile) isServerBucketProfile = true; } public BucketProfileAndId() {} public int getId() { return id; } BucketProfile getBucketProfile() { return bp; } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { id = in.readInt(); isServerBucketProfile = in.readBoolean(); if (isServerBucketProfile) bp = new ServerBucketProfile(); else bp = new BucketProfile(); InternalDataSerializer.invokeFromData(bp, in); } @Override public void toData(DataOutput out) throws IOException { out.writeInt(id); out.writeBoolean(isServerBucketProfile); InternalDataSerializer.invokeToData(bp, out); } @Override public String toString() { return "BucketProfileAndId (profile=" + bp + "; id=" + id + ")"; } } // profile listener to monitor remote member unexpected leave during shutdownAll private class ProfileShutdownListener implements ProfileListener { ProfileShutdownListener() { } private boolean profileChanged = false; void waitForChange() { Region pr = getPartitionedRegion(); synchronized (this) { while (!profileChanged && pr != null && !pr.isDestroyed()) { // the advisee might have been destroyed due to initialization failure try { wait(1000); } catch (InterruptedException ignored) { } } profileChanged = false; } } @Override public void profileCreated(Profile profile) { profileUpdated(profile); } @Override public void profileRemoved(Profile profile, boolean regionDestroyed) { // if a profile is gone, notify synchronized (this) { profileChanged = true; notifyAll(); } } @Override public void profileUpdated(Profile profile) { // when updated, notify the loop in GFC to check the list again synchronized (this) { profileChanged = true; notifyAll(); } } } }
GEODE-7133: Remove Assert calls. (#3977)
geode-core/src/main/java/org/apache/geode/internal/cache/partitioned/RegionAdvisor.java
GEODE-7133: Remove Assert calls. (#3977)
<ide><path>eode-core/src/main/java/org/apache/geode/internal/cache/partitioned/RegionAdvisor.java <ide> import org.apache.geode.distributed.internal.DistributionConfig; <ide> import org.apache.geode.distributed.internal.ProfileListener; <ide> import org.apache.geode.distributed.internal.membership.InternalDistributedMember; <del>import org.apache.geode.internal.Assert; <ide> import org.apache.geode.internal.InternalDataSerializer; <ide> import org.apache.geode.internal.cache.BucketAdvisor; <ide> import org.apache.geode.internal.cache.BucketAdvisor.BucketProfile; <ide> if (MemoryThresholds.isLowMemoryExceptionDisabled()) { <ide> return; <ide> } <del> assert buckets != null; <del> assert buckets[bucketId] != null; <ide> if (buckets[bucketId].isBucketSick()) { <ide> Set<DistributedMember> sm = buckets[bucketId].getSickMembers(); <ide> if (sm.isEmpty()) { <ide> <ide> @Override <ide> public synchronized boolean putProfile(Profile p) { <del> assert p instanceof CacheProfile; <ide> CacheProfile profile = (CacheProfile) p; <ide> PartitionedRegion pr = getPartitionedRegion(); <ide> if (profile.hasCacheLoader) { <ide> * @return the bucket identified by bucketId <ide> */ <ide> public Bucket getBucket(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> ProxyBucketRegion pbr = buckets[bucketId]; <ide> Bucket ret = pbr.getHostedBucketRegion(); <ide> if (ret != null) { <ide> * @return the bucket advisor identified by bucketId <ide> */ <ide> public BucketAdvisor getBucketAdvisor(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> ProxyBucketRegion pbr = buckets[bucketId]; <ide> Bucket ret = pbr.getHostedBucketRegion(); <ide> if (ret != null) { <ide> } <ide> <ide> public Map<Integer, BucketAdvisor> getAllBucketAdvisors() { <del> Assert.assertTrue(buckets != null); <ide> Map<Integer, BucketAdvisor> map = new HashMap<>(); <ide> for (ProxyBucketRegion pbr : buckets) { <ide> Bucket ret = pbr.getHostedBucketRegion(); <ide> * @return the Node managing the primary copy of the bucket <ide> */ <ide> public InternalDistributedMember getPrimaryMemberForBucket(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> Bucket b = buckets[bucketId]; <ide> return b.getBucketAdvisor().getPrimary(); <ide> } <ide> * @return the member, possibly null if no member is available <ide> */ <ide> public InternalDistributedMember getPreferredNode(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> Bucket b = buckets[bucketId]; <ide> return b.getBucketAdvisor().getPreferredNode(); <ide> } <ide> <ide> public boolean isStorageAssignedForBucket(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> return buckets[bucketId].getBucketRedundancy() >= 0; <ide> } <ide> <ide> if (!wait) { <ide> return isStorageAssignedForBucket(bucketId); <ide> } else { <del> Assert.assertTrue(buckets != null); <ide> return buckets[bucketId].getBucketAdvisor().waitForRedundancy(minRedundancy); <ide> } <ide> } <ide> * bucket. <ide> */ <ide> public int getBucketRedundancy(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> return buckets[bucketId].getBucketRedundancy(); <ide> } <ide> <ide> * @return a set of {@link InternalDistributedMember}s that own the bucket <ide> */ <ide> public Set<InternalDistributedMember> getBucketOwners(int bucketId) { <del> Assert.assertTrue(buckets != null); <ide> return buckets[bucketId].getBucketOwners(); <ide> } <ide> <ide> * @return set of Integer bucketIds <ide> */ <ide> public Set<Integer> getBucketSet() { <del> Assert.assertTrue(buckets != null); <ide> return new BucketSet(); <ide> } <ide> <ide> <ide> BucketSet() { <ide> pbrs = buckets; <del> Assert.assertTrue(pbrs != null); <ide> } <ide> <ide> /* <ide> public void incrementBucketCount(Profile p) { <ide> PartitionProfile pp = (PartitionProfile) getProfile(p.getDistributedMember()); <ide> if (pp != null) { <del> Assert.assertTrue(pp.isDataStore); <ide> pp.numBuckets++; <ide> } <ide> } <ide> public void decrementsBucketCount(Profile p) { <ide> PartitionProfile pp = (PartitionProfile) getProfile(p.getDistributedMember()); <ide> if (pp != null) { <del> Assert.assertTrue(pp.isDataStore); <ide> pp.numBuckets--; <ide> if (pp.numBuckets < 0) { <ide> pp.numBuckets = 0; <ide> } <ide> <ide> public void notPrimary(int bucketId, InternalDistributedMember wasPrimary) { <del> Assert.assertTrue(buckets != null); <ide> ProxyBucketRegion b = buckets[bucketId]; <ide> b.getBucketAdvisor().notPrimary(wasPrimary); <ide> } <ide> * @return set of InternalDistributedMember ids <ide> */ <ide> public Set advisePrimaryOwners() { <del> Assert.assertTrue(buckets != null); <ide> ProxyBucketRegion[] bucs = buckets; <ide> HashSet<InternalDistributedMember> hs = new HashSet<>(); <ide> for (int i = 0; i < bucs.length; i++) {
JavaScript
apache-2.0
49751eb5896556b6e70c117a27db9632eb9789d0
0
GageGaskins/osf.io,CenterForOpenScience/osf.io,jmcarp/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,binoculars/osf.io,jinluyuan/osf.io,arpitar/osf.io,jeffreyliu3230/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,njantrania/osf.io,doublebits/osf.io,DanielSBrown/osf.io,baylee-d/osf.io,brandonPurvis/osf.io,zachjanicki/osf.io,crcresearch/osf.io,HarryRybacki/osf.io,chennan47/osf.io,KAsante95/osf.io,Nesiehr/osf.io,jmcarp/osf.io,saradbowman/osf.io,cosenal/osf.io,erinspace/osf.io,sbt9uc/osf.io,laurenrevere/osf.io,sloria/osf.io,mluke93/osf.io,ckc6cz/osf.io,amyshi188/osf.io,mluo613/osf.io,petermalcolm/osf.io,ZobairAlijan/osf.io,lamdnhan/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,njantrania/osf.io,RomanZWang/osf.io,arpitar/osf.io,mattclark/osf.io,jmcarp/osf.io,ticklemepierce/osf.io,fabianvf/osf.io,haoyuchen1992/osf.io,Johnetordoff/osf.io,sbt9uc/osf.io,icereval/osf.io,kwierman/osf.io,himanshuo/osf.io,asanfilippo7/osf.io,njantrania/osf.io,fabianvf/osf.io,SSJohns/osf.io,AndrewSallans/osf.io,cldershem/osf.io,jeffreyliu3230/osf.io,chrisseto/osf.io,himanshuo/osf.io,ZobairAlijan/osf.io,cldershem/osf.io,bdyetton/prettychart,cldershem/osf.io,chrisseto/osf.io,mfraezz/osf.io,kch8qx/osf.io,ckc6cz/osf.io,caseyrygt/osf.io,wearpants/osf.io,jolene-esposito/osf.io,KAsante95/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,cwisecarver/osf.io,leb2dg/osf.io,doublebits/osf.io,acshi/osf.io,Johnetordoff/osf.io,ticklemepierce/osf.io,MerlinZhang/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,kushG/osf.io,hmoco/osf.io,abought/osf.io,alexschiller/osf.io,caseyrollins/osf.io,TomBaxter/osf.io,felliott/osf.io,jolene-esposito/osf.io,revanthkolli/osf.io,mluo613/osf.io,laurenrevere/osf.io,Ghalko/osf.io,billyhunt/osf.io,jmcarp/osf.io,zachjanicki/osf.io,danielneis/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,acshi/osf.io,RomanZWang/osf.io,barbour-em/osf.io,himanshuo/osf.io,revanthkolli/osf.io,reinaH/osf.io,danielneis/osf.io,emetsger/osf.io,GaryKriebel/osf.io,zkraime/osf.io,mfraezz/osf.io,mluo613/osf.io,brandonPurvis/osf.io,reinaH/osf.io,mluke93/osf.io,ticklemepierce/osf.io,sbt9uc/osf.io,jolene-esposito/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,GageGaskins/osf.io,caseyrollins/osf.io,billyhunt/osf.io,jinluyuan/osf.io,caseyrygt/osf.io,kwierman/osf.io,TomHeatwole/osf.io,brandonPurvis/osf.io,cslzchen/osf.io,caneruguz/osf.io,GaryKriebel/osf.io,zamattiac/osf.io,RomanZWang/osf.io,acshi/osf.io,mluo613/osf.io,hmoco/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,dplorimer/osf,caseyrygt/osf.io,dplorimer/osf,jnayak1/osf.io,billyhunt/osf.io,lamdnhan/osf.io,petermalcolm/osf.io,felliott/osf.io,GaryKriebel/osf.io,acshi/osf.io,Nesiehr/osf.io,alexschiller/osf.io,bdyetton/prettychart,SSJohns/osf.io,kch8qx/osf.io,barbour-em/osf.io,zamattiac/osf.io,jnayak1/osf.io,brianjgeiger/osf.io,samanehsan/osf.io,emetsger/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,fabianvf/osf.io,RomanZWang/osf.io,KAsante95/osf.io,doublebits/osf.io,haoyuchen1992/osf.io,DanielSBrown/osf.io,reinaH/osf.io,zamattiac/osf.io,caneruguz/osf.io,caneruguz/osf.io,reinaH/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,sloria/osf.io,pattisdr/osf.io,zachjanicki/osf.io,cslzchen/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,Ghalko/osf.io,billyhunt/osf.io,chennan47/osf.io,binoculars/osf.io,abought/osf.io,caneruguz/osf.io,doublebits/osf.io,sloria/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,jinluyuan/osf.io,petermalcolm/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,alexschiller/osf.io,zkraime/osf.io,baylee-d/osf.io,chrisseto/osf.io,kwierman/osf.io,barbour-em/osf.io,bdyetton/prettychart,samchrisinger/osf.io,mattclark/osf.io,HarryRybacki/osf.io,brianjgeiger/osf.io,kushG/osf.io,cosenal/osf.io,Ghalko/osf.io,samchrisinger/osf.io,ckc6cz/osf.io,MerlinZhang/osf.io,monikagrabowska/osf.io,amyshi188/osf.io,asanfilippo7/osf.io,MerlinZhang/osf.io,jinluyuan/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,kwierman/osf.io,adlius/osf.io,rdhyee/osf.io,TomBaxter/osf.io,chrisseto/osf.io,TomBaxter/osf.io,cosenal/osf.io,icereval/osf.io,rdhyee/osf.io,aaxelb/osf.io,caseyrollins/osf.io,arpitar/osf.io,jeffreyliu3230/osf.io,cwisecarver/osf.io,amyshi188/osf.io,hmoco/osf.io,acshi/osf.io,samanehsan/osf.io,monikagrabowska/osf.io,laurenrevere/osf.io,chennan47/osf.io,amyshi188/osf.io,aaxelb/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,ticklemepierce/osf.io,zkraime/osf.io,rdhyee/osf.io,danielneis/osf.io,TomHeatwole/osf.io,leb2dg/osf.io,felliott/osf.io,lamdnhan/osf.io,RomanZWang/osf.io,cwisecarver/osf.io,kch8qx/osf.io,erinspace/osf.io,adlius/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,asanfilippo7/osf.io,himanshuo/osf.io,mluke93/osf.io,abought/osf.io,lyndsysimon/osf.io,zkraime/osf.io,icereval/osf.io,mluo613/osf.io,abought/osf.io,kushG/osf.io,barbour-em/osf.io,felliott/osf.io,asanfilippo7/osf.io,lamdnhan/osf.io,revanthkolli/osf.io,leb2dg/osf.io,GageGaskins/osf.io,adlius/osf.io,jolene-esposito/osf.io,leb2dg/osf.io,jnayak1/osf.io,pattisdr/osf.io,sbt9uc/osf.io,emetsger/osf.io,KAsante95/osf.io,emetsger/osf.io,danielneis/osf.io,wearpants/osf.io,samanehsan/osf.io,Ghalko/osf.io,haoyuchen1992/osf.io,GageGaskins/osf.io,baylee-d/osf.io,AndrewSallans/osf.io,njantrania/osf.io,arpitar/osf.io,kch8qx/osf.io,cslzchen/osf.io,KAsante95/osf.io,mattclark/osf.io,jeffreyliu3230/osf.io,kushG/osf.io,crcresearch/osf.io,cosenal/osf.io,caseyrygt/osf.io,doublebits/osf.io,zachjanicki/osf.io,lyndsysimon/osf.io,bdyetton/prettychart,TomHeatwole/osf.io,HarryRybacki/osf.io,mluke93/osf.io,lyndsysimon/osf.io,samanehsan/osf.io,aaxelb/osf.io,adlius/osf.io,mfraezz/osf.io,binoculars/osf.io,pattisdr/osf.io,dplorimer/osf,CenterForOpenScience/osf.io,dplorimer/osf,MerlinZhang/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,lyndsysimon/osf.io,revanthkolli/osf.io,ZobairAlijan/osf.io,crcresearch/osf.io,HarryRybacki/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,wearpants/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,kch8qx/osf.io,ckc6cz/osf.io,Nesiehr/osf.io,samchrisinger/osf.io,alexschiller/osf.io,wearpants/osf.io,DanielSBrown/osf.io
///////////////////// // Project JS // ///////////////////// (function($){ window.NodeActions = {}; // Namespace for NodeActions // TODO: move me to the NodeControl or separate NodeActions.forkPointer = function(pointerId, nodeId) { beforeForkNode('/api/v1/' + nodeId + '/fork/before/', function() { // Block page $.osf.block(); // Fork pointer $.ajax({ type: 'post', url: nodeApiUrl + 'pointer/fork/', data: JSON.stringify({'pointerId': pointerId}), contentType: 'application/json', dataType: 'json', success: function(response) { window.location.reload(); }, error: function() { $.osf.unblock(); bootbox.alert('Could not fork link.'); } }); }); }; NodeActions.addonFileRedirect = function(item) { window.location.href = item.params.urls.view; return false; }; $(function(){ $('#newComponent form').on('submit', function(e) { $("#add-component-submit") .attr("disabled", "disabled") .text("Adding"); if ($.trim($("#title").val())==''){ $("#alert").text("The new component title cannot be empty"); $("#add-component-submit") .removeAttr("disabled","disabled") .text("OK"); e.preventDefault(); } else if ($(e.target).find("#title").val().length>200){ $("#alert").text("The new component title cannot be more than 200 characters."); $("#add-component-submit") .removeAttr("disabled","disabled") .text("OK"); e.preventDefault(); } // else{ // $.ajax({ // url: $(e.target).attr("action"), // type:"POST", // timeout:60000, // data:$(e.target).serialize() // }).success(function(){ // location.reload(); // }).fail(function(jqXHR, textStatus, errorThrown){ // if(textStatus==="timeout") { // $("#alert").text("Add component timed out"); //Handle the timeout // }else{ // $("#alert").text('Add component failed'); // } // $("#add-component-submit") // .removeAttr("disabled","disabled") // .text("OK"); // }); // } }); }); NodeActions._openCloseNode = function(nodeId) { var icon = $('#icon-' + nodeId); var body = $('#body-' + nodeId); body.toggleClass('hide'); if ( body.hasClass('hide') ) { icon.removeClass('icon-minus'); icon.addClass('icon-plus'); icon.attr('title', 'More'); } else { icon.removeClass('icon-plus'); icon.addClass('icon-minus'); icon.attr('title', 'Less'); } // Refresh tooltip text icon.tooltip('destroy'); icon.tooltip(); }; NodeActions.reorderChildren = function(idList, elm) { $.ajax({ type: 'POST', url: nodeApiUrl + 'reorder_components/', data: JSON.stringify({'new_list': idList}), contentType: 'application/json', dataType: 'json', fail: function() { $(elm).sortable('cancel'); } }); }; NodeActions.removePointer = function(pointerId, pointerElm) { $.ajax({ type: 'DELETE', url: nodeApiUrl + 'pointer/', data: JSON.stringify({pointerId: pointerId}), contentType: 'application/json', dataType: 'json', success: function(response) { pointerElm.remove(); } }) }; /* refresh rendered file through mfr */ window.FileRenderer = { start: function(url, selector){ this.url = url; this.element = $(selector); this.tries = 0; this.refreshContent = window.setInterval(this.getCachedFromServer.bind(this), 1000); }, getCachedFromServer: function() { var self = this; $.get( self.url, function(data) { if (data) { self.element.html(data); clearInterval(self.refreshContent); } else { self.tries += 1; if(self.tries > 10){ clearInterval(self.refreshContent); self.element.html("Timeout occurred while loading, please refresh the page") } } }); } }; /* Display recent logs for for a node on the project view page. */ NodeActions.openCloseNode = function(nodeId){ var $logs = $('#logs-' + nodeId); if (!$logs.hasClass('active')) { if (!$logs.hasClass('served')) { $.getJSON( $logs.attr('data-uri'), {count: 3}, function(response) { $script(['/static/js/logFeed.js'], function() { var log = new LogFeed($logs, response.logs); }); $logs.addClass('served'); } ); } $logs.addClass('active'); } else { $logs.removeClass('active'); } // Hide/show the html NodeActions._openCloseNode(nodeId); }; $(document).ready(function() { ko.punches.enableAll(); var permissionInfoHtml = '<ul>' + '<li><strong>Read</strong>: View project content and comment</li>' + '<li><strong>Read + Write</strong>: Read privileges plus add and configure components; add and edit content</li>' + '<li><strong>Administrator</strong>: Read and write privileges; manage contributors; delete and register project; public-private settings</li>' + '</ul>'; $('.permission-info').attr( 'data-content', permissionInfoHtml ).popover(); //////////////////// // Event Handlers // //////////////////// $('.remove-pointer').on('click', function() { var $this = $(this); bootbox.confirm( 'Are you sure you want to remove this link? This will not ' + 'remove the project this link refers to.', function(result) { if (result) { var pointerId = $this.attr('data-id'); var pointerElm = $this.closest('.list-group-item'); NodeActions.removePointer(pointerId, pointerElm); } } ) }); $('.citation-toggle').on('click', function() { $(this).closest('.citations').find('.citation-list').slideToggle(); }); // Widgets $('.widget-disable').on('click', function() { var $this = $(this); $.ajax({ url: $this.attr('href'), type: 'POST', contentType: 'application/json', dataType: 'json', complete: function() { window.location = '/' + nodeId + '/'; } }); return false; }); }); }).call(this, jQuery);
website/static/js/project.js
///////////////////// // Project JS // ///////////////////// (function($){ window.NodeActions = {}; // Namespace for NodeActions // TODO: move me to the NodeControl or separate NodeActions.forkPointer = function(pointerId, nodeId) { beforeForkNode('/api/v1/' + nodeId + '/fork/before/', function() { // Block page $.osf.block(); // Fork pointer $.ajax({ type: 'post', url: nodeApiUrl + 'pointer/fork/', data: JSON.stringify({'pointerId': pointerId}), contentType: 'application/json', dataType: 'json', success: function(response) { window.location.reload(); }, error: function() { $.osf.unblock(); bootbox.alert('Could not fork link.'); } }); }); }; NodeActions.addonFileRedirect = function(item) { window.location.href = item.params.urls.view; return false; }; $(function(){ $('#newComponent form').on('submit', function(e) { $("#add-component-submit") .attr("disabled", "disabled") .text("Adding"); if ($.trim($("#title").val())==''){ $("#alert").text("The new component title cannot be empty"); $("#add-component-submit") .removeAttr("disabled","disabled") .text("OK"); e.preventDefault(); } else if ($(e.target).find("#title").val().length>200){ $("#alert").text("The new component title cannot be more than 200 characters."); $("#add-component-submit") .removeAttr("disabled","disabled") .text("OK"); e.preventDefault(); } // else{ // $.ajax({ // url: $(e.target).attr("action"), // type:"POST", // timeout:60000, // data:$(e.target).serialize() // }).success(function(){ // location.reload(); // }).fail(function(jqXHR, textStatus, errorThrown){ // if(textStatus==="timeout") { // $("#alert").text("Add component timed out"); //Handle the timeout // }else{ // $("#alert").text('Add component failed'); // } // $("#add-component-submit") // .removeAttr("disabled","disabled") // .text("OK"); // }); // } }); }); NodeActions._openCloseNode = function(nodeId) { var icon = $('#icon-' + nodeId); var body = $('#body-' + nodeId); body.toggleClass('hide'); if ( body.hasClass('hide') ) { icon.removeClass('icon-minus'); icon.addClass('icon-plus'); icon.attr('title', 'More'); } else { icon.removeClass('icon-plus'); icon.addClass('icon-minus'); icon.attr('title', 'Less'); } // Refresh tooltip text icon.tooltip('destroy'); icon.tooltip(); }; NodeActions.reorderChildren = function(idList, elm) { $.ajax({ type: 'POST', url: nodeApiUrl + 'reorder_components/', data: JSON.stringify({'new_list': idList}), contentType: 'application/json', dataType: 'json', fail: function() { $(elm).sortable('cancel'); } }); }; NodeActions.removePointer = function(pointerId, pointerElm) { $.ajax({ type: 'DELETE', url: nodeApiUrl + 'pointer/', data: JSON.stringify({pointerId: pointerId}), contentType: 'application/json', dataType: 'json', success: function(response) { pointerElm.remove(); } }) }; /* refresh rendered file through mfr */ window.FileRenderer = { start: function(url, selector){ this.url = url; this.element = $(selector); this.tries = 0; this.refreshContent = window.setInterval(this.getCachedFromServer.bind(this), 1000); }, getCachedFromServer: function() { var self = this; $.get( self.url, function(data) { if (data) { self.element.html(data); clearInterval(self.refreshContent); } else { self.tries += 1; if(self.tries > 10){ clearInterval(self.refreshContent); self.element.html("Timeout occurred while loading, please refresh the page") } } }); } }; $script(['/static/js/logFeed.js'], 'logFeed'); /* Display recent logs for for a node on the project view page. */ NodeActions.openCloseNode = function(nodeId){ var $logs = $('#logs-' + nodeId); if (!$logs.hasClass('active')) { if (!$logs.hasClass('served')) { $.getJSON( $logs.attr('data-uri'), {count: 3}, function(response) { $script.ready('logFeed', function() { var logFeed = new LogFeed($logs, response.logs); }); $logs.addClass('served'); } ); } $logs.addClass('active'); } else { $logs.removeClass('active'); } // Hide/show the html NodeActions._openCloseNode(nodeId); }; $(document).ready(function() { ko.punches.enableAll(); var permissionInfoHtml = '<ul>' + '<li><strong>Read</strong>: View project content and comment</li>' + '<li><strong>Read + Write</strong>: Read privileges plus add and configure components; add and edit content</li>' + '<li><strong>Administrator</strong>: Read and write privileges; manage contributors; delete and register project; public-private settings</li>' + '</ul>'; $('.permission-info').attr( 'data-content', permissionInfoHtml ).popover(); //////////////////// // Event Handlers // //////////////////// $('.remove-pointer').on('click', function() { var $this = $(this); bootbox.confirm( 'Are you sure you want to remove this link? This will not ' + 'remove the project this link refers to.', function(result) { if (result) { var pointerId = $this.attr('data-id'); var pointerElm = $this.closest('.list-group-item'); NodeActions.removePointer(pointerId, pointerElm); } } ) }); $('.citation-toggle').on('click', function() { $(this).closest('.citations').find('.citation-list').slideToggle(); }); // Widgets $('.widget-disable').on('click', function() { var $this = $(this); $.ajax({ url: $this.attr('href'), type: 'POST', contentType: 'application/json', dataType: 'json', complete: function() { window.location = '/' + nodeId + '/'; } }); return false; }); }); }).call(this, jQuery);
improve
website/static/js/project.js
improve
<ide><path>ebsite/static/js/project.js <ide> } <ide> }; <ide> <del>$script(['/static/js/logFeed.js'], 'logFeed'); <add> <ide> /* <ide> Display recent logs for for a node on the project view page. <ide> */ <ide> $logs.attr('data-uri'), <ide> {count: 3}, <ide> function(response) { <del> $script.ready('logFeed', function() { <del> var logFeed = new LogFeed($logs, response.logs); <add> $script(['/static/js/logFeed.js'], function() { <add> var log = new LogFeed($logs, response.logs); <ide> }); <ide> $logs.addClass('served'); <ide> }
Java
apache-2.0
cb4d21a0ecbf00b1b113420580fead96077f15ff
0
gbif/crawler
package org.gbif.crawler.pipelines.indexing; import java.io.IOException; import java.util.Date; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.gbif.api.model.registry.Dataset; import org.gbif.api.service.registry.DatasetService; import org.gbif.common.messaging.AbstractMessageCallback; import org.gbif.common.messaging.api.MessagePublisher; import org.gbif.common.messaging.api.messages.PipelinesIndexedMessage; import org.gbif.common.messaging.api.messages.PipelinesInterpretedMessage; import org.gbif.crawler.pipelines.HdfsUtils; import org.gbif.crawler.pipelines.PipelineCallback; import org.gbif.crawler.pipelines.PipelineCallback.Steps; import org.gbif.crawler.pipelines.dwca.DwcaToAvroConfiguration; import org.gbif.pipelines.common.PipelinesVariables.Metrics; import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Interpretation; import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Interpretation.RecordType; import org.apache.curator.framework.CuratorFramework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import static org.gbif.crawler.constants.PipelinesNodePaths.INTERPRETED_TO_INDEX; import static com.google.common.base.Preconditions.checkNotNull; /** * Callback which is called when the {@link PipelinesInterpretedMessage} is received. * <p> * The main method is {@link IndexingCallback#handleMessage} */ public class IndexingCallback extends AbstractMessageCallback<PipelinesInterpretedMessage> { private static final Logger LOG = LoggerFactory.getLogger(IndexingCallback.class); private final IndexingConfiguration config; private final MessagePublisher publisher; private final DatasetService datasetService; private final CuratorFramework curator; IndexingCallback(IndexingConfiguration config, MessagePublisher publisher, DatasetService datasetService, CuratorFramework curator) { this.curator = checkNotNull(curator, "curator cannot be null"); this.config = checkNotNull(config, "config cannot be null"); this.datasetService = checkNotNull(datasetService, "config cannot be null"); this.publisher = publisher; } /** * Handles a MQ {@link PipelinesInterpretedMessage} message */ @Override public void handleMessage(PipelinesInterpretedMessage message) { LOG.info("Message handler began - {}", message); if (!isMessageCorrect(message)) { return; } UUID datasetId = message.getDatasetUuid(); Set<String> steps = message.getPipelineSteps(); Runnable runnable = createRunnable(message); // Message callback handler, updates zookeeper info, runs process logic and sends next MQ message PipelineCallback.create() .incomingMessage(message) .outgoingMessage(new PipelinesIndexedMessage(datasetId, message.getAttempt(), steps, null)) .curator(curator) .zkRootElementPath(INTERPRETED_TO_INDEX) .pipelinesStepName(Steps.INTERPRETED_TO_INDEX.name()) .publisher(publisher) .runnable(runnable) .build() .handleMessage(); LOG.info("Message handler ended - {}", message); } /** * Only correct messages can be handled, by now is only messages with the same runner as runner in service config * {@link IndexingConfiguration#processRunner} */ private boolean isMessageCorrect(PipelinesInterpretedMessage message) { if (Strings.isNullOrEmpty(message.getRunner())) { throw new IllegalArgumentException("Runner can't be null or empty " + message.toString()); } return config.processRunner.equals(message.getRunner()); } /** * Main message processing logic, creates a terminal java process, which runs interpreted-to-index pipeline */ private Runnable createRunnable(PipelinesInterpretedMessage message) { return () -> { try { String datasetId = message.getDatasetUuid().toString(); String attempt = Integer.toString(message.getAttempt()); long recordsNumber = getRecordNumber(message); String indexName = computeIndexName(datasetId, attempt, recordsNumber); String indexAlias = indexName.startsWith(datasetId) ? datasetId + "," + config.indexAlias : config.indexAlias; int numberOfShards = computeNumberOfShards(indexName, recordsNumber); int sparkParallelism = computeSparkParallelism(datasetId, attempt); int sparkExecutorNumbers = computeSparkExecutorNumbers(recordsNumber); String sparkExecutorMemory = computeSparkExecutorMemory(recordsNumber, sparkExecutorNumbers); // Assembles a terminal java process and runs it int exitValue = ProcessRunnerBuilder.create() .config(config) .message(message) .sparkParallelism(sparkParallelism) .sparkExecutorMemory(sparkExecutorMemory) .sparkExecutorNumbers(sparkExecutorNumbers) .esIndexName(indexName) .esAlias(indexAlias) .esShardsNumber(numberOfShards) .build() .start() .waitFor(); if (exitValue != 0) { LOG.error("Process has been finished with exit value - {}, dataset - {}_{}", exitValue, datasetId, attempt); } else { LOG.info("Process has been finished with exit value - {}, dataset - {}_{}", exitValue, datasetId, attempt); } } catch (InterruptedException | IOException ex) { LOG.error(ex.getMessage(), ex); throw new IllegalStateException("Failed indexing on " + message.getDatasetUuid(), ex); } }; } /** * Computes the number of thread for spark.default.parallelism, top limit is config.sparkParallelismMax */ private int computeSparkParallelism(String datasetId, String attempt) throws IOException { // Chooses a runner type by calculating number of files String basic = RecordType.BASIC.name().toLowerCase(); String directoryName = Interpretation.DIRECTORY_NAME; String basicPath = String.join("/", config.repositoryPath, datasetId, attempt, directoryName, basic); int count = HdfsUtils.getfileCount(basicPath, config.hdfsSiteConfig); count *= 2; // 2 Times more threads than files return count > config.sparkParallelismMax ? config.sparkParallelismMax : count; } /** * Computes the memory for executor in Gb, where min is config.sparkExecutorMemoryGbMin and * max is config.sparkExecutorMemoryGbMax * <p> * 65_536d is found empirically salt */ private String computeSparkExecutorMemory(long recordsNumber, int sparkExecutorNumbers) { int memoryGb = (int) Math.ceil(recordsNumber / (double) sparkExecutorNumbers / 65_536d); memoryGb = memoryGb < config.sparkExecutorMemoryGbMin ? config.sparkExecutorMemoryGbMin : memoryGb > config.sparkExecutorMemoryGbMax ? config.sparkExecutorMemoryGbMax : memoryGb; return memoryGb + "G"; } /** * Computes the numbers of executors, where min is config.sparkExecutorNumbersMin and * max is config.sparkExecutorNumbersMax * <p> * 500_000d is records per executor */ private int computeSparkExecutorNumbers(long recordsNumber) { int sparkExecutorNumbers = (int) Math.ceil(recordsNumber / 500_000d); return sparkExecutorNumbers < config.sparkExecutorNumbersMin ? config.sparkExecutorNumbersMin : sparkExecutorNumbers > config.sparkExecutorNumbersMax ? config.sparkExecutorNumbersMax : sparkExecutorNumbers; } /** * Computes the name for ES index: * Case 1 - Independent index for datasets where number of records more than config.indexIndepRecord * Case 2 - Default static index name for datasets where last changed date more than * config.indexDefStaticDateDurationDd * Case 3 - Default dynamic index name for all other datasets */ private String computeIndexName(String datasetId, String attempt, long recordsNumber) { // Independent index for datasets where number of records more than config.indexIndepRecord String idxName; if (recordsNumber >= config.indexIndepRecord) { idxName = datasetId + "_" + attempt; LOG.info("ES Index name - {}, recordsNumber - {}, config.indexIndepRecord - {}", idxName, recordsNumber, config.indexIndepRecord); return idxName; } // Default static index name for datasets where last changed date more than config.indexDefStaticDateDurationDd Date lastChangedDate = getLastChangedDate(datasetId); long diffInMillies = Math.abs(new Date().getTime() - lastChangedDate.getTime()); long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); if (diff >= config.indexDefStaticDateDurationDd) { idxName = config.indexDefStaticName; LOG.info("ES Index name - {}, lastChangedDate - {}, diff days - {}", idxName, lastChangedDate, diff); return idxName; } // Default dynamic index name for all other datasets idxName = config.indexDefDynamicName; LOG.info("ES Index name - {}, lastChangedDate - {}, diff days - {}", idxName, lastChangedDate, diff); return idxName; } private int computeNumberOfShards(String indexName, long recordsNumber) { if (indexName.equals(config.indexDefDynamicName)) { return config.indexDefDynamicShardNumber; } if (indexName.equals(config.indexDefStaticName)) { return config.indexDefStaticNameShardNumber; } return (int) Math.ceil((double) recordsNumber / (double) config.indexRecordsPerShard); } /** * Uses Registry to ask the last changed date for a dataset */ private Date getLastChangedDate(String datasetId) { Dataset dataset = datasetService.get(UUID.fromString(datasetId)); return dataset.getModified(); } /** * Reads number of records from a archive-to-avro metadata file, verbatim-to-interpreted contains attempted records * count, which is not accurate enough */ private long getRecordNumber(PipelinesInterpretedMessage message) throws IOException { String datasetId = message.getDatasetUuid().toString(); String attempt = Integer.toString(message.getAttempt()); String metaFileName = new DwcaToAvroConfiguration().metaFileName; String metaPath = String.join("/", config.repositoryPath, datasetId, attempt, metaFileName); String recordsNumber = HdfsUtils.getValueByKey(config.hdfsSiteConfig, metaPath, Metrics.ARCHIVE_TO_ER_COUNT); if (recordsNumber == null || recordsNumber.isEmpty()) { if (message.getNumberOfRecords() != null) { return message.getNumberOfRecords(); } else { throw new IllegalArgumentException( "Please check archive-to-avro metadata yaml file or message records number, recordsNumber can't be null or empty!"); } } return Long.parseLong(recordsNumber); } }
crawler-cli/src/main/java/org/gbif/crawler/pipelines/indexing/IndexingCallback.java
package org.gbif.crawler.pipelines.indexing; import java.io.IOException; import java.util.Date; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.gbif.api.model.registry.Dataset; import org.gbif.api.service.registry.DatasetService; import org.gbif.common.messaging.AbstractMessageCallback; import org.gbif.common.messaging.api.MessagePublisher; import org.gbif.common.messaging.api.messages.PipelinesIndexedMessage; import org.gbif.common.messaging.api.messages.PipelinesInterpretedMessage; import org.gbif.crawler.pipelines.HdfsUtils; import org.gbif.crawler.pipelines.PipelineCallback; import org.gbif.crawler.pipelines.PipelineCallback.Steps; import org.gbif.crawler.pipelines.dwca.DwcaToAvroConfiguration; import org.gbif.pipelines.common.PipelinesVariables.Metrics; import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Interpretation; import org.gbif.pipelines.common.PipelinesVariables.Pipeline.Interpretation.RecordType; import org.apache.curator.framework.CuratorFramework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import static org.gbif.crawler.constants.PipelinesNodePaths.INTERPRETED_TO_INDEX; import static com.google.common.base.Preconditions.checkNotNull; /** * Callback which is called when the {@link PipelinesInterpretedMessage} is received. * <p> * The main method is {@link IndexingCallback#handleMessage} */ public class IndexingCallback extends AbstractMessageCallback<PipelinesInterpretedMessage> { private static final Logger LOG = LoggerFactory.getLogger(IndexingCallback.class); private final IndexingConfiguration config; private final MessagePublisher publisher; private final DatasetService datasetService; private final CuratorFramework curator; IndexingCallback(IndexingConfiguration config, MessagePublisher publisher, DatasetService datasetService, CuratorFramework curator) { this.curator = checkNotNull(curator, "curator cannot be null"); this.config = checkNotNull(config, "config cannot be null"); this.datasetService = checkNotNull(datasetService, "config cannot be null"); this.publisher = publisher; } /** * Handles a MQ {@link PipelinesInterpretedMessage} message */ @Override public void handleMessage(PipelinesInterpretedMessage message) { LOG.info("Message handler began - {}", message); if (!isMessageCorrect(message)) { return; } UUID datasetId = message.getDatasetUuid(); Set<String> steps = message.getPipelineSteps(); Runnable runnable = createRunnable(message); // Message callback handler, updates zookeeper info, runs process logic and sends next MQ message PipelineCallback.create() .incomingMessage(message) .outgoingMessage(new PipelinesIndexedMessage(datasetId, message.getAttempt(), steps, null)) .curator(curator) .zkRootElementPath(INTERPRETED_TO_INDEX) .pipelinesStepName(Steps.INTERPRETED_TO_INDEX.name()) .publisher(publisher) .runnable(runnable) .build() .handleMessage(); LOG.info("Message handler ended - {}", message); } /** * Only correct messages can be handled, by now is only messages with the same runner as runner in service config * {@link IndexingConfiguration#processRunner} */ private boolean isMessageCorrect(PipelinesInterpretedMessage message) { if (Strings.isNullOrEmpty(message.getRunner())) { throw new IllegalArgumentException("Runner can't be null or empty " + message.toString()); } return config.processRunner.equals(message.getRunner()); } /** * Main message processing logic, creates a terminal java process, which runs interpreted-to-index pipeline */ private Runnable createRunnable(PipelinesInterpretedMessage message) { return () -> { try { String datasetId = message.getDatasetUuid().toString(); String attempt = Integer.toString(message.getAttempt()); long recordsNumber = getRecordNumber(message); String indexName = computeIndexName(datasetId, attempt, recordsNumber); String indexAlias = indexName.startsWith(datasetId) ? datasetId + "," + config.indexAlias : ""; int numberOfShards = computeNumberOfShards(indexName, recordsNumber); int sparkParallelism = computeSparkParallelism(datasetId, attempt); int sparkExecutorNumbers = computeSparkExecutorNumbers(recordsNumber); String sparkExecutorMemory = computeSparkExecutorMemory(recordsNumber, sparkExecutorNumbers); // Assembles a terminal java process and runs it int exitValue = ProcessRunnerBuilder.create() .config(config) .message(message) .sparkParallelism(sparkParallelism) .sparkExecutorMemory(sparkExecutorMemory) .sparkExecutorNumbers(sparkExecutorNumbers) .esIndexName(indexName) .esAlias(indexAlias) .esShardsNumber(numberOfShards) .build() .start() .waitFor(); if (exitValue != 0) { LOG.error("Process has been finished with exit value - {}, dataset - {}_{}", exitValue, datasetId, attempt); } else { LOG.info("Process has been finished with exit value - {}, dataset - {}_{}", exitValue, datasetId, attempt); } } catch (InterruptedException | IOException ex) { LOG.error(ex.getMessage(), ex); throw new IllegalStateException("Failed indexing on " + message.getDatasetUuid(), ex); } }; } /** * Computes the number of thread for spark.default.parallelism, top limit is config.sparkParallelismMax */ private int computeSparkParallelism(String datasetId, String attempt) throws IOException { // Chooses a runner type by calculating number of files String basic = RecordType.BASIC.name().toLowerCase(); String directoryName = Interpretation.DIRECTORY_NAME; String basicPath = String.join("/", config.repositoryPath, datasetId, attempt, directoryName, basic); int count = HdfsUtils.getfileCount(basicPath, config.hdfsSiteConfig); count *= 2; // 2 Times more threads than files return count > config.sparkParallelismMax ? config.sparkParallelismMax : count; } /** * Computes the memory for executor in Gb, where min is config.sparkExecutorMemoryGbMin and * max is config.sparkExecutorMemoryGbMax * <p> * 65_536d is found empirically salt */ private String computeSparkExecutorMemory(long recordsNumber, int sparkExecutorNumbers) { int memoryGb = (int) Math.ceil(recordsNumber / (double) sparkExecutorNumbers / 65_536d); memoryGb = memoryGb < config.sparkExecutorMemoryGbMin ? config.sparkExecutorMemoryGbMin : memoryGb > config.sparkExecutorMemoryGbMax ? config.sparkExecutorMemoryGbMax : memoryGb; return memoryGb + "G"; } /** * Computes the numbers of executors, where min is config.sparkExecutorNumbersMin and * max is config.sparkExecutorNumbersMax * <p> * 500_000d is records per executor */ private int computeSparkExecutorNumbers(long recordsNumber) { int sparkExecutorNumbers = (int) Math.ceil(recordsNumber / 500_000d); return sparkExecutorNumbers < config.sparkExecutorNumbersMin ? config.sparkExecutorNumbersMin : sparkExecutorNumbers > config.sparkExecutorNumbersMax ? config.sparkExecutorNumbersMax : sparkExecutorNumbers; } /** * Computes the name for ES index: * Case 1 - Independent index for datasets where number of records more than config.indexIndepRecord * Case 2 - Default static index name for datasets where last changed date more than * config.indexDefStaticDateDurationDd * Case 3 - Default dynamic index name for all other datasets */ private String computeIndexName(String datasetId, String attempt, long recordsNumber) { // Independent index for datasets where number of records more than config.indexIndepRecord String idxName; if (recordsNumber >= config.indexIndepRecord) { idxName = datasetId + "_" + attempt; LOG.info("ES Index name - {}, recordsNumber - {}, config.indexIndepRecord - {}", idxName, recordsNumber, config.indexIndepRecord); return idxName; } // Default static index name for datasets where last changed date more than config.indexDefStaticDateDurationDd Date lastChangedDate = getLastChangedDate(datasetId); long diffInMillies = Math.abs(new Date().getTime() - lastChangedDate.getTime()); long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); if (diff >= config.indexDefStaticDateDurationDd) { idxName = config.indexDefStaticName; LOG.info("ES Index name - {}, lastChangedDate - {}, diff days - {}", idxName, lastChangedDate, diff); return idxName; } // Default dynamic index name for all other datasets idxName = config.indexDefDynamicName; LOG.info("ES Index name - {}, lastChangedDate - {}, diff days - {}", idxName, lastChangedDate, diff); return idxName; } private int computeNumberOfShards(String indexName, long recordsNumber) { if (indexName.equals(config.indexDefDynamicName)) { return config.indexDefDynamicShardNumber; } if (indexName.equals(config.indexDefStaticName)) { return config.indexDefStaticNameShardNumber; } return (int) Math.ceil((double) recordsNumber / (double) config.indexRecordsPerShard); } /** * Uses Registry to ask the last changed date for a dataset */ private Date getLastChangedDate(String datasetId) { Dataset dataset = datasetService.get(UUID.fromString(datasetId)); return dataset.getModified(); } /** * Reads number of records from a archive-to-avro metadata file, verbatim-to-interpreted contains attempted records * count, which is not accurate enough */ private long getRecordNumber(PipelinesInterpretedMessage message) throws IOException { String datasetId = message.getDatasetUuid().toString(); String attempt = Integer.toString(message.getAttempt()); String metaFileName = new DwcaToAvroConfiguration().metaFileName; String metaPath = String.join("/", config.repositoryPath, datasetId, attempt, metaFileName); String recordsNumber = HdfsUtils.getValueByKey(config.hdfsSiteConfig, metaPath, Metrics.ARCHIVE_TO_ER_COUNT); if (recordsNumber == null || recordsNumber.isEmpty()) { if (message.getNumberOfRecords() != null) { return message.getNumberOfRecords(); } else { throw new IllegalArgumentException( "Please check archive-to-avro metadata yaml file or message records number, recordsNumber can't be null or empty!"); } } return Long.parseLong(recordsNumber); } }
change to always pass the alias to indexing pipeline
crawler-cli/src/main/java/org/gbif/crawler/pipelines/indexing/IndexingCallback.java
change to always pass the alias to indexing pipeline
<ide><path>rawler-cli/src/main/java/org/gbif/crawler/pipelines/indexing/IndexingCallback.java <ide> long recordsNumber = getRecordNumber(message); <ide> <ide> String indexName = computeIndexName(datasetId, attempt, recordsNumber); <del> String indexAlias = indexName.startsWith(datasetId) ? datasetId + "," + config.indexAlias : ""; <add> String indexAlias = indexName.startsWith(datasetId) ? datasetId + "," + config.indexAlias : config.indexAlias; <ide> int numberOfShards = computeNumberOfShards(indexName, recordsNumber); <ide> int sparkParallelism = computeSparkParallelism(datasetId, attempt); <ide> int sparkExecutorNumbers = computeSparkExecutorNumbers(recordsNumber);
Java
mit
67ce74d4e751054abccb724ab2425d0c7e2b1fb3
0
stephenc/jenkins,jenkinsci/jenkins,liupugong/jenkins,jpederzolli/jenkins-1,scoheb/jenkins,jcarrothers-sap/jenkins,iterate/coding-dojo,synopsys-arc-oss/jenkins,stephenc/jenkins,CodeShane/jenkins,samatdav/jenkins,luoqii/jenkins,SenolOzer/jenkins,v1v/jenkins,ikedam/jenkins,arunsingh/jenkins,batmat/jenkins,wuwen5/jenkins,dennisjlee/jenkins,MichaelPranovich/jenkins_sc,tangkun75/jenkins,fbelzunc/jenkins,ns163/jenkins,msrb/jenkins,mdonohue/jenkins,abayer/jenkins,mattclark/jenkins,Ykus/jenkins,AustinKwang/jenkins,rashmikanta-1984/jenkins,hashar/jenkins,NehemiahMi/jenkins,albers/jenkins,brunocvcunha/jenkins,ydubreuil/jenkins,rsandell/jenkins,samatdav/jenkins,akshayabd/jenkins,everyonce/jenkins,6WIND/jenkins,goldchang/jenkins,rsandell/jenkins,jtnord/jenkins,lindzh/jenkins,bpzhang/jenkins,liorhson/jenkins,soenter/jenkins,mpeltonen/jenkins,FTG-003/jenkins,Krasnyanskiy/jenkins,protazy/jenkins,gorcz/jenkins,albers/jenkins,sathiya-mit/jenkins,mrobinet/jenkins,Vlatombe/jenkins,ChrisA89/jenkins,Vlatombe/jenkins,hplatou/jenkins,lvotypko/jenkins3,akshayabd/jenkins,SebastienGllmt/jenkins,maikeffi/hudson,protazy/jenkins,huybrechts/hudson,hashar/jenkins,nandan4/Jenkins,Wilfred/jenkins,lvotypko/jenkins3,pjanouse/jenkins,amuniz/jenkins,jcsirot/jenkins,godfath3r/jenkins,vlajos/jenkins,maikeffi/hudson,everyonce/jenkins,chbiel/jenkins,huybrechts/hudson,jzjzjzj/jenkins,rsandell/jenkins,lordofthejars/jenkins,rsandell/jenkins,stephenc/jenkins,olivergondza/jenkins,jhoblitt/jenkins,lordofthejars/jenkins,scoheb/jenkins,mrobinet/jenkins,kohsuke/hudson,svanoort/jenkins,tfennelly/jenkins,rashmikanta-1984/jenkins,aquarellian/jenkins,singh88/jenkins,damianszczepanik/jenkins,morficus/jenkins,MarkEWaite/jenkins,msrb/jenkins,ydubreuil/jenkins,hemantojhaa/jenkins,thomassuckow/jenkins,MadsNielsen/jtemp,samatdav/jenkins,dbroady1/jenkins,MarkEWaite/jenkins,azweb76/jenkins,kzantow/jenkins,luoqii/jenkins,bkmeneguello/jenkins,lvotypko/jenkins,hplatou/jenkins,ChrisA89/jenkins,gusreiber/jenkins,pselle/jenkins,SenolOzer/jenkins,lvotypko/jenkins3,dariver/jenkins,jenkinsci/jenkins,hudson/hudson-2.x,jpbriend/jenkins,Ykus/jenkins,stefanbrausch/hudson-main,MichaelPranovich/jenkins_sc,intelchen/jenkins,albers/jenkins,wangyikai/jenkins,CodeShane/jenkins,ChrisA89/jenkins,MarkEWaite/jenkins,lvotypko/jenkins,aquarellian/jenkins,gorcz/jenkins,deadmoose/jenkins,pselle/jenkins,escoem/jenkins,christ66/jenkins,kzantow/jenkins,KostyaSha/jenkins,lilyJi/jenkins,gusreiber/jenkins,hplatou/jenkins,iqstack/jenkins,kohsuke/hudson,vlajos/jenkins,292388900/jenkins,albers/jenkins,lvotypko/jenkins2,brunocvcunha/jenkins,vivek/hudson,intelchen/jenkins,daniel-beck/jenkins,Jimilian/jenkins,keyurpatankar/hudson,samatdav/jenkins,ajshastri/jenkins,ajshastri/jenkins,kohsuke/hudson,6WIND/jenkins,iterate/coding-dojo,duzifang/my-jenkins,verbitan/jenkins,wangyikai/jenkins,MadsNielsen/jtemp,mrooney/jenkins,pantheon-systems/jenkins,aldaris/jenkins,stefanbrausch/hudson-main,jtnord/jenkins,tangkun75/jenkins,liorhson/jenkins,Jimilian/jenkins,sathiya-mit/jenkins,aquarellian/jenkins,rashmikanta-1984/jenkins,yonglehou/jenkins,hplatou/jenkins,ndeloof/jenkins,DoctorQ/jenkins,jglick/jenkins,ikedam/jenkins,paulmillar/jenkins,aldaris/jenkins,yonglehou/jenkins,Vlatombe/jenkins,alvarolobato/jenkins,tfennelly/jenkins,mcanthony/jenkins,mdonohue/jenkins,andresrc/jenkins,SenolOzer/jenkins,vvv444/jenkins,KostyaSha/jenkins,nandan4/Jenkins,dennisjlee/jenkins,tastatur/jenkins,seanlin816/jenkins,svanoort/jenkins,hudson/hudson-2.x,thomassuckow/jenkins,viqueen/jenkins,jhoblitt/jenkins,arcivanov/jenkins,amuniz/jenkins,oleg-nenashev/jenkins,shahharsh/jenkins,ydubreuil/jenkins,vvv444/jenkins,elkingtonmcb/jenkins,tangkun75/jenkins,my7seven/jenkins,pjanouse/jenkins,singh88/jenkins,aduprat/jenkins,paulmillar/jenkins,mpeltonen/jenkins,pselle/jenkins,guoxu0514/jenkins,ChrisA89/jenkins,v1v/jenkins,lilyJi/jenkins,jglick/jenkins,andresrc/jenkins,shahharsh/jenkins,protazy/jenkins,CodeShane/jenkins,morficus/jenkins,rsandell/jenkins,msrb/jenkins,goldchang/jenkins,oleg-nenashev/jenkins,maikeffi/hudson,patbos/jenkins,gusreiber/jenkins,jcsirot/jenkins,jtnord/jenkins,viqueen/jenkins,Ykus/jenkins,arcivanov/jenkins,godfath3r/jenkins,ErikVerheul/jenkins,vlajos/jenkins,paulwellnerbou/jenkins,daspilker/jenkins,daspilker/jenkins,akshayabd/jenkins,paulmillar/jenkins,DanielWeber/jenkins,sathiya-mit/jenkins,hemantojhaa/jenkins,damianszczepanik/jenkins,amuniz/jenkins,Ykus/jenkins,dbroady1/jenkins,godfath3r/jenkins,olivergondza/jenkins,mattclark/jenkins,jpbriend/jenkins,arunsingh/jenkins,abayer/jenkins,jzjzjzj/jenkins,evernat/jenkins,hashar/jenkins,gorcz/jenkins,patbos/jenkins,gusreiber/jenkins,paulwellnerbou/jenkins,jpederzolli/jenkins-1,jglick/jenkins,msrb/jenkins,azweb76/jenkins,DoctorQ/jenkins,292388900/jenkins,intelchen/jenkins,mattclark/jenkins,seanlin816/jenkins,goldchang/jenkins,SebastienGllmt/jenkins,KostyaSha/jenkins,kzantow/jenkins,ydubreuil/jenkins,duzifang/my-jenkins,petermarcoen/jenkins,mattclark/jenkins,mdonohue/jenkins,everyonce/jenkins,aquarellian/jenkins,recena/jenkins,tfennelly/jenkins,dennisjlee/jenkins,jzjzjzj/jenkins,vivek/hudson,svanoort/jenkins,mrobinet/jenkins,batmat/jenkins,Wilfred/jenkins,nandan4/Jenkins,NehemiahMi/jenkins,gitaccountforprashant/gittest,mdonohue/jenkins,viqueen/jenkins,gorcz/jenkins,jglick/jenkins,kzantow/jenkins,wangyikai/jenkins,brunocvcunha/jenkins,guoxu0514/jenkins,lvotypko/jenkins3,jhoblitt/jenkins,daniel-beck/jenkins,khmarbaise/jenkins,h4ck3rm1k3/jenkins,Krasnyanskiy/jenkins,aheritier/jenkins,jk47/jenkins,recena/jenkins,varmenise/jenkins,lvotypko/jenkins2,batmat/jenkins,daniel-beck/jenkins,brunocvcunha/jenkins,v1v/jenkins,fbelzunc/jenkins,scoheb/jenkins,arcivanov/jenkins,escoem/jenkins,KostyaSha/jenkins,iqstack/jenkins,DanielWeber/jenkins,1and1/jenkins,elkingtonmcb/jenkins,mdonohue/jenkins,chbiel/jenkins,mdonohue/jenkins,noikiy/jenkins,albers/jenkins,khmarbaise/jenkins,andresrc/jenkins,amuniz/jenkins,MarkEWaite/jenkins,deadmoose/jenkins,kohsuke/hudson,jenkinsci/jenkins,amruthsoft9/Jenkis,verbitan/jenkins,rlugojr/jenkins,SebastienGllmt/jenkins,amuniz/jenkins,ndeloof/jenkins,tangkun75/jenkins,aquarellian/jenkins,h4ck3rm1k3/jenkins,csimons/jenkins,github-api-test-org/jenkins,dariver/jenkins,yonglehou/jenkins,Jimilian/jenkins,everyonce/jenkins,292388900/jenkins,guoxu0514/jenkins,my7seven/jenkins,jk47/jenkins,scoheb/jenkins,lordofthejars/jenkins,iterate/coding-dojo,keyurpatankar/hudson,DoctorQ/jenkins,csimons/jenkins,pantheon-systems/jenkins,gusreiber/jenkins,dennisjlee/jenkins,evernat/jenkins,iqstack/jenkins,h4ck3rm1k3/jenkins,iqstack/jenkins,aduprat/jenkins,abayer/jenkins,AustinKwang/jenkins,Vlatombe/jenkins,jk47/jenkins,synopsys-arc-oss/jenkins,mrooney/jenkins,vijayto/jenkins,thomassuckow/jenkins,ns163/jenkins,liorhson/jenkins,jenkinsci/jenkins,lvotypko/jenkins,viqueen/jenkins,keyurpatankar/hudson,iqstack/jenkins,jtnord/jenkins,v1v/jenkins,godfath3r/jenkins,duzifang/my-jenkins,dbroady1/jenkins,ikedam/jenkins,mpeltonen/jenkins,akshayabd/jenkins,alvarolobato/jenkins,petermarcoen/jenkins,github-api-test-org/jenkins,escoem/jenkins,fbelzunc/jenkins,hashar/jenkins,fbelzunc/jenkins,singh88/jenkins,vlajos/jenkins,amuniz/jenkins,sathiya-mit/jenkins,soenter/jenkins,1and1/jenkins,samatdav/jenkins,huybrechts/hudson,seanlin816/jenkins,pantheon-systems/jenkins,Jochen-A-Fuerbacher/jenkins,chbiel/jenkins,singh88/jenkins,abayer/jenkins,kohsuke/hudson,dennisjlee/jenkins,dennisjlee/jenkins,Krasnyanskiy/jenkins,everyonce/jenkins,protazy/jenkins,patbos/jenkins,arunsingh/jenkins,lordofthejars/jenkins,ns163/jenkins,rashmikanta-1984/jenkins,gitaccountforprashant/gittest,olivergondza/jenkins,jenkinsci/jenkins,keyurpatankar/hudson,huybrechts/hudson,lvotypko/jenkins2,liupugong/jenkins,pselle/jenkins,albers/jenkins,mrobinet/jenkins,keyurpatankar/hudson,gorcz/jenkins,hudson/hudson-2.x,wuwen5/jenkins,Wilfred/jenkins,jzjzjzj/jenkins,abayer/jenkins,arcivanov/jenkins,MarkEWaite/jenkins,olivergondza/jenkins,AustinKwang/jenkins,aheritier/jenkins,vvv444/jenkins,github-api-test-org/jenkins,pjanouse/jenkins,wuwen5/jenkins,amuniz/jenkins,ErikVerheul/jenkins,my7seven/jenkins,azweb76/jenkins,maikeffi/hudson,tastatur/jenkins,kohsuke/hudson,synopsys-arc-oss/jenkins,FarmGeek4Life/jenkins,svanoort/jenkins,daniel-beck/jenkins,lordofthejars/jenkins,SebastienGllmt/jenkins,mrooney/jenkins,h4ck3rm1k3/jenkins,Jochen-A-Fuerbacher/jenkins,chbiel/jenkins,dariver/jenkins,SebastienGllmt/jenkins,SenolOzer/jenkins,goldchang/jenkins,goldchang/jenkins,MichaelPranovich/jenkins_sc,alvarolobato/jenkins,lvotypko/jenkins3,arcivanov/jenkins,1and1/jenkins,aldaris/jenkins,intelchen/jenkins,Jochen-A-Fuerbacher/jenkins,mrobinet/jenkins,iterate/coding-dojo,NehemiahMi/jenkins,liorhson/jenkins,amruthsoft9/Jenkis,recena/jenkins,varmenise/jenkins,brunocvcunha/jenkins,Ykus/jenkins,vijayto/jenkins,stephenc/jenkins,lilyJi/jenkins,noikiy/jenkins,MadsNielsen/jtemp,lvotypko/jenkins2,1and1/jenkins,chbiel/jenkins,ajshastri/jenkins,ikedam/jenkins,6WIND/jenkins,vvv444/jenkins,ydubreuil/jenkins,varmenise/jenkins,synopsys-arc-oss/jenkins,svanoort/jenkins,aduprat/jenkins,intelchen/jenkins,ns163/jenkins,shahharsh/jenkins,vijayto/jenkins,daniel-beck/jenkins,bkmeneguello/jenkins,lvotypko/jenkins,mdonohue/jenkins,mattclark/jenkins,singh88/jenkins,andresrc/jenkins,1and1/jenkins,mpeltonen/jenkins,olivergondza/jenkins,amruthsoft9/Jenkis,mattclark/jenkins,paulwellnerbou/jenkins,ndeloof/jenkins,FTG-003/jenkins,azweb76/jenkins,noikiy/jenkins,1and1/jenkins,guoxu0514/jenkins,tangkun75/jenkins,morficus/jenkins,Krasnyanskiy/jenkins,yonglehou/jenkins,KostyaSha/jenkins,hemantojhaa/jenkins,akshayabd/jenkins,arunsingh/jenkins,NehemiahMi/jenkins,hashar/jenkins,patbos/jenkins,mrobinet/jenkins,jpbriend/jenkins,MichaelPranovich/jenkins_sc,rsandell/jenkins,ndeloof/jenkins,Ykus/jenkins,mcanthony/jenkins,bkmeneguello/jenkins,maikeffi/hudson,akshayabd/jenkins,everyonce/jenkins,vivek/hudson,lindzh/jenkins,liorhson/jenkins,Vlatombe/jenkins,shahharsh/jenkins,deadmoose/jenkins,elkingtonmcb/jenkins,ikedam/jenkins,pselle/jenkins,vjuranek/jenkins,gorcz/jenkins,ikedam/jenkins,singh88/jenkins,daniel-beck/jenkins,aldaris/jenkins,fbelzunc/jenkins,batmat/jenkins,jcarrothers-sap/jenkins,morficus/jenkins,h4ck3rm1k3/jenkins,vivek/hudson,github-api-test-org/jenkins,nandan4/Jenkins,ErikVerheul/jenkins,Krasnyanskiy/jenkins,oleg-nenashev/jenkins,goldchang/jenkins,daspilker/jenkins,wuwen5/jenkins,liupugong/jenkins,duzifang/my-jenkins,mcanthony/jenkins,lvotypko/jenkins2,Jochen-A-Fuerbacher/jenkins,olivergondza/jenkins,albers/jenkins,MarkEWaite/jenkins,mrooney/jenkins,fbelzunc/jenkins,aduprat/jenkins,SebastienGllmt/jenkins,escoem/jenkins,yonglehou/jenkins,my7seven/jenkins,jglick/jenkins,synopsys-arc-oss/jenkins,varmenise/jenkins,lilyJi/jenkins,morficus/jenkins,1and1/jenkins,SebastienGllmt/jenkins,gusreiber/jenkins,ndeloof/jenkins,jpbriend/jenkins,jcsirot/jenkins,6WIND/jenkins,bpzhang/jenkins,abayer/jenkins,morficus/jenkins,stephenc/jenkins,evernat/jenkins,pjanouse/jenkins,MadsNielsen/jtemp,lvotypko/jenkins,jpederzolli/jenkins-1,jcsirot/jenkins,hashar/jenkins,CodeShane/jenkins,soenter/jenkins,samatdav/jenkins,verbitan/jenkins,aheritier/jenkins,goldchang/jenkins,tastatur/jenkins,MadsNielsen/jtemp,Ykus/jenkins,batmat/jenkins,iterate/coding-dojo,Vlatombe/jenkins,arunsingh/jenkins,thomassuckow/jenkins,evernat/jenkins,ajshastri/jenkins,Wilfred/jenkins,DanielWeber/jenkins,godfath3r/jenkins,paulmillar/jenkins,christ66/jenkins,rlugojr/jenkins,luoqii/jenkins,hplatou/jenkins,daniel-beck/jenkins,gitaccountforprashant/gittest,paulwellnerbou/jenkins,vlajos/jenkins,vivek/hudson,ErikVerheul/jenkins,292388900/jenkins,christ66/jenkins,ydubreuil/jenkins,h4ck3rm1k3/jenkins,tastatur/jenkins,SenolOzer/jenkins,damianszczepanik/jenkins,escoem/jenkins,tangkun75/jenkins,recena/jenkins,vijayto/jenkins,hplatou/jenkins,my7seven/jenkins,aldaris/jenkins,mrooney/jenkins,aheritier/jenkins,elkingtonmcb/jenkins,iqstack/jenkins,viqueen/jenkins,sathiya-mit/jenkins,khmarbaise/jenkins,oleg-nenashev/jenkins,dariver/jenkins,tangkun75/jenkins,amruthsoft9/Jenkis,MichaelPranovich/jenkins_sc,hemantojhaa/jenkins,jk47/jenkins,ErikVerheul/jenkins,MadsNielsen/jtemp,kzantow/jenkins,mrooney/jenkins,arcivanov/jenkins,soenter/jenkins,stefanbrausch/hudson-main,v1v/jenkins,jcarrothers-sap/jenkins,rlugojr/jenkins,MarkEWaite/jenkins,svanoort/jenkins,alvarolobato/jenkins,mpeltonen/jenkins,petermarcoen/jenkins,DoctorQ/jenkins,FTG-003/jenkins,liupugong/jenkins,v1v/jenkins,csimons/jenkins,petermarcoen/jenkins,csimons/jenkins,vlajos/jenkins,elkingtonmcb/jenkins,aquarellian/jenkins,jk47/jenkins,jenkinsci/jenkins,hashar/jenkins,goldchang/jenkins,alvarolobato/jenkins,jglick/jenkins,pantheon-systems/jenkins,MichaelPranovich/jenkins_sc,292388900/jenkins,morficus/jenkins,kzantow/jenkins,everyonce/jenkins,jk47/jenkins,KostyaSha/jenkins,deadmoose/jenkins,luoqii/jenkins,iqstack/jenkins,DanielWeber/jenkins,Jimilian/jenkins,gitaccountforprashant/gittest,jtnord/jenkins,nandan4/Jenkins,synopsys-arc-oss/jenkins,lvotypko/jenkins,wangyikai/jenkins,NehemiahMi/jenkins,github-api-test-org/jenkins,ndeloof/jenkins,DanielWeber/jenkins,deadmoose/jenkins,lvotypko/jenkins3,dariver/jenkins,tastatur/jenkins,rashmikanta-1984/jenkins,Vlatombe/jenkins,FarmGeek4Life/jenkins,brunocvcunha/jenkins,varmenise/jenkins,singh88/jenkins,aquarellian/jenkins,pantheon-systems/jenkins,thomassuckow/jenkins,jzjzjzj/jenkins,Wilfred/jenkins,duzifang/my-jenkins,ndeloof/jenkins,6WIND/jenkins,stefanbrausch/hudson-main,guoxu0514/jenkins,SenolOzer/jenkins,dbroady1/jenkins,bpzhang/jenkins,aldaris/jenkins,yonglehou/jenkins,paulmillar/jenkins,hemantojhaa/jenkins,Krasnyanskiy/jenkins,liupugong/jenkins,daspilker/jenkins,jhoblitt/jenkins,vjuranek/jenkins,viqueen/jenkins,brunocvcunha/jenkins,damianszczepanik/jenkins,rsandell/jenkins,damianszczepanik/jenkins,damianszczepanik/jenkins,luoqii/jenkins,vjuranek/jenkins,lvotypko/jenkins3,pjanouse/jenkins,shahharsh/jenkins,petermarcoen/jenkins,samatdav/jenkins,DoctorQ/jenkins,msrb/jenkins,jcsirot/jenkins,FarmGeek4Life/jenkins,aheritier/jenkins,bkmeneguello/jenkins,jhoblitt/jenkins,verbitan/jenkins,MichaelPranovich/jenkins_sc,rlugojr/jenkins,kohsuke/hudson,alvarolobato/jenkins,daspilker/jenkins,bpzhang/jenkins,azweb76/jenkins,vjuranek/jenkins,vjuranek/jenkins,khmarbaise/jenkins,ikedam/jenkins,khmarbaise/jenkins,jhoblitt/jenkins,lilyJi/jenkins,mrobinet/jenkins,daspilker/jenkins,soenter/jenkins,bkmeneguello/jenkins,stephenc/jenkins,DoctorQ/jenkins,elkingtonmcb/jenkins,chbiel/jenkins,alvarolobato/jenkins,olivergondza/jenkins,gorcz/jenkins,stefanbrausch/hudson-main,ydubreuil/jenkins,tastatur/jenkins,ChrisA89/jenkins,bpzhang/jenkins,soenter/jenkins,jhoblitt/jenkins,tastatur/jenkins,mcanthony/jenkins,tfennelly/jenkins,kzantow/jenkins,deadmoose/jenkins,andresrc/jenkins,jcarrothers-sap/jenkins,verbitan/jenkins,pantheon-systems/jenkins,Jimilian/jenkins,protazy/jenkins,NehemiahMi/jenkins,huybrechts/hudson,github-api-test-org/jenkins,oleg-nenashev/jenkins,wuwen5/jenkins,khmarbaise/jenkins,CodeShane/jenkins,mrooney/jenkins,AustinKwang/jenkins,bkmeneguello/jenkins,maikeffi/hudson,guoxu0514/jenkins,Wilfred/jenkins,mattclark/jenkins,damianszczepanik/jenkins,mpeltonen/jenkins,huybrechts/hudson,lindzh/jenkins,vijayto/jenkins,synopsys-arc-oss/jenkins,jpederzolli/jenkins-1,amruthsoft9/Jenkis,svanoort/jenkins,ChrisA89/jenkins,Jochen-A-Fuerbacher/jenkins,tfennelly/jenkins,recena/jenkins,escoem/jenkins,AustinKwang/jenkins,luoqii/jenkins,thomassuckow/jenkins,Jimilian/jenkins,aldaris/jenkins,rsandell/jenkins,vvv444/jenkins,aheritier/jenkins,CodeShane/jenkins,stefanbrausch/hudson-main,maikeffi/hudson,noikiy/jenkins,noikiy/jenkins,lilyJi/jenkins,sathiya-mit/jenkins,DanielWeber/jenkins,292388900/jenkins,ErikVerheul/jenkins,christ66/jenkins,christ66/jenkins,vvv444/jenkins,jcarrothers-sap/jenkins,vijayto/jenkins,FTG-003/jenkins,NehemiahMi/jenkins,lilyJi/jenkins,gitaccountforprashant/gittest,chbiel/jenkins,jcarrothers-sap/jenkins,duzifang/my-jenkins,jcsirot/jenkins,oleg-nenashev/jenkins,recena/jenkins,DoctorQ/jenkins,msrb/jenkins,keyurpatankar/hudson,azweb76/jenkins,Jochen-A-Fuerbacher/jenkins,pselle/jenkins,my7seven/jenkins,andresrc/jenkins,varmenise/jenkins,verbitan/jenkins,6WIND/jenkins,mcanthony/jenkins,pantheon-systems/jenkins,gitaccountforprashant/gittest,jcarrothers-sap/jenkins,DoctorQ/jenkins,lindzh/jenkins,godfath3r/jenkins,vivek/hudson,evernat/jenkins,bpzhang/jenkins,jtnord/jenkins,hemantojhaa/jenkins,wangyikai/jenkins,h4ck3rm1k3/jenkins,luoqii/jenkins,jzjzjzj/jenkins,liorhson/jenkins,guoxu0514/jenkins,christ66/jenkins,jpbriend/jenkins,jpederzolli/jenkins-1,petermarcoen/jenkins,sathiya-mit/jenkins,paulmillar/jenkins,iterate/coding-dojo,FTG-003/jenkins,SenolOzer/jenkins,paulmillar/jenkins,vjuranek/jenkins,lvotypko/jenkins2,ikedam/jenkins,shahharsh/jenkins,soenter/jenkins,deadmoose/jenkins,ChrisA89/jenkins,jpbriend/jenkins,aduprat/jenkins,gusreiber/jenkins,hemantojhaa/jenkins,ajshastri/jenkins,aheritier/jenkins,evernat/jenkins,github-api-test-org/jenkins,CodeShane/jenkins,pjanouse/jenkins,kohsuke/hudson,my7seven/jenkins,christ66/jenkins,lordofthejars/jenkins,292388900/jenkins,amruthsoft9/Jenkis,FarmGeek4Life/jenkins,damianszczepanik/jenkins,jzjzjzj/jenkins,patbos/jenkins,ajshastri/jenkins,noikiy/jenkins,Jochen-A-Fuerbacher/jenkins,liorhson/jenkins,jtnord/jenkins,ErikVerheul/jenkins,liupugong/jenkins,gorcz/jenkins,nandan4/Jenkins,vlajos/jenkins,wangyikai/jenkins,paulwellnerbou/jenkins,aduprat/jenkins,liupugong/jenkins,hudson/hudson-2.x,hudson/hudson-2.x,FarmGeek4Life/jenkins,duzifang/my-jenkins,azweb76/jenkins,seanlin816/jenkins,jzjzjzj/jenkins,lindzh/jenkins,rashmikanta-1984/jenkins,evernat/jenkins,msrb/jenkins,verbitan/jenkins,jcsirot/jenkins,abayer/jenkins,aduprat/jenkins,wuwen5/jenkins,paulwellnerbou/jenkins,iterate/coding-dojo,varmenise/jenkins,lindzh/jenkins,jenkinsci/jenkins,keyurpatankar/hudson,fbelzunc/jenkins,pselle/jenkins,dennisjlee/jenkins,dbroady1/jenkins,ns163/jenkins,amruthsoft9/Jenkis,bpzhang/jenkins,hplatou/jenkins,lordofthejars/jenkins,mcanthony/jenkins,FTG-003/jenkins,Jimilian/jenkins,arcivanov/jenkins,wuwen5/jenkins,FarmGeek4Life/jenkins,jpederzolli/jenkins-1,vivek/hudson,vijayto/jenkins,AustinKwang/jenkins,petermarcoen/jenkins,vivek/hudson,jcarrothers-sap/jenkins,rashmikanta-1984/jenkins,jk47/jenkins,arunsingh/jenkins,protazy/jenkins,KostyaSha/jenkins,stephenc/jenkins,daniel-beck/jenkins,github-api-test-org/jenkins,jpbriend/jenkins,wangyikai/jenkins,pjanouse/jenkins,keyurpatankar/hudson,lvotypko/jenkins2,protazy/jenkins,maikeffi/hudson,scoheb/jenkins,FarmGeek4Life/jenkins,seanlin816/jenkins,csimons/jenkins,MarkEWaite/jenkins,yonglehou/jenkins,recena/jenkins,escoem/jenkins,huybrechts/hudson,tfennelly/jenkins,noikiy/jenkins,dariver/jenkins,jglick/jenkins,intelchen/jenkins,ajshastri/jenkins,batmat/jenkins,v1v/jenkins,intelchen/jenkins,tfennelly/jenkins,batmat/jenkins,andresrc/jenkins,seanlin816/jenkins,arunsingh/jenkins,stefanbrausch/hudson-main,hudson/hudson-2.x,csimons/jenkins,dbroady1/jenkins,dariver/jenkins,paulwellnerbou/jenkins,godfath3r/jenkins,nandan4/Jenkins,DanielWeber/jenkins,jpederzolli/jenkins-1,shahharsh/jenkins,KostyaSha/jenkins,seanlin816/jenkins,lvotypko/jenkins,mpeltonen/jenkins,akshayabd/jenkins,bkmeneguello/jenkins,thomassuckow/jenkins,khmarbaise/jenkins,scoheb/jenkins,elkingtonmcb/jenkins,ns163/jenkins,csimons/jenkins,rlugojr/jenkins,6WIND/jenkins,daspilker/jenkins,vjuranek/jenkins,vvv444/jenkins,gitaccountforprashant/gittest,scoheb/jenkins,jenkinsci/jenkins,viqueen/jenkins,mcanthony/jenkins,shahharsh/jenkins,AustinKwang/jenkins,dbroady1/jenkins,rlugojr/jenkins,Krasnyanskiy/jenkins,oleg-nenashev/jenkins,Wilfred/jenkins,FTG-003/jenkins,MadsNielsen/jtemp,patbos/jenkins,rlugojr/jenkins,ns163/jenkins,patbos/jenkins,lindzh/jenkins
package hudson.maven.reporters; import hudson.FilePath; import hudson.Util; import hudson.maven.MavenBuildProxy; import hudson.maven.MavenModule; import hudson.maven.MavenReporter; import hudson.maven.MavenReporterDescriptor; import hudson.maven.MojoInfo; import hudson.maven.MavenModuleSet; import hudson.maven.MavenReportInfo; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.JavadocArchiver.JavadocAction; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import java.io.File; import java.io.IOException; /** * Records the javadoc and archives it. * * @author Kohsuke Kawaguchi */ public class MavenJavadocArchiver extends MavenReporter { public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException { if(!mojo.is("org.apache.maven.plugins","maven-javadoc-plugin","javadoc") && !mojo.is("org.apache.maven.plugins","maven-javadoc-plugin","aggregate")) return true; File destDir; boolean aggregated; try { aggregated = mojo.getConfigurationValue("aggregate",Boolean.class) || mojo.getGoal().equals("aggregate"); if(aggregated && !pom.isExecutionRoot()) return true; // in the aggregated mode, the generation will only happen for the root module destDir = mojo.getConfigurationValue("reportOutputDirectory", File.class); if(destDir==null) destDir = mojo.getConfigurationValue("outputDirectory", File.class); } catch (ComponentConfigurationException e) { e.printStackTrace(listener.fatalError(Messages.MavenJavadocArchiver_NoDestDir())); build.setResult(Result.FAILURE); return true; } if(destDir.exists()) { // javadoc:javadoc just skips itself when the current project is not a java project FilePath target; if(aggregated) { // store at MavenModuleSet level. listener.getLogger().println("[HUDSON] Archiving aggregated javadoc"); target = build.getModuleSetRootDir(); } else { listener.getLogger().println("[HUDSON] Archiving javadoc"); target = build.getProjectRootDir(); } target = target.child("javadoc"); try { new FilePath(destDir).copyRecursiveTo("**/*",target); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.fatalError(Messages.MavenJavadocArchiver_FailedToCopy(destDir,target))); build.setResult(Result.FAILURE); } if(aggregated) build.registerAsAggregatedProjectAction(this); else build.registerAsProjectAction(this); } return true; } @Override public boolean reportGenerated(MavenBuildProxy build, MavenProject pom, MavenReportInfo report, BuildListener listener) throws InterruptedException, IOException { return postExecute(build,pom,report,listener,null); } public Action getProjectAction(MavenModule project) { return new JavadocAction(project); } public Action getAggregatedProjectAction(MavenModuleSet project) { return new JavadocAction(project); } public DescriptorImpl getDescriptor() { return DescriptorImpl.DESCRIPTOR; } public static final class DescriptorImpl extends MavenReporterDescriptor { public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); private DescriptorImpl() { super(MavenJavadocArchiver.class); } public String getDisplayName() { return Messages.MavenJavadocArchiver_DisplayName(); } public MavenJavadocArchiver newAutoInstance(MavenModule module) { return new MavenJavadocArchiver(); } } private static final long serialVersionUID = 1L; }
core/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java
package hudson.maven.reporters; import hudson.FilePath; import hudson.Util; import hudson.maven.MavenBuildProxy; import hudson.maven.MavenModule; import hudson.maven.MavenReporter; import hudson.maven.MavenReporterDescriptor; import hudson.maven.MojoInfo; import hudson.maven.MavenBuild; import hudson.maven.MavenModuleSet; import hudson.maven.MavenReportInfo; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Result; import hudson.tasks.JavadocArchiver.JavadocAction; import org.apache.maven.project.MavenProject; import org.apache.maven.reporting.MavenReport; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import java.io.File; import java.io.IOException; /** * Records the javadoc and archives it. * * @author Kohsuke Kawaguchi */ public class MavenJavadocArchiver extends MavenReporter { public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException { if(!mojo.is("org.apache.maven.plugins","maven-javadoc-plugin","javadoc")) return true; File destDir; boolean aggregated; try { aggregated = mojo.getConfigurationValue("aggregate",Boolean.class); if(aggregated && !pom.isExecutionRoot()) return true; // in the aggregated mode, the generation will only happen for the root module destDir = mojo.getConfigurationValue("reportOutputDirectory", File.class); if(destDir==null) destDir = mojo.getConfigurationValue("outputDirectory", File.class); } catch (ComponentConfigurationException e) { e.printStackTrace(listener.fatalError(Messages.MavenJavadocArchiver_NoDestDir())); build.setResult(Result.FAILURE); return true; } if(destDir.exists()) { // javadoc:javadoc just skips itself when the current project is not a java project FilePath target; if(aggregated) // store at MavenModuleSet level. target = build.getModuleSetRootDir(); else target = build.getProjectRootDir(); target = target.child("javadoc"); try { listener.getLogger().println("[HUDSON] Archiving javadoc"); new FilePath(destDir).copyRecursiveTo("**/*",target); } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.fatalError(Messages.MavenJavadocArchiver_FailedToCopy(destDir,target))); build.setResult(Result.FAILURE); } if(aggregated) build.registerAsAggregatedProjectAction(this); else build.registerAsProjectAction(this); } return true; } @Override public boolean reportGenerated(MavenBuildProxy build, MavenProject pom, MavenReportInfo report, BuildListener listener) throws InterruptedException, IOException { return postExecute(build,pom,report,listener,null); } public Action getProjectAction(MavenModule project) { return new JavadocAction(project); } public Action getAggregatedProjectAction(MavenModuleSet project) { return new JavadocAction(project); } public DescriptorImpl getDescriptor() { return DescriptorImpl.DESCRIPTOR; } public static final class DescriptorImpl extends MavenReporterDescriptor { public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); private DescriptorImpl() { super(MavenJavadocArchiver.class); } public String getDisplayName() { return Messages.MavenJavadocArchiver_DisplayName(); } public MavenJavadocArchiver newAutoInstance(MavenModule module) { return new MavenJavadocArchiver(); } } private static final long serialVersionUID = 1L; }
[FIXED HUDSON-2562] Supported javadoc:aggregate git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@12964 71c3de6d-444a-0410-be80-ed276b4c234a
core/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java
[FIXED HUDSON-2562] Supported javadoc:aggregate
<ide><path>ore/src/main/java/hudson/maven/reporters/MavenJavadocArchiver.java <ide> import hudson.maven.MavenReporter; <ide> import hudson.maven.MavenReporterDescriptor; <ide> import hudson.maven.MojoInfo; <del>import hudson.maven.MavenBuild; <ide> import hudson.maven.MavenModuleSet; <ide> import hudson.maven.MavenReportInfo; <ide> import hudson.model.Action; <ide> import hudson.model.Result; <ide> import hudson.tasks.JavadocArchiver.JavadocAction; <ide> import org.apache.maven.project.MavenProject; <del>import org.apache.maven.reporting.MavenReport; <ide> import org.codehaus.plexus.component.configurator.ComponentConfigurationException; <ide> <ide> import java.io.File; <ide> */ <ide> public class MavenJavadocArchiver extends MavenReporter { <ide> public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) throws InterruptedException, IOException { <del> if(!mojo.is("org.apache.maven.plugins","maven-javadoc-plugin","javadoc")) <add> if(!mojo.is("org.apache.maven.plugins","maven-javadoc-plugin","javadoc") <add> && !mojo.is("org.apache.maven.plugins","maven-javadoc-plugin","aggregate")) <ide> return true; <ide> <ide> File destDir; <ide> boolean aggregated; <ide> try { <del> aggregated = mojo.getConfigurationValue("aggregate",Boolean.class); <add> aggregated = mojo.getConfigurationValue("aggregate",Boolean.class) || mojo.getGoal().equals("aggregate"); <ide> if(aggregated && !pom.isExecutionRoot()) <ide> return true; // in the aggregated mode, the generation will only happen for the root module <ide> <ide> if(destDir.exists()) { <ide> // javadoc:javadoc just skips itself when the current project is not a java project <ide> FilePath target; <del> if(aggregated) <add> if(aggregated) { <ide> // store at MavenModuleSet level. <add> listener.getLogger().println("[HUDSON] Archiving aggregated javadoc"); <ide> target = build.getModuleSetRootDir(); <del> else <add> } else { <add> listener.getLogger().println("[HUDSON] Archiving javadoc"); <ide> target = build.getProjectRootDir(); <add> } <ide> <ide> target = target.child("javadoc"); <ide> <ide> try { <del> listener.getLogger().println("[HUDSON] Archiving javadoc"); <ide> new FilePath(destDir).copyRecursiveTo("**/*",target); <ide> } catch (IOException e) { <ide> Util.displayIOException(e,listener);
JavaScript
mit
5be6373c049e8a5a2ac0e8e4497ecafff0e8dd06
0
donmccurdy/sandbox-aframe,donmccurdy/aframe-extras
/** * Touch-to-move-forward controls for mobile. */ module.exports = AFRAME.registerComponent('touch-controls', { schema: { enabled: { default: true }, reverseEnabled: { default: true } }, init: function () { this.dVelocity = new THREE.Vector3(); this.bindMethods(); }, play: function () { this.addEventListeners(); }, pause: function () { this.removeEventListeners(); this.dVelocity.set(0, 0, 0); }, remove: function () { this.pause(); }, addEventListeners: function () { const sceneEl = this.el.sceneEl; const canvasEl = sceneEl.canvas; if (!canvasEl) { sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this)); return; } canvasEl.addEventListener('touchstart', this.onTouchStart); canvasEl.addEventListener('touchend', this.onTouchEnd); }, removeEventListeners: function () { const canvasEl = this.el.sceneEl && this.el.sceneEl.canvas; if (!canvasEl) { return; } canvasEl.removeEventListener('touchstart', this.onTouchStart); canvasEl.removeEventListener('touchend', this.onTouchEnd); }, isVelocityActive: function () { return this.data.enabled && this.isMoving; }, getVelocityDelta: function () { const zDir = this.isReverse && this.data.reverseEnabled ? 1 : -1 this.dVelocity.z = this.isMoving ? zDir : 0; return this.dVelocity.clone(); }, bindMethods: function () { this.onTouchStart = this.onTouchStart.bind(this); this.onTouchEnd = this.onTouchEnd.bind(this); }, onTouchStart: function (e) { this.isMoving = true; this.isReverse = e.touches.length == 2 e.preventDefault(); }, onTouchEnd: function (e) { this.isMoving = false; e.preventDefault(); } });
src/controls/touch-controls.js
/** * Touch-to-move-forward controls for mobile. */ module.exports = AFRAME.registerComponent('touch-controls', { schema: { enabled: { default: true }, reverseEnabled: { default: true } }, init: function () { this.dVelocity = new THREE.Vector3(); this.bindMethods(); }, play: function () { this.addEventListeners(); }, pause: function () { this.removeEventListeners(); this.dVelocity.set(0, 0, 0); }, remove: function () { this.pause(); }, addEventListeners: function () { const sceneEl = this.el.sceneEl; const canvasEl = sceneEl.canvas; if (!canvasEl) { sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this)); return; } canvasEl.addEventListener('touchstart', this.onTouchStart); canvasEl.addEventListener('touchend', this.onTouchEnd); }, removeEventListeners: function () { const canvasEl = this.el.sceneEl && this.el.sceneEl.canvas; if (!canvasEl) { return; } canvasEl.removeEventListener('touchstart', this.onTouchStart); canvasEl.removeEventListener('touchend', this.onTouchEnd); }, isVelocityActive: function () { return this.data.enabled && this.isMoving; }, getVelocityDelta: function () { zDir = this.isReverse && this.data.reverseEnabled ? 1 : -1 this.dVelocity.z = this.isMoving ? zDir : 0; return this.dVelocity.clone(); }, bindMethods: function () { this.onTouchStart = this.onTouchStart.bind(this); this.onTouchEnd = this.onTouchEnd.bind(this); }, onTouchStart: function (e) { this.isMoving = true; this.isReverse = e.touches.length == 2 e.preventDefault(); }, onTouchEnd: function (e) { this.isMoving = false; e.preventDefault(); } });
Fix variable initialization;
src/controls/touch-controls.js
Fix variable initialization;
<ide><path>rc/controls/touch-controls.js <ide> }, <ide> <ide> getVelocityDelta: function () { <del> zDir = this.isReverse && this.data.reverseEnabled ? 1 : -1 <add> const zDir = this.isReverse && this.data.reverseEnabled ? 1 : -1 <ide> this.dVelocity.z = this.isMoving ? zDir : 0; <ide> return this.dVelocity.clone(); <ide> },
Java
apache-2.0
1db76e01057762d1f44511546cea396d2ec6618b
0
DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel,DaveVoorhis/Rel
package org.reldb.dbrowser.ui; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Label; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.widgets.Text; import org.reldb.dbrowser.Core; import org.reldb.rel.client.Connection; import org.reldb.rel.client.Response; import org.eclipse.swt.widgets.Button; public class RestoreDatabaseDialog extends Dialog { protected Shell shell; private Text textDatabaseDir; private Text textSourceFile; private Text textOutput; private DirectoryDialog newDatabaseDialog; private FileDialog restoreFileDialog; private Button btnCancel; private Button btnOk; /** * Create the dialog. * @param parent * @param style */ public RestoreDatabaseDialog(Shell parent) { super(parent, SWT.DIALOG_TRIM | SWT.RESIZE); setText("Create and Restore Database"); newDatabaseDialog = new DirectoryDialog(parent); newDatabaseDialog.setText("Create Database"); newDatabaseDialog.setMessage("Select a folder to hold a new database."); newDatabaseDialog.setFilterPath(System.getProperty("user.home")); restoreFileDialog = new FileDialog(Core.getShell(), SWT.OPEN); restoreFileDialog.setFilterPath(System.getProperty("user.home")); restoreFileDialog.setFilterExtensions(new String[] {"*.rel", "*.*"}); restoreFileDialog.setFilterNames(new String[] {"Rel script", "All Files"}); restoreFileDialog.setText("Load Backup"); } /** * Open the dialog. */ public void open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } private void setupUIAsFinished() { textDatabaseDir.setEnabled(false); textSourceFile.setEnabled(false); btnOk.setVisible(false); btnCancel.setText("Close"); } private void process(String dbURL, String backupToRestore) { textOutput.append("Ready to create database " + dbURL + "\n"); try (Connection connection = new Connection(dbURL, true)) { textOutput.append("Database " + dbURL + " created.\n"); try { String serverAnnouncement = connection.getServerAnnouncement(); textOutput.append(serverAnnouncement + "\n"); Response response = connection.execute(backupToRestore); response.awaitResult(999999); setupUIAsFinished(); } catch (IOException e1) { textOutput.append("Unable to communicate with database due to " + e1.getMessage()); } } catch (Exception e) { textOutput.append("Unable to create database " + dbURL + "\n"); textOutput.append(e.getMessage()); } } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), getStyle()); shell.setSize(640, 480); shell.setText(getText()); shell.setLayout(new FormLayout()); Label lblDatabaseDir = new Label(shell, SWT.NONE); FormData fd_lblDatabaseDir = new FormData(); lblDatabaseDir.setLayoutData(fd_lblDatabaseDir); lblDatabaseDir.setText("Directory for new database:"); textDatabaseDir = new Text(shell, SWT.BORDER); FormData fd_textDatabaseDir = new FormData(); textDatabaseDir.setLayoutData(fd_textDatabaseDir); Button btnDatabaseDir = new Button(shell, SWT.NONE); FormData fd_btnDatabaseDir = new FormData(); btnDatabaseDir.setLayoutData(fd_btnDatabaseDir); btnDatabaseDir.setText("Directory..."); btnDatabaseDir.addListener(SWT.Selection, e -> { if (textDatabaseDir.getText().trim().length() == 0) newDatabaseDialog.setFilterPath(System.getProperty("user.home")); else newDatabaseDialog.setFilterPath(textDatabaseDir.getText()); String result = newDatabaseDialog.open(); if (result == null) return; textDatabaseDir.setText(result); }); Label lblSourceFile = new Label(shell, SWT.NONE); FormData fd_lblSourceFile = new FormData(); lblSourceFile.setLayoutData(fd_lblSourceFile); lblSourceFile.setText("Backup to restore:"); textSourceFile = new Text(shell, SWT.BORDER); FormData fd_textSourceFile = new FormData(); textSourceFile.setLayoutData(fd_textSourceFile); Button btnSourceFile = new Button(shell, SWT.NONE); FormData fd_btnSourceFile = new FormData(); btnSourceFile.setLayoutData(fd_btnSourceFile); btnSourceFile.setText("Choose file..."); btnOk = new Button(shell, SWT.NONE); FormData fd_btnOk = new FormData(); btnOk.setLayoutData(fd_btnOk); btnOk.setText("Ok"); btnOk.addListener(SWT.Selection, e -> { String databaseDir = textDatabaseDir.getText().trim(); if (databaseDir.length() == 0) { MessageDialog.openInformation(shell, "No Directory Specified", "No database directory was specified."); return; } String sourceFileName = textSourceFile.getText().trim(); if (sourceFileName.length() == 0) { MessageDialog.openInformation(shell, "No Backup File Specified", "No database backup file to restore was specified."); return; } File sourceFile = new File(sourceFileName); if (!sourceFile.exists()) { MessageDialog.openInformation(shell, "Unable to Open Backup File", "Database backup file cannot be found."); return; } String backup = ""; try { backup = new String(Files.readAllBytes(sourceFile.toPath()), "UTF-8"); } catch (IOException e2) { MessageDialog.openInformation(shell, "Unable to Read Backup File", "The database backup file a can't be read due to " + e2.getMessage()); return; } if (backup.trim().length() == 0) { MessageDialog.openInformation(shell, "Unable to Read Backup File", "The database backup file appears to be empty or unreadable."); return; } String dbURL = "db:" + databaseDir; Connection connection; try { connection = new Connection(dbURL); connection.close(); MessageDialog.openInformation(shell, "Database Exists", "A Rel database already exists at " + dbURL); } catch (Exception e1) { Throwable cause = e1.getCause(); if (cause != null && cause.getMessage().startsWith("RS0406:")) process(dbURL, backup); else MessageDialog.openError(shell, "Problem with Directory", "Unable to use " + dbURL + " due to: " + e1.getMessage()); } }); btnCancel = new Button(shell, SWT.NONE); FormData fd_btnCancel = new FormData(); btnCancel.setLayoutData(fd_btnCancel); btnCancel.setText("Cancel"); btnCancel.addListener(SWT.Selection, e -> shell.dispose()); Label lblOutput = new Label(shell, SWT.NONE); FormData fd_lblOutput = new FormData(); lblOutput.setLayoutData(fd_lblOutput); lblOutput.setText("Output"); textOutput = new Text(shell, SWT.BORDER | SWT.MULTI); FormData fd_textOutput = new FormData(); textOutput.setLayoutData(fd_textOutput); fd_lblDatabaseDir.top = new FormAttachment(0, 10); fd_lblDatabaseDir.left = new FormAttachment(0, 5); fd_lblSourceFile.top = new FormAttachment(lblDatabaseDir, 25); fd_lblSourceFile.right = new FormAttachment(lblDatabaseDir, 0, SWT.RIGHT); fd_textDatabaseDir.top = new FormAttachment(0, 10); fd_textDatabaseDir.left = new FormAttachment(lblDatabaseDir, 5); fd_textDatabaseDir.right = new FormAttachment(btnSourceFile, -5); fd_textSourceFile.top = new FormAttachment(lblDatabaseDir, 25); fd_textSourceFile.left = new FormAttachment(lblSourceFile, 5); fd_textSourceFile.right = new FormAttachment(btnSourceFile, -5); fd_btnDatabaseDir.top = new FormAttachment(0, 10); fd_btnDatabaseDir.left = new FormAttachment(btnSourceFile, 0, SWT.LEFT); fd_btnDatabaseDir.right = new FormAttachment(btnSourceFile, 0, SWT.RIGHT); fd_btnSourceFile.top = new FormAttachment(lblDatabaseDir, 25); fd_btnSourceFile.right = new FormAttachment(100, -5); fd_lblOutput.top = new FormAttachment(textSourceFile, 30); fd_lblOutput.left = new FormAttachment(0, 5); fd_textOutput.top = new FormAttachment(lblOutput, 5); fd_textOutput.left = new FormAttachment(0, 5); fd_textOutput.bottom = new FormAttachment(btnOk, -5); fd_textOutput.right = new FormAttachment(100, -5); fd_btnCancel.bottom = new FormAttachment(100, -5); fd_btnCancel.right = new FormAttachment(100, -5); fd_btnOk.bottom = new FormAttachment(100, -5); fd_btnOk.right = new FormAttachment(btnCancel, -5); } }
DBrowser/src/org/reldb/dbrowser/ui/RestoreDatabaseDialog.java
package org.reldb.dbrowser.ui; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Label; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.widgets.Text; import org.reldb.dbrowser.Core; import org.reldb.rel.client.Connection; import org.eclipse.swt.widgets.Button; public class RestoreDatabaseDialog extends Dialog { protected Object result; protected Shell shell; private Text textDatabaseDir; private Text textSourceFile; private Text textOutput; private DirectoryDialog newDatabaseDialog; private FileDialog restoreFileDialog; private Button btnCancel; private Button btnOk; /** * Create the dialog. * @param parent * @param style */ public RestoreDatabaseDialog(Shell parent) { super(parent, SWT.DIALOG_TRIM | SWT.RESIZE); setText("Create and Restore Database"); newDatabaseDialog = new DirectoryDialog(parent); newDatabaseDialog.setText("Create Database"); newDatabaseDialog.setMessage("Select a folder to hold a new database."); newDatabaseDialog.setFilterPath(System.getProperty("user.home")); restoreFileDialog = new FileDialog(Core.getShell(), SWT.OPEN); restoreFileDialog.setFilterPath(System.getProperty("user.home")); restoreFileDialog.setFilterExtensions(new String[] {"*.rel", "*.*"}); restoreFileDialog.setFilterNames(new String[] {"Rel script", "All Files"}); restoreFileDialog.setText("Load Backup"); } /** * Open the dialog. * @return the result */ public Object open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } private void process(String dbURL) { textOutput.append("Ready to create database " + dbURL + "\n"); try (Connection connection = new Connection(dbURL, true)) { textOutput.append("Database " + dbURL + " created.\n"); btnOk.setVisible(false); btnCancel.setText("Close"); } catch (Exception e) { textOutput.append("Unable to create database " + dbURL + "\n"); textOutput.append(e.getMessage()); } } /** * Create contents of the dialog. */ private void createContents() { shell = new Shell(getParent(), getStyle()); shell.setSize(640, 480); shell.setText(getText()); shell.setLayout(new FormLayout()); Label lblDatabaseDir = new Label(shell, SWT.NONE); FormData fd_lblDatabaseDir = new FormData(); lblDatabaseDir.setLayoutData(fd_lblDatabaseDir); lblDatabaseDir.setText("Directory for new database:"); textDatabaseDir = new Text(shell, SWT.BORDER); FormData fd_textDatabaseDir = new FormData(); textDatabaseDir.setLayoutData(fd_textDatabaseDir); Button btnDatabaseDir = new Button(shell, SWT.NONE); FormData fd_btnDatabaseDir = new FormData(); btnDatabaseDir.setLayoutData(fd_btnDatabaseDir); btnDatabaseDir.setText("Directory..."); btnDatabaseDir.addListener(SWT.Selection, e -> { if (textDatabaseDir.getText().trim().length() == 0) newDatabaseDialog.setFilterPath(System.getProperty("user.home")); else newDatabaseDialog.setFilterPath(textDatabaseDir.getText()); String result = newDatabaseDialog.open(); if (result == null) return; textDatabaseDir.setText(result); }); Label lblSourceFile = new Label(shell, SWT.NONE); FormData fd_lblSourceFile = new FormData(); lblSourceFile.setLayoutData(fd_lblSourceFile); lblSourceFile.setText("Backup to restore:"); textSourceFile = new Text(shell, SWT.BORDER); FormData fd_textSourceFile = new FormData(); textSourceFile.setLayoutData(fd_textSourceFile); Button btnSourceFile = new Button(shell, SWT.NONE); FormData fd_btnSourceFile = new FormData(); btnSourceFile.setLayoutData(fd_btnSourceFile); btnSourceFile.setText("Choose file..."); Button btnOk = new Button(shell, SWT.NONE); FormData fd_btnOk = new FormData(); btnOk.setLayoutData(fd_btnOk); btnOk.setText("Ok"); btnOk.addListener(SWT.Selection, e -> { String databaseDir = textDatabaseDir.getText().trim(); if (databaseDir.length() == 0) { MessageDialog.openInformation(shell, "No Directory Specified", "No database directory was specified."); return; } String dbURL = "db:" + databaseDir; Connection connection; try { connection = new Connection(dbURL); connection.close(); MessageDialog.openInformation(shell, "Database Exists", "A Rel database already exists at " + dbURL); } catch (Exception e1) { Throwable cause = e1.getCause(); if (cause != null && cause.getMessage().startsWith("RS0406:")) process(dbURL); else MessageDialog.openError(shell, "Problem with Directory", "Unable to use " + dbURL + " due to: " + e1.getMessage()); } }); Button btnCancel = new Button(shell, SWT.NONE); FormData fd_btnCancel = new FormData(); btnCancel.setLayoutData(fd_btnCancel); btnCancel.setText("Cancel"); btnCancel.addListener(SWT.Selection, e -> shell.dispose()); Label lblOutput = new Label(shell, SWT.NONE); FormData fd_lblOutput = new FormData(); lblOutput.setLayoutData(fd_lblOutput); lblOutput.setText("Output"); textOutput = new Text(shell, SWT.BORDER | SWT.MULTI); FormData fd_textOutput = new FormData(); textOutput.setLayoutData(fd_textOutput); fd_lblDatabaseDir.top = new FormAttachment(0, 10); fd_lblDatabaseDir.left = new FormAttachment(0, 5); fd_lblSourceFile.top = new FormAttachment(lblDatabaseDir, 25); fd_lblSourceFile.right = new FormAttachment(lblDatabaseDir, 0, SWT.RIGHT); fd_textDatabaseDir.top = new FormAttachment(0, 10); fd_textDatabaseDir.left = new FormAttachment(lblDatabaseDir, 5); fd_textDatabaseDir.right = new FormAttachment(btnSourceFile, -5); fd_textSourceFile.top = new FormAttachment(lblDatabaseDir, 25); fd_textSourceFile.left = new FormAttachment(lblSourceFile, 5); fd_textSourceFile.right = new FormAttachment(btnSourceFile, -5); fd_btnDatabaseDir.top = new FormAttachment(0, 10); fd_btnDatabaseDir.left = new FormAttachment(btnSourceFile, 0, SWT.LEFT); fd_btnDatabaseDir.right = new FormAttachment(btnSourceFile, 0, SWT.RIGHT); fd_btnSourceFile.top = new FormAttachment(lblDatabaseDir, 25); fd_btnSourceFile.right = new FormAttachment(100, -5); fd_lblOutput.top = new FormAttachment(textSourceFile, 30); fd_lblOutput.left = new FormAttachment(0, 5); fd_textOutput.top = new FormAttachment(lblOutput, 5); fd_textOutput.left = new FormAttachment(0, 5); fd_textOutput.bottom = new FormAttachment(btnOk, -5); fd_textOutput.right = new FormAttachment(100, -5); fd_btnCancel.bottom = new FormAttachment(100, -5); fd_btnCancel.right = new FormAttachment(100, -5); fd_btnOk.bottom = new FormAttachment(100, -5); fd_btnOk.right = new FormAttachment(btnCancel, -5); } }
Work on restore operation.
DBrowser/src/org/reldb/dbrowser/ui/RestoreDatabaseDialog.java
Work on restore operation.
<ide><path>Browser/src/org/reldb/dbrowser/ui/RestoreDatabaseDialog.java <ide> import org.eclipse.swt.widgets.Shell; <ide> import org.eclipse.swt.layout.FormLayout; <ide> import org.eclipse.swt.widgets.Label; <add> <add>import java.io.File; <add>import java.io.IOException; <add>import java.nio.file.Files; <add> <ide> import org.eclipse.jface.dialogs.MessageDialog; <ide> import org.eclipse.swt.SWT; <ide> import org.eclipse.swt.layout.FormData; <ide> import org.eclipse.swt.widgets.Text; <ide> import org.reldb.dbrowser.Core; <ide> import org.reldb.rel.client.Connection; <add>import org.reldb.rel.client.Response; <ide> import org.eclipse.swt.widgets.Button; <ide> <ide> public class RestoreDatabaseDialog extends Dialog { <ide> <del> protected Object result; <ide> protected Shell shell; <add> <ide> private Text textDatabaseDir; <ide> private Text textSourceFile; <ide> private Text textOutput; <add> <ide> private DirectoryDialog newDatabaseDialog; <ide> private FileDialog restoreFileDialog; <ide> <ide> <ide> /** <ide> * Open the dialog. <del> * @return the result <ide> */ <del> public Object open() { <add> public void open() { <ide> createContents(); <ide> shell.open(); <ide> shell.layout(); <ide> display.sleep(); <ide> } <ide> } <del> return result; <del> } <del> <del> private void process(String dbURL) { <add> } <add> <add> private void setupUIAsFinished() { <add> textDatabaseDir.setEnabled(false); <add> textSourceFile.setEnabled(false); <add> btnOk.setVisible(false); <add> btnCancel.setText("Close"); <add> } <add> <add> private void process(String dbURL, String backupToRestore) { <ide> textOutput.append("Ready to create database " + dbURL + "\n"); <ide> try (Connection connection = new Connection(dbURL, true)) { <del> textOutput.append("Database " + dbURL + " created.\n"); <del> btnOk.setVisible(false); <del> btnCancel.setText("Close"); <add> textOutput.append("Database " + dbURL + " created.\n"); <add> try { <add> String serverAnnouncement = connection.getServerAnnouncement(); <add> textOutput.append(serverAnnouncement + "\n"); <add> Response response = connection.execute(backupToRestore); <add> response.awaitResult(999999); <add> setupUIAsFinished(); <add> } catch (IOException e1) { <add> textOutput.append("Unable to communicate with database due to " + e1.getMessage()); <add> } <ide> } catch (Exception e) { <ide> textOutput.append("Unable to create database " + dbURL + "\n"); <ide> textOutput.append(e.getMessage()); <ide> btnSourceFile.setLayoutData(fd_btnSourceFile); <ide> btnSourceFile.setText("Choose file..."); <ide> <del> Button btnOk = new Button(shell, SWT.NONE); <add> btnOk = new Button(shell, SWT.NONE); <ide> FormData fd_btnOk = new FormData(); <ide> btnOk.setLayoutData(fd_btnOk); <ide> btnOk.setText("Ok"); <ide> String databaseDir = textDatabaseDir.getText().trim(); <ide> if (databaseDir.length() == 0) { <ide> MessageDialog.openInformation(shell, "No Directory Specified", "No database directory was specified."); <add> return; <add> } <add> String sourceFileName = textSourceFile.getText().trim(); <add> if (sourceFileName.length() == 0) { <add> MessageDialog.openInformation(shell, "No Backup File Specified", "No database backup file to restore was specified."); <add> return; <add> } <add> File sourceFile = new File(sourceFileName); <add> if (!sourceFile.exists()) { <add> MessageDialog.openInformation(shell, "Unable to Open Backup File", "Database backup file cannot be found."); <add> return; <add> } <add> String backup = ""; <add> try { <add> backup = new String(Files.readAllBytes(sourceFile.toPath()), "UTF-8"); <add> } catch (IOException e2) { <add> MessageDialog.openInformation(shell, "Unable to Read Backup File", "The database backup file a can't be read due to " + e2.getMessage()); <add> return; <add> } <add> if (backup.trim().length() == 0) { <add> MessageDialog.openInformation(shell, "Unable to Read Backup File", "The database backup file appears to be empty or unreadable."); <ide> return; <ide> } <ide> String dbURL = "db:" + databaseDir; <ide> } catch (Exception e1) { <ide> Throwable cause = e1.getCause(); <ide> if (cause != null && cause.getMessage().startsWith("RS0406:")) <del> process(dbURL); <add> process(dbURL, backup); <ide> else <ide> MessageDialog.openError(shell, "Problem with Directory", "Unable to use " + dbURL + " due to: " + e1.getMessage()); <del> } <add> } <ide> }); <ide> <del> Button btnCancel = new Button(shell, SWT.NONE); <add> btnCancel = new Button(shell, SWT.NONE); <ide> FormData fd_btnCancel = new FormData(); <ide> btnCancel.setLayoutData(fd_btnCancel); <ide> btnCancel.setText("Cancel");
Java
apache-2.0
2d369a83cf29d8acb728878561b1f94668620a57
0
vatbub/common,vatbub/common
/*- * #%L * FOKProjects Common View Core * %% * Copyright (C) 2016 - 2020 Frederik Kammel * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ module common.view.core { requires javafx.graphics; requires javafx.controls; requires commons.lang; exports com.github.vatbub.common.view.core; }
view/core/src/main/java/module-info.java
/*- * #%L * FOKProjects Common View Core * %% * Copyright (C) 2016 - 2020 Frederik Kammel * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ module common.view.core { requires javafx.graphics; requires javafx.controls; requires commons.lang; }
Added module info to view.core
view/core/src/main/java/module-info.java
Added module info to view.core
<ide><path>iew/core/src/main/java/module-info.java <ide> requires javafx.graphics; <ide> requires javafx.controls; <ide> requires commons.lang; <add> <add> exports com.github.vatbub.common.view.core; <ide> }
Java
apache-2.0
0d83a7ce34510600826f556efb89f90aa90f0b83
0
yujiasun/Distributed-Kit
package com.distributed.lock.redis; import com.distributed.utils.JedisUtils; import org.jboss.netty.util.internal.NonReentrantLock; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.ReentrantLock; /** * Created by [email protected] on 2016/2/26. */ class RedisLockInternals { private static final org.slf4j.Logger log = LoggerFactory.getLogger(RedisLockInternals.class); private JedisPool jedisPool; /** * 重试等待时间 */ private int retryAwait=300; private int lockTimeout=60*1000; RedisLockInternals(JedisPool jedisPool) { this.jedisPool = jedisPool; } String tryRedisLock(String lockId,long time, TimeUnit unit) { final long startMillis = System.currentTimeMillis(); final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; String lockValue=null; while (lockValue==null){ lockValue=createRedisKey(lockId); if(lockValue!=null){ break; } if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){ break; } LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(retryAwait)); } return lockValue; } private String createRedisKey(String lockId) { Jedis jedis = null; boolean broken = false; try { String value=lockId+randomId(1); jedis = jedisPool.getResource(); String luaScript = "" + "\nlocal r = tonumber(redis.call('SETNX', KEYS[1],ARGV[1]));" + "\nredis.call('PEXPIRE',KEYS[1],ARGV[2]);" + "\nreturn r"; List<String> keys = new ArrayList<String>(); keys.add(lockId); List<String> args = new ArrayList<String>(); args.add(value); args.add(lockTimeout+""); Long ret = (Long) jedis.eval(luaScript, keys, args); if( new Long(1).equals(ret)){ return value; } } catch (JedisException e) { log.error(e.getMessage(),e); broken = JedisUtils.handleJedisException(jedisPool, e); } finally { JedisUtils.closeResource(jedisPool, jedis, broken); } return null; } void unlockRedisLock(String key,String value) { Jedis jedis = null; boolean broken = false; try { jedis = jedisPool.getResource(); String luaScript="" +"\nlocal v = redis.call('GET', KEYS[1]);" +"\nlocal r= 0;" +"\nif v == ARGV[1] then" +"\nr =redis.call('DEL',KEYS[1]);" +"\nend" +"\nreturn r"; List<String> keys = new ArrayList<String>(); keys.add(key); List<String> args = new ArrayList<String>(); args.add(value); Object r=jedis.eval(luaScript, keys, args); } catch (JedisException e) { log.error(e.getMessage(),e); broken = JedisUtils.handleJedisException(jedisPool, e); throw e; } finally { JedisUtils.closeResource(jedisPool,jedis, broken); } } private final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; private String randomId(int size) { char[] cs = new char[size]; for (int i = 0; i < cs.length; i++) { cs[i] = digits[ThreadLocalRandom.current().nextInt(digits.length)]; } return new String(cs); } public static void main(String[] args){ System.out.println(System.currentTimeMillis()); LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(300)); System.out.println(System.currentTimeMillis()); } }
src/main/java/com/distributed/lock/redis/RedisLockInternals.java
package com.distributed.lock.redis; import com.distributed.utils.JedisUtils; import org.jboss.netty.util.internal.NonReentrantLock; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by [email protected] on 2016/2/26. */ class RedisLockInternals { private static final org.slf4j.Logger log = LoggerFactory.getLogger(RedisLockInternals.class); private JedisPool jedisPool; /** * 重试等待时间 */ private int retryAwait=300; private int lockTimeout=60*1000; RedisLockInternals(JedisPool jedisPool) { this.jedisPool = jedisPool; } String tryRedisLock(String lockId,long time, TimeUnit unit) { final long startMillis = System.currentTimeMillis(); final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; String lockValue=null; ReentrantLock lock=new ReentrantLock(); try { lock.lock(); Condition reTryCondition = lock.newCondition(); while (lockValue==null){ lockValue=createRedisKey(lockId); if(lockValue!=null){ break; } if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){ break; } reTryCondition.await(retryAwait, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { log.error(e.getMessage(),e); Thread.interrupted(); }finally{ lock.unlock(); } return lockValue; } private String createRedisKey(String lockId) { Jedis jedis = null; boolean broken = false; try { String value=lockId+randomId(1); jedis = jedisPool.getResource(); String luaScript = "" + "\nlocal r = tonumber(redis.call('SETNX', KEYS[1],ARGV[1]));" + "\nredis.call('PEXPIRE',KEYS[1],ARGV[2]);" + "\nreturn r"; List<String> keys = new ArrayList<String>(); keys.add(lockId); List<String> args = new ArrayList<String>(); args.add(value); args.add(lockTimeout+""); Long ret = (Long) jedis.eval(luaScript, keys, args); if( new Long(1).equals(ret)){ return value; } } catch (JedisException e) { log.error(e.getMessage(),e); broken = JedisUtils.handleJedisException(jedisPool, e); } finally { JedisUtils.closeResource(jedisPool, jedis, broken); } return null; } void unlockRedisLock(String key,String value) { Jedis jedis = null; boolean broken = false; try { jedis = jedisPool.getResource(); String luaScript="" +"\nlocal v = redis.call('GET', KEYS[1]);" +"\nlocal r= 0;" +"\nif v == ARGV[1] then" +"\nr =redis.call('DEL',KEYS[1]);" +"\nend" +"\nreturn r"; List<String> keys = new ArrayList<String>(); keys.add(key); List<String> args = new ArrayList<String>(); args.add(value); Object r=jedis.eval(luaScript, keys, args); } catch (JedisException e) { log.error(e.getMessage(),e); broken = JedisUtils.handleJedisException(jedisPool, e); throw e; } finally { JedisUtils.closeResource(jedisPool,jedis, broken); } } private final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; private String randomId(int size) { char[] cs = new char[size]; for (int i = 0; i < cs.length; i++) { cs[i] = digits[ThreadLocalRandom.current().nextInt(digits.length)]; } return new String(cs); } }
使用底层的LockSupport直接完成定时阻塞的功能.
src/main/java/com/distributed/lock/redis/RedisLockInternals.java
使用底层的LockSupport直接完成定时阻塞的功能.
<ide><path>rc/main/java/com/distributed/lock/redis/RedisLockInternals.java <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.locks.Condition; <ide> import java.util.concurrent.locks.Lock; <add>import java.util.concurrent.locks.LockSupport; <ide> import java.util.concurrent.locks.ReentrantLock; <ide> <ide> /** <ide> final long startMillis = System.currentTimeMillis(); <ide> final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; <ide> String lockValue=null; <del> ReentrantLock lock=new ReentrantLock(); <del> try { <del> lock.lock(); <del> Condition reTryCondition = lock.newCondition(); <del> while (lockValue==null){ <del> lockValue=createRedisKey(lockId); <del> if(lockValue!=null){ <del> break; <del> } <del> if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){ <del> break; <del> } <del> reTryCondition.await(retryAwait, TimeUnit.MILLISECONDS); <add> while (lockValue==null){ <add> lockValue=createRedisKey(lockId); <add> if(lockValue!=null){ <add> break; <ide> } <del> } catch (InterruptedException e) { <del> log.error(e.getMessage(),e); <del> Thread.interrupted(); <del> }finally{ <del> lock.unlock(); <add> if(System.currentTimeMillis()-startMillis-retryAwait>millisToWait){ <add> break; <add> } <add> LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(retryAwait)); <ide> } <ide> return lockValue; <ide> } <ide> } <ide> return new String(cs); <ide> } <add> <add> public static void main(String[] args){ <add> System.out.println(System.currentTimeMillis()); <add> LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(300)); <add> System.out.println(System.currentTimeMillis()); <add> } <ide> }
Java
agpl-3.0
7ea82bb4b005ba2e47747c7487ca6816b16849a7
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.wrapper; import de.lmu.ifi.dbs.algorithm.KDDTask; import de.lmu.ifi.dbs.algorithm.clustering.OPTICS; import de.lmu.ifi.dbs.distance.VarianceDistanceFunction; import de.lmu.ifi.dbs.logging.LoggingConfiguration; import de.lmu.ifi.dbs.normalization.AttributeWiseRealVectorNormalization; import de.lmu.ifi.dbs.preprocessing.HiSCPreprocessor; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Wrapper class for HiSC algorithm. Performs an attribute wise normalization on * the database objects. * * @author Elke Achtert (<a href="mailto:[email protected]">[email protected]</a>) */ public class HiSCWrapper extends FileBasedDatabaseConnectionWrapper { /** * Holds the class specific debug status. */ @SuppressWarnings("unused") private static final boolean DEBUG = LoggingConfiguration.DEBUG; //private static final boolean DEBUG = true; /** * The logger of this class. */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * Description for parameter k. */ public static final String K_D = "<k>a positive integer specifying the number of " + "nearest neighbors considered to determine the preference vector. " + "If this value is not defined, k ist set to minpts."; /** * Main method to run this wrapper. * * @param args the arguments to run this wrapper */ public static void main(String[] args) { HiSCWrapper wrapper = new HiSCWrapper(); try { wrapper.run(args); } catch(ParameterException e) { wrapper.logger.log(Level.SEVERE, wrapper.optionHandler.usage(e.getMessage()), e); } } /** * Sets the parameter minpts and k in the parameter map additionally to the * parameters provided by super-classes. */ public HiSCWrapper() { super(); parameterToDescription.put(OPTICS.MINPTS_P + OptionHandler.EXPECTS_VALUE, OPTICS.MINPTS_D); parameterToDescription.put(HiSCPreprocessor.ALPHA_P + OptionHandler.EXPECTS_VALUE, HiSCPreprocessor.ALPHA_D); parameterToDescription.put(HiSCPreprocessor.K_P + OptionHandler.EXPECTS_VALUE, HiSCWrapper.K_D); optionHandler = new OptionHandler(parameterToDescription, getClass().getName()); } /** * @see de.lmu.ifi.dbs.wrapper.KDDTaskWrapper#getParameters() */ public List<String> getParameters() throws ParameterException { List<String> parameters = super.getParameters(); // OPTICS algorithm parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.ALGORITHM_P); parameters.add(OPTICS.class.getName()); // distance function parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.DISTANCE_FUNCTION_P); parameters.add(VarianceDistanceFunction.class.getName()); // omit flag parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.OMIT_PREPROCESSING_F); // epsilon for OPTICS parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.EPSILON_P); parameters.add(VarianceDistanceFunction.INFINITY_PATTERN); // minpts for OPTICS parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.MINPTS_P); parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); // preprocessor parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.PREPROCESSOR_CLASS_P); parameters.add(HiSCPreprocessor.class.getName()); // k for preprocessor parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.K_P); if(optionHandler.isSet(HiSCPreprocessor.K_P)) { parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.K_P)); } else { parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); } // alpha for preprocessor if(optionHandler.isSet(HiSCPreprocessor.ALPHA_P)) { parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.ALPHA_P); parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.ALPHA_P)); } // normalization parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_P); parameters.add(AttributeWiseRealVectorNormalization.class.getName()); parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_UNDO_F); return parameters; } }
src/de/lmu/ifi/dbs/wrapper/HiSCWrapper.java
package de.lmu.ifi.dbs.wrapper; import de.lmu.ifi.dbs.algorithm.KDDTask; import de.lmu.ifi.dbs.algorithm.clustering.OPTICS; import de.lmu.ifi.dbs.distance.VarianceDistanceFunction; import de.lmu.ifi.dbs.normalization.AttributeWiseRealVectorNormalization; import de.lmu.ifi.dbs.preprocessing.HiSCPreprocessor; import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Wrapper class for HiSC algorithm. Performs an attribute wise normalization on * the database objects. * * @author Elke Achtert (<a href="mailto:[email protected]">[email protected]</a>) */ public class HiSCWrapper extends FileBasedDatabaseConnectionWrapper { /** * Holds the class specific debug status. */ // private static final boolean DEBUG = LoggingConfiguration.DEBUG; @SuppressWarnings({"UNUSED_SYMBOL"}) private static final boolean DEBUG = true; /** * The logger of this class. */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * Description for parameter k. */ public static final String K_D = "<k>a positive integer specifying the number of " + "nearest neighbors considered to determine the preference vector. " + "If this value is not defined, k ist set to minpts."; /** * Main method to run this wrapper. * * @param args the arguments to run this wrapper */ public static void main(String[] args) { HiSCWrapper wrapper = new HiSCWrapper(); try { wrapper.run(args); } catch (ParameterException e) { wrapper.logger.log(Level.SEVERE, wrapper.optionHandler.usage(e.getMessage()), e); } } /** * Sets the parameter minpts and k in the parameter map additionally to the * parameters provided by super-classes. */ public HiSCWrapper() { super(); parameterToDescription.put(OPTICS.MINPTS_P + OptionHandler.EXPECTS_VALUE, OPTICS.MINPTS_D); parameterToDescription.put(HiSCPreprocessor.ALPHA_P + OptionHandler.EXPECTS_VALUE, HiSCPreprocessor.ALPHA_D); parameterToDescription.put(HiSCPreprocessor.K_P + OptionHandler.EXPECTS_VALUE, HiSCWrapper.K_D); optionHandler = new OptionHandler(parameterToDescription, getClass().getName()); } /** * @see de.lmu.ifi.dbs.wrapper.KDDTaskWrapper#getParameters() */ public List<String> getParameters() throws ParameterException { List<String> parameters = super.getParameters(); // OPTICS algorithm parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.ALGORITHM_P); parameters.add(OPTICS.class.getName()); // distance function parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.DISTANCE_FUNCTION_P); parameters.add(VarianceDistanceFunction.class.getName()); // omit flag parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.OMIT_PREPROCESSING_F); // epsilon for OPTICS parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.EPSILON_P); parameters.add(VarianceDistanceFunction.INFINITY_PATTERN); // minpts for OPTICS parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.MINPTS_P); parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); // preprocessor parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.PREPROCESSOR_CLASS_P); parameters.add(HiSCPreprocessor.class.getName()); // k for preprocessor parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.K_P); if (optionHandler.isSet(HiSCPreprocessor.K_P)) { parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.K_P)); } else { parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); } // alpha for preprocessor if (optionHandler.isSet(HiSCPreprocessor.ALPHA_P)) { parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.ALPHA_P); parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.ALPHA_P)); } // normalization parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_P); parameters.add(AttributeWiseRealVectorNormalization.class.getName()); parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_UNDO_F); return parameters; } }
logger debug false
src/de/lmu/ifi/dbs/wrapper/HiSCWrapper.java
logger debug false
<ide><path>rc/de/lmu/ifi/dbs/wrapper/HiSCWrapper.java <ide> import de.lmu.ifi.dbs.algorithm.KDDTask; <ide> import de.lmu.ifi.dbs.algorithm.clustering.OPTICS; <ide> import de.lmu.ifi.dbs.distance.VarianceDistanceFunction; <add>import de.lmu.ifi.dbs.logging.LoggingConfiguration; <ide> import de.lmu.ifi.dbs.normalization.AttributeWiseRealVectorNormalization; <ide> import de.lmu.ifi.dbs.preprocessing.HiSCPreprocessor; <ide> import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler; <ide> * <ide> * @author Elke Achtert (<a href="mailto:[email protected]">[email protected]</a>) <ide> */ <del>public class HiSCWrapper extends FileBasedDatabaseConnectionWrapper { <del> /** <del> * Holds the class specific debug status. <del> */ <del>// private static final boolean DEBUG = LoggingConfiguration.DEBUG; <del> @SuppressWarnings({"UNUSED_SYMBOL"}) <del> private static final boolean DEBUG = true; <add>public class HiSCWrapper extends FileBasedDatabaseConnectionWrapper <add>{ <add> /** <add> * Holds the class specific debug status. <add> */ <add> @SuppressWarnings("unused") <add> private static final boolean DEBUG = LoggingConfiguration.DEBUG; <add> <add> //private static final boolean DEBUG = true; <ide> <del> /** <del> * The logger of this class. <del> */ <del> private Logger logger = Logger.getLogger(this.getClass().getName()); <add> /** <add> * The logger of this class. <add> */ <add> private Logger logger = Logger.getLogger(this.getClass().getName()); <ide> <del> /** <del> * Description for parameter k. <del> */ <del> public static final String K_D = "<k>a positive integer specifying the number of " + <del> "nearest neighbors considered to determine the preference vector. " + <del> "If this value is not defined, k ist set to minpts."; <add> /** <add> * Description for parameter k. <add> */ <add> public static final String K_D = "<k>a positive integer specifying the number of " + "nearest neighbors considered to determine the preference vector. " + "If this value is not defined, k ist set to minpts."; <ide> <del> /** <del> * Main method to run this wrapper. <del> * <del> * @param args the arguments to run this wrapper <del> */ <del> public static void main(String[] args) { <del> HiSCWrapper wrapper = new HiSCWrapper(); <del> try { <del> wrapper.run(args); <del> } <del> catch (ParameterException e) { <del> wrapper.logger.log(Level.SEVERE, wrapper.optionHandler.usage(e.getMessage()), e); <del> } <del> } <del> <del> /** <del> * Sets the parameter minpts and k in the parameter map additionally to the <del> * parameters provided by super-classes. <del> */ <del> public HiSCWrapper() { <del> super(); <del> parameterToDescription.put(OPTICS.MINPTS_P + OptionHandler.EXPECTS_VALUE, OPTICS.MINPTS_D); <del> parameterToDescription.put(HiSCPreprocessor.ALPHA_P + OptionHandler.EXPECTS_VALUE, HiSCPreprocessor.ALPHA_D); <del> parameterToDescription.put(HiSCPreprocessor.K_P + OptionHandler.EXPECTS_VALUE, HiSCWrapper.K_D); <del> optionHandler = new OptionHandler(parameterToDescription, getClass().getName()); <del> } <del> <del> /** <del> * @see de.lmu.ifi.dbs.wrapper.KDDTaskWrapper#getParameters() <del> */ <del> public List<String> getParameters() throws ParameterException { <del> List<String> parameters = super.getParameters(); <del> <del> // OPTICS algorithm <del> parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.ALGORITHM_P); <del> parameters.add(OPTICS.class.getName()); <del> <del> // distance function <del> parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.DISTANCE_FUNCTION_P); <del> parameters.add(VarianceDistanceFunction.class.getName()); <del> <del> // omit flag <del> parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.OMIT_PREPROCESSING_F); <del> <del> // epsilon for OPTICS <del> parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.EPSILON_P); <del> parameters.add(VarianceDistanceFunction.INFINITY_PATTERN); <del> <del> // minpts for OPTICS <del> parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.MINPTS_P); <del> parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); <del> <del> // preprocessor <del> parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.PREPROCESSOR_CLASS_P); <del> parameters.add(HiSCPreprocessor.class.getName()); <del> <del> // k for preprocessor <del> parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.K_P); <del> if (optionHandler.isSet(HiSCPreprocessor.K_P)) { <del> parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.K_P)); <del> } <del> else { <del> parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); <add> /** <add> * Main method to run this wrapper. <add> * <add> * @param args the arguments to run this wrapper <add> */ <add> public static void main(String[] args) <add> { <add> HiSCWrapper wrapper = new HiSCWrapper(); <add> try <add> { <add> wrapper.run(args); <add> } <add> catch(ParameterException e) <add> { <add> wrapper.logger.log(Level.SEVERE, wrapper.optionHandler.usage(e.getMessage()), e); <add> } <ide> } <ide> <del> // alpha for preprocessor <del> if (optionHandler.isSet(HiSCPreprocessor.ALPHA_P)) { <del> parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.ALPHA_P); <del> parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.ALPHA_P)); <add> /** <add> * Sets the parameter minpts and k in the parameter map additionally to the <add> * parameters provided by super-classes. <add> */ <add> public HiSCWrapper() <add> { <add> super(); <add> parameterToDescription.put(OPTICS.MINPTS_P + OptionHandler.EXPECTS_VALUE, OPTICS.MINPTS_D); <add> parameterToDescription.put(HiSCPreprocessor.ALPHA_P + OptionHandler.EXPECTS_VALUE, HiSCPreprocessor.ALPHA_D); <add> parameterToDescription.put(HiSCPreprocessor.K_P + OptionHandler.EXPECTS_VALUE, HiSCWrapper.K_D); <add> optionHandler = new OptionHandler(parameterToDescription, getClass().getName()); <ide> } <ide> <del> // normalization <del> parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_P); <del> parameters.add(AttributeWiseRealVectorNormalization.class.getName()); <del> parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_UNDO_F); <add> /** <add> * @see de.lmu.ifi.dbs.wrapper.KDDTaskWrapper#getParameters() <add> */ <add> public List<String> getParameters() throws ParameterException <add> { <add> List<String> parameters = super.getParameters(); <ide> <del> return parameters; <del> } <add> // OPTICS algorithm <add> parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.ALGORITHM_P); <add> parameters.add(OPTICS.class.getName()); <add> <add> // distance function <add> parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.DISTANCE_FUNCTION_P); <add> parameters.add(VarianceDistanceFunction.class.getName()); <add> <add> // omit flag <add> parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.OMIT_PREPROCESSING_F); <add> <add> // epsilon for OPTICS <add> parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.EPSILON_P); <add> parameters.add(VarianceDistanceFunction.INFINITY_PATTERN); <add> <add> // minpts for OPTICS <add> parameters.add(OptionHandler.OPTION_PREFIX + OPTICS.MINPTS_P); <add> parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); <add> <add> // preprocessor <add> parameters.add(OptionHandler.OPTION_PREFIX + VarianceDistanceFunction.PREPROCESSOR_CLASS_P); <add> parameters.add(HiSCPreprocessor.class.getName()); <add> <add> // k for preprocessor <add> parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.K_P); <add> if(optionHandler.isSet(HiSCPreprocessor.K_P)) <add> { <add> parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.K_P)); <add> } <add> else <add> { <add> parameters.add(optionHandler.getOptionValue(OPTICS.MINPTS_P)); <add> } <add> <add> // alpha for preprocessor <add> if(optionHandler.isSet(HiSCPreprocessor.ALPHA_P)) <add> { <add> parameters.add(OptionHandler.OPTION_PREFIX + HiSCPreprocessor.ALPHA_P); <add> parameters.add(optionHandler.getOptionValue(HiSCPreprocessor.ALPHA_P)); <add> } <add> <add> // normalization <add> parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_P); <add> parameters.add(AttributeWiseRealVectorNormalization.class.getName()); <add> parameters.add(OptionHandler.OPTION_PREFIX + KDDTask.NORMALIZATION_UNDO_F); <add> <add> return parameters; <add> } <ide> }
JavaScript
mit
110b38439944a0cd643352cb23266021aebd6f2a
0
hks-epod/paydash
'use strict'; var Joi = require('joi'); var _ = require('lodash'); var Notifier = require('../../helpers/notifier'); exports.showUnreadNotifications = { description: 'Show unread notifications', handler: function(request, reply) { // var db = request.server.plugins.sequelize.db; // var notifications = request.server.plugins.sequelize.db.notifications; var ctx = { notifications: [] }; // notifications.findAll({ // where: { // user_id: request.auth.credentials.id, // viewed: 0 // } // }).then(function(unread) { // unread.forEach(function(n) { // n.dataValues.msg = Notifier.message(n, request); // }); // ctx.notifications = _.groupBy(unread, function(n) { // return n.batch_id; // }); // notifications.update({ // viewed: 1 // }, { // where: { // user_id: request.auth.credentials.id, // viewed: 0 // } // }); reply.view('alerts/notifications-unread', ctx); }); } }; exports.showReadNotifications = { description: 'Show notifications', handler: function(request, reply) { // var db = request.server.plugins.sequelize.db; // var notifications = request.server.plugins.sequelize.db.notifications; var ctx = { notifications: [] }; // notifications.findAll({ // where: { // user_id: request.auth.credentials.id, // viewed: 1 // } // }).then(function(read) { // read.forEach(function(n) { // n.dataValues.msg = Notifier.message(n, request); // }); // ctx.notifications = _.groupBy(read, function(n) { // return n.batch_id; // }); reply.view('alerts/notifications-read', ctx); }); } };
app/controllers/alerts/notifications.js
'use strict'; var Joi = require('joi'); var _ = require('lodash'); var Notifier = require('../../helpers/notifier'); exports.showUnreadNotifications = { description: 'Show unread notifications', handler: function(request, reply) { var db = request.server.plugins.sequelize.db; var notifications = request.server.plugins.sequelize.db.notifications; var ctx = { notifications: null }; notifications.findAll({ where: { user_id: request.auth.credentials.id, viewed: 0 } }).then(function(unread) { unread.forEach(function(n) { n.dataValues.msg = Notifier.message(n, request); }); ctx.notifications = _.groupBy(unread, function(n) { return n.batch_id; }); notifications.update({ viewed: 1 }, { where: { user_id: request.auth.credentials.id, viewed: 0 } }); reply.view('alerts/notifications-unread', ctx); }); } }; exports.showReadNotifications = { description: 'Show notifications', handler: function(request, reply) { var db = request.server.plugins.sequelize.db; var notifications = request.server.plugins.sequelize.db.notifications; var ctx = { notifications: null }; notifications.findAll({ where: { user_id: request.auth.credentials.id, viewed: 1 } }).then(function(read) { read.forEach(function(n) { n.dataValues.msg = Notifier.message(n, request); }); ctx.notifications = _.groupBy(read, function(n) { return n.batch_id; }); reply.view('alerts/notifications-read', ctx); }); } };
send empty array for notifications data on web version
app/controllers/alerts/notifications.js
send empty array for notifications data on web version
<ide><path>pp/controllers/alerts/notifications.js <ide> description: 'Show unread notifications', <ide> handler: function(request, reply) { <ide> <del> var db = request.server.plugins.sequelize.db; <del> var notifications = request.server.plugins.sequelize.db.notifications; <add> // var db = request.server.plugins.sequelize.db; <add> // var notifications = request.server.plugins.sequelize.db.notifications; <ide> var ctx = { <del> notifications: null <add> notifications: [] <ide> }; <del> notifications.findAll({ <del> where: { <del> user_id: request.auth.credentials.id, <del> viewed: 0 <del> } <add> // notifications.findAll({ <add> // where: { <add> // user_id: request.auth.credentials.id, <add> // viewed: 0 <add> // } <ide> <del> }).then(function(unread) { <add> // }).then(function(unread) { <ide> <del> unread.forEach(function(n) { <del> n.dataValues.msg = Notifier.message(n, request); <del> }); <add> // unread.forEach(function(n) { <add> // n.dataValues.msg = Notifier.message(n, request); <add> // }); <ide> <del> ctx.notifications = _.groupBy(unread, function(n) { <del> return n.batch_id; <del> }); <add> // ctx.notifications = _.groupBy(unread, function(n) { <add> // return n.batch_id; <add> // }); <ide> <del> notifications.update({ <del> viewed: 1 <del> }, { <del> where: { <del> user_id: request.auth.credentials.id, <del> viewed: 0 <del> } <del> }); <add> // notifications.update({ <add> // viewed: 1 <add> // }, { <add> // where: { <add> // user_id: request.auth.credentials.id, <add> // viewed: 0 <add> // } <add> // }); <ide> reply.view('alerts/notifications-unread', ctx); <ide> }); <ide> <ide> description: 'Show notifications', <ide> handler: function(request, reply) { <ide> <del> var db = request.server.plugins.sequelize.db; <del> var notifications = request.server.plugins.sequelize.db.notifications; <add> // var db = request.server.plugins.sequelize.db; <add> // var notifications = request.server.plugins.sequelize.db.notifications; <ide> var ctx = { <del> notifications: null <add> notifications: [] <ide> }; <ide> <del> notifications.findAll({ <del> where: { <del> user_id: request.auth.credentials.id, <del> viewed: 1 <del> } <del> }).then(function(read) { <add> // notifications.findAll({ <add> // where: { <add> // user_id: request.auth.credentials.id, <add> // viewed: 1 <add> // } <add> // }).then(function(read) { <ide> <del> read.forEach(function(n) { <del> n.dataValues.msg = Notifier.message(n, request); <del> }); <add> // read.forEach(function(n) { <add> // n.dataValues.msg = Notifier.message(n, request); <add> // }); <ide> <del> ctx.notifications = _.groupBy(read, function(n) { <del> return n.batch_id; <del> }); <add> // ctx.notifications = _.groupBy(read, function(n) { <add> // return n.batch_id; <add> // }); <ide> <ide> reply.view('alerts/notifications-read', ctx); <ide> });
Java
apache-2.0
b4cf97ba67e8cdfc6abb9b153637ed1f5182959b
0
0359xiaodong/dmix,philchand/mpdroid-2014,joansmith/dmix,jcnoir/dmix,hurzl/dmix,0359xiaodong/dmix,eisnerd/mupeace,jcnoir/dmix,philchand/mpdroid-2014,abarisain/dmix,abarisain/dmix,philchand/mpdroid-2014,philchand/mpdroid-2014,hurzl/dmix,eisnerd/mupeace,eisnerd/mupeace,joansmith/dmix
package com.namelessdev.mpdroid; import java.util.Collection; import java.util.LinkedList; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnKeyListener; import android.content.Intent; import android.net.ConnectivityManager; import android.os.StrictMode; import android.view.KeyEvent; import android.view.WindowManager.BadTokenException; import com.namelessdev.mpdroid.MPDAsyncHelper.ConnectionListener; import com.namelessdev.mpdroid.tools.SettingsHelper; public class MPDApplication extends Application implements ConnectionListener { // Change this... (sag) public MPDAsyncHelper oMPDAsyncHelper = null; private SettingsHelper settingsHelper = null; private ApplicationState state = new ApplicationState(); private Collection<Object> connectionLocks = new LinkedList<Object>(); private AlertDialog ad; private Activity currentActivity; public class ApplicationState { public boolean streamingMode = false; public boolean settingsShown = false; public boolean warningShown = false; } class DialogClickListener implements OnClickListener { public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_NEUTRAL: // Show Settings currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); break; case AlertDialog.BUTTON_NEGATIVE: currentActivity.finish(); break; case AlertDialog.BUTTON_POSITIVE: connectMPD(); break; } } } public static final int SETTINGS = 5; @Override public void onCreate() { super.onCreate(); System.err.println("onCreate Application"); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } oMPDAsyncHelper = new MPDAsyncHelper(); oMPDAsyncHelper.addConnectionListener((MPDApplication) getApplicationContext()); settingsHelper = new SettingsHelper(this, oMPDAsyncHelper); } public void setActivity(Object activity) { if (activity instanceof Activity) currentActivity = (Activity) activity; connectionLocks.add(activity); checkMonitorNeeded(); checkConnectionNeeded(); } public void unsetActivity(Object activity) { connectionLocks.remove(activity); checkMonitorNeeded(); checkConnectionNeeded(); if (currentActivity == activity) currentActivity = null; } private void checkMonitorNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.isMonitorAlive()) oMPDAsyncHelper.startMonitor(); } else { oMPDAsyncHelper.stopMonitor(); } } private void checkConnectionNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.oMPD.isConnected() && (currentActivity == null || !currentActivity.getClass().equals(WifiConnectionSettings.class))) connect(); } else { disconnect(); } } public void connect() { if(!settingsHelper.updateSettings()) { // Absolutely no settings defined! Open Settings! if (currentActivity != null && !state.settingsShown) { currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); state.settingsShown = true; } } if (currentActivity != null && !settingsHelper.warningShown() && !state.warningShown) { currentActivity.startActivity(new Intent(currentActivity, WarningActivity.class)); state.warningShown = true; } connectMPD(); } public void disconnect() { oMPDAsyncHelper.disconnect(); } private void connectMPD() { // dismiss possible dialog dismissAlertDialog(); // check for network if (!isNetworkConnected()) { connectionFailed("No network."); return; } // show connecting to server dialog if (currentActivity != null) { ad = new ProgressDialog(currentActivity); ad.setTitle(getResources().getString(R.string.connecting)); ad.setMessage(getResources().getString(R.string.connectingToServer)); ad.setCancelable(false); ad.setOnKeyListener(new OnKeyListener() { public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // Handle all keys! return true; } }); try { ad.show(); } catch (BadTokenException e) { // Can't display it. Don't care. } } // really connect oMPDAsyncHelper.connect(); } public void connectionFailed(String message) { // dismiss possible dialog dismissAlertDialog(); if (currentActivity == null) return; if (currentActivity != null && connectionLocks.size() > 0) { // are we in the settings activity? if (currentActivity.getClass() == SettingsActivity.class) { AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity); builder.setMessage(String.format(getResources().getString(R.string.connectionFailedMessageSetting), message)); builder.setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); ad = builder.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity); builder.setTitle(getResources().getString(R.string.connectionFailed)); builder.setMessage(String.format(getResources().getString(R.string.connectionFailedMessage), message)); DialogClickListener oDialogClickListener = new DialogClickListener(); builder.setNegativeButton(getResources().getString(R.string.quit), oDialogClickListener); builder.setNeutralButton(getResources().getString(R.string.settings), oDialogClickListener); builder.setPositiveButton(getResources().getString(R.string.retry), oDialogClickListener); try { ad = builder.show(); } catch (BadTokenException e) { // Can't display it. Don't care. } } } } public void connectionSucceeded(String message) { dismissAlertDialog(); // checkMonitorNeeded(); } public ApplicationState getApplicationState() { return state; } private boolean isNetworkConnected() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (conMgr.getActiveNetworkInfo() == null) return false; return (conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()); } private void dismissAlertDialog() { if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } } }
MPDroid/src/com/namelessdev/mpdroid/MPDApplication.java
package com.namelessdev.mpdroid; import java.util.Collection; import java.util.LinkedList; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnKeyListener; import android.content.Intent; import android.net.ConnectivityManager; import android.os.StrictMode; import android.view.KeyEvent; import android.view.WindowManager.BadTokenException; import com.namelessdev.mpdroid.MPDAsyncHelper.ConnectionListener; import com.namelessdev.mpdroid.tools.SettingsHelper; public class MPDApplication extends Application implements ConnectionListener { // Change this... (sag) public MPDAsyncHelper oMPDAsyncHelper = null; private SettingsHelper settingsHelper = null; private ApplicationState state = new ApplicationState(); private Collection<Object> connectionLocks = new LinkedList<Object>(); private AlertDialog ad; private Activity currentActivity; public class ApplicationState { public boolean streamingMode = false; public boolean settingsShown = false; public boolean warningShown = false; } class DialogClickListener implements OnClickListener { public void onClick(DialogInterface dialog, int which) { switch (which) { case AlertDialog.BUTTON_NEUTRAL: // Show Settings currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); break; case AlertDialog.BUTTON_NEGATIVE: currentActivity.finish(); break; case AlertDialog.BUTTON_POSITIVE: connectMPD(); break; } } } public static final int SETTINGS = 5; @Override public void onCreate() { super.onCreate(); System.err.println("onCreate Application"); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); oMPDAsyncHelper = new MPDAsyncHelper(); oMPDAsyncHelper.addConnectionListener((MPDApplication) getApplicationContext()); settingsHelper = new SettingsHelper(this, oMPDAsyncHelper); } public void setActivity(Object activity) { if (activity instanceof Activity) currentActivity = (Activity) activity; connectionLocks.add(activity); checkMonitorNeeded(); checkConnectionNeeded(); } public void unsetActivity(Object activity) { connectionLocks.remove(activity); checkMonitorNeeded(); checkConnectionNeeded(); if (currentActivity == activity) currentActivity = null; } private void checkMonitorNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.isMonitorAlive()) oMPDAsyncHelper.startMonitor(); } else { oMPDAsyncHelper.stopMonitor(); } } private void checkConnectionNeeded() { if (connectionLocks.size() > 0) { if (!oMPDAsyncHelper.oMPD.isConnected() && (currentActivity == null || !currentActivity.getClass().equals(WifiConnectionSettings.class))) connect(); } else { disconnect(); } } public void connect() { if(!settingsHelper.updateSettings()) { // Absolutely no settings defined! Open Settings! if (currentActivity != null && !state.settingsShown) { currentActivity.startActivityForResult(new Intent(currentActivity, WifiConnectionSettings.class), SETTINGS); state.settingsShown = true; } } if (currentActivity != null && !settingsHelper.warningShown() && !state.warningShown) { currentActivity.startActivity(new Intent(currentActivity, WarningActivity.class)); state.warningShown = true; } connectMPD(); } public void disconnect() { oMPDAsyncHelper.disconnect(); } private void connectMPD() { // dismiss possible dialog dismissAlertDialog(); // check for network if (!isNetworkConnected()) { connectionFailed("No network."); return; } // show connecting to server dialog if (currentActivity != null) { ad = new ProgressDialog(currentActivity); ad.setTitle(getResources().getString(R.string.connecting)); ad.setMessage(getResources().getString(R.string.connectingToServer)); ad.setCancelable(false); ad.setOnKeyListener(new OnKeyListener() { public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // Handle all keys! return true; } }); try { ad.show(); } catch (BadTokenException e) { // Can't display it. Don't care. } } // really connect oMPDAsyncHelper.connect(); } public void connectionFailed(String message) { // dismiss possible dialog dismissAlertDialog(); if (currentActivity == null) return; if (currentActivity != null && connectionLocks.size() > 0) { // are we in the settings activity? if (currentActivity.getClass() == SettingsActivity.class) { AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity); builder.setMessage(String.format(getResources().getString(R.string.connectionFailedMessageSetting), message)); builder.setPositiveButton("OK", new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); ad = builder.show(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity); builder.setTitle(getResources().getString(R.string.connectionFailed)); builder.setMessage(String.format(getResources().getString(R.string.connectionFailedMessage), message)); DialogClickListener oDialogClickListener = new DialogClickListener(); builder.setNegativeButton(getResources().getString(R.string.quit), oDialogClickListener); builder.setNeutralButton(getResources().getString(R.string.settings), oDialogClickListener); builder.setPositiveButton(getResources().getString(R.string.retry), oDialogClickListener); try { ad = builder.show(); } catch (BadTokenException e) { // Can't display it. Don't care. } } } } public void connectionSucceeded(String message) { dismissAlertDialog(); // checkMonitorNeeded(); } public ApplicationState getApplicationState() { return state; } private boolean isNetworkConnected() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (conMgr.getActiveNetworkInfo() == null) return false; return (conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()); } private void dismissAlertDialog() { if (ad != null) { if (ad.isShowing()) { try { ad.dismiss(); } catch (IllegalArgumentException e) { // We don't care, it has already been destroyed } } } } }
Fixed a crash at startup on devices with android version < 9
MPDroid/src/com/namelessdev/mpdroid/MPDApplication.java
Fixed a crash at startup on devices with android version < 9
<ide><path>PDroid/src/com/namelessdev/mpdroid/MPDApplication.java <ide> super.onCreate(); <ide> System.err.println("onCreate Application"); <ide> <del> StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); <del> StrictMode.setThreadPolicy(policy); <add> if (android.os.Build.VERSION.SDK_INT > 9) { <add> StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); <add> StrictMode.setThreadPolicy(policy); <add> } <ide> <ide> oMPDAsyncHelper = new MPDAsyncHelper(); <ide> oMPDAsyncHelper.addConnectionListener((MPDApplication) getApplicationContext());
Java
epl-1.0
aeebd8e9e9aea41e14680784816188d2d8bb28a5
0
theArchonius/mervin,theArchonius/mervin
/******************************************************************************* * Copyright (c) 2015, 2016, 2017 Florian Zoubek. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Florian Zoubek - initial API and implementation *******************************************************************************/ package at.bitandart.zoubek.mervin.property.diff; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.emf.compare.Comparison; import org.eclipse.emf.compare.Match; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import at.bitandart.zoubek.mervin.IDiagramModelHelper; import at.bitandart.zoubek.mervin.draw2d.figures.overlay.IOverlayTypeStyleAdvisor; import at.bitandart.zoubek.mervin.draw2d.figures.overlay.OverlayType; import at.bitandart.zoubek.mervin.model.modelreview.ModelReview; import at.bitandart.zoubek.mervin.property.diff.PropertyDiffItemProvider.SelectionEntry; import at.bitandart.zoubek.mervin.review.ModelReviewEditorTrackingView; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiff; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiffSide; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiffType; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiffViewer; /** * A {@link ModelReviewEditorTrackingView} that shows a side-by-side tree diff * of the currently selected model element. * * @author Florian Zoubek * */ public class PropertyDiffView extends ModelReviewEditorTrackingView { /** * id of the part descriptor for this view */ public static final String PART_DESCRIPTOR_ID = "at.bitandart.zoubek.mervin.partdescriptor.properties.diff"; /** * helper utility class that is used to retrieve information about the * diagram model. */ @Inject private IDiagramModelHelper diagramModelHelper; /** * the main panel of this view that contains all controls for this view. */ private Composite mainPanel; /** * the side-by-side tree diff viewer used to show the differences of the * current selection */ private TreeDiffViewer diffViewer; /** * indicates if the view's control have been correctly initialized */ private boolean viewInitialized = false; /** * the {@link IOverlayTypeStyleAdvisor} to use for the colors of the * property diff viewer */ @Inject private IOverlayTypeStyleAdvisor styleAdvisor; @Inject public PropertyDiffView() { } @PostConstruct public void postConstruct(Composite parent) { mainPanel = new Composite(parent, SWT.NONE); mainPanel.setLayout(new GridLayout()); diffViewer = new TreeDiffViewer(mainPanel); TreeDiff treeDiff = diffViewer.getTreeDiff(); treeDiff.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); diffViewer.setTreeDiffItemProvider(new PropertyDiffItemProvider()); treeDiff.setChangedSide(TreeDiffSide.LEFT); /* assign the colors of the style advisor */ treeDiff.setDiffColor(TreeDiffType.ADD, styleAdvisor.getForegroundColorForOverlayType(OverlayType.ADDITION)); treeDiff.setDiffColor(TreeDiffType.DELETE, styleAdvisor.getForegroundColorForOverlayType(OverlayType.DELETION)); treeDiff.setDiffColor(TreeDiffType.MODIFY, styleAdvisor.getForegroundColorForOverlayType(OverlayType.MODIFICATION)); viewInitialized = true; } @Inject public void setSelection(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (viewInitialized && selection != null) { Object propertyDiffInput = createInputFromSelection(selection); if (propertyDiffInput != null) { diffViewer.setInput(propertyDiffInput); diffViewer.refresh(); } else { /* no input for the current selection found -> clear viewer */ diffViewer.setInput(null); diffViewer.refresh(); } } } /** * creates the input object for the tree diff viewer based on the given * selection. * * @param selection * the selection used to create the input object for. * @return the input object for the tree diff viewer. */ private Object createInputFromSelection(IStructuredSelection selection) { ModelReview currentModelReview = getCurrentModelReview(); Comparison modelComparison = getModelComparison(); Comparison diagramComparison = getDiagramComparison(); List<SelectionEntry> modelEntries = new ArrayList<>(selection.size()); if (modelComparison != null || diagramComparison != null) { Iterator<?> selectionIterator = selection.iterator(); int selectionIndex = 1; while (selectionIterator.hasNext()) { Object object = selectionIterator.next(); EObject selectedSemanticModelElement = diagramModelHelper.getSemanticModel(object); View selectedNotationModelElement = diagramModelHelper.getNotationModel(object); if (currentModelReview != null) { View originalNotationModelElement = (View) currentModelReview.getUnifiedModelMap() .getOriginal(selectedNotationModelElement); if (originalNotationModelElement != null) { selectedNotationModelElement = originalNotationModelElement; } } Match semanticModelMatch = null; if (modelComparison != null) { semanticModelMatch = modelComparison.getMatch(selectedSemanticModelElement); } Match notationModelMatch = null; if (diagramComparison != null) { notationModelMatch = diagramComparison.getMatch(selectedNotationModelElement); } /* * create an entry only if the selection contains a model * element contained in the comparison */ if (semanticModelMatch != null || notationModelMatch != null) { SelectionEntry modelEntry = new SelectionEntry(null, selectionIndex + ". ", semanticModelMatch, notationModelMatch); modelEntries.add(modelEntry); // TODO add other (referencing, context, etc...) notation // models selectionIndex++; } } } return modelEntries; } /** * @return the diagram comparison to use for this view. */ private Comparison getDiagramComparison() { ModelReview currentModelReview = getCurrentModelReview(); if (currentModelReview != null) { return currentModelReview.getSelectedDiagramComparison(); } return null; } /** * @return the model comparison to use for this view. */ private Comparison getModelComparison() { ModelReview currentModelReview = getCurrentModelReview(); if (currentModelReview != null) { return currentModelReview.getSelectedModelComparison(); } return null; } @Override protected void updateValues() { if (viewInitialized) { ModelReview modelReview = getCurrentModelReview(); if (modelReview == null) { /* no active model review -> clear diff viewer if necessary */ if (diffViewer != null && diffViewer.getInput() != null) { diffViewer.setInput(null); diffViewer.refresh(); } } } } }
plugins/at.bitandart.zoubek.mervin/src/at/bitandart/zoubek/mervin/property/diff/PropertyDiffView.java
/******************************************************************************* * Copyright (c) 2015, 2016, 2017 Florian Zoubek. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Florian Zoubek - initial API and implementation *******************************************************************************/ package at.bitandart.zoubek.mervin.property.diff; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.emf.compare.Comparison; import org.eclipse.emf.compare.Match; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import at.bitandart.zoubek.mervin.IDiagramModelHelper; import at.bitandart.zoubek.mervin.draw2d.figures.overlay.IOverlayTypeStyleAdvisor; import at.bitandart.zoubek.mervin.draw2d.figures.overlay.OverlayType; import at.bitandart.zoubek.mervin.model.modelreview.ModelReview; import at.bitandart.zoubek.mervin.property.diff.PropertyDiffItemProvider.SelectionEntry; import at.bitandart.zoubek.mervin.review.ModelReviewEditorTrackingView; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiff; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiffSide; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiffType; import at.bitandart.zoubek.mervin.swt.diff.tree.TreeDiffViewer; /** * A {@link ModelReviewEditorTrackingView} that shows a side-by-side tree diff * of the currently selected model element. * * @author Florian Zoubek * */ public class PropertyDiffView extends ModelReviewEditorTrackingView { /** * id of the part descriptor for this view */ public static final String PART_DESCRIPTOR_ID = "at.bitandart.zoubek.mervin.partdescriptor.properties.diff"; /** * helper utility class that is used to retrieve information about the * diagram model. */ @Inject private IDiagramModelHelper diagramModelHelper; /** * the main panel of this view that contains all controls for this view. */ private Composite mainPanel; /** * the side-by-side tree diff viewer used to show the differences of the * current selection */ private TreeDiffViewer diffViewer; /** * indicates if the view's control have been correctly initialized */ private boolean viewInitialized = false; /** * the {@link IOverlayTypeStyleAdvisor} to use for the colors of the * property diff viewer */ @Inject private IOverlayTypeStyleAdvisor styleAdvisor; @Inject public PropertyDiffView() { } @PostConstruct public void postConstruct(Composite parent) { mainPanel = new Composite(parent, SWT.NONE); mainPanel.setLayout(new GridLayout()); diffViewer = new TreeDiffViewer(mainPanel); TreeDiff treeDiff = diffViewer.getTreeDiff(); treeDiff.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); diffViewer.setTreeDiffItemProvider(new PropertyDiffItemProvider()); treeDiff.setChangedSide(TreeDiffSide.LEFT); /* assign the colors of the style advisor */ treeDiff.setDiffColor(TreeDiffType.ADD, styleAdvisor.getForegroundColorForOverlayType(OverlayType.ADDITION)); treeDiff.setDiffColor(TreeDiffType.DELETE, styleAdvisor.getForegroundColorForOverlayType(OverlayType.DELETION)); treeDiff.setDiffColor(TreeDiffType.MODIFY, styleAdvisor.getForegroundColorForOverlayType(OverlayType.MODIFICATION)); viewInitialized = true; } @Inject public void setSelection(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (viewInitialized && selection != null) { Object propertyDiffInput = createInputFromSelection(selection); if (propertyDiffInput != null) { diffViewer.setInput(propertyDiffInput); diffViewer.refresh(); } else { /* no input for the current selection found -> clear viewer */ diffViewer.setInput(null); diffViewer.refresh(); } } } /** * creates the input object for the tree diff viewer based on the given * selection. * * @param selection * the selection used to create the input object for. * @return the input object for the tree diff viewer. */ private Object createInputFromSelection(IStructuredSelection selection) { Comparison comparison = getComparison(selection); List<SelectionEntry> modelEntries = new ArrayList<>(selection.size()); if (comparison != null) { Iterator<?> selectionIterator = selection.iterator(); int selectionIndex = 1; while (selectionIterator.hasNext()) { Object object = selectionIterator.next(); EObject selectedSemanticModelElement = diagramModelHelper.getSemanticModel(object); View selectedNotationModelElement = diagramModelHelper.getNotationModel(object); ModelReview currentModelReview = getCurrentModelReview(); if (currentModelReview != null) { View originalNotationModelElement = (View) currentModelReview.getUnifiedModelMap() .getOriginal(selectedNotationModelElement); if (originalNotationModelElement != null) { selectedNotationModelElement = originalNotationModelElement; } } Match semanticModelMatch = comparison.getMatch(selectedSemanticModelElement); Match notationModelMatch = comparison.getMatch(selectedNotationModelElement); /* * create an entry only if the selection contains a model * element contained in the comparison */ if (semanticModelMatch != null || notationModelMatch != null) { SelectionEntry modelEntry = new SelectionEntry(null, selectionIndex + ". ", semanticModelMatch, notationModelMatch); modelEntries.add(modelEntry); // TODO add other (referencing, context, etc...) notation // models selectionIndex++; } } } return modelEntries; } /** * returns the comparison associated with the given selection. * * @param selection * the selection to get the comparison for. * @return the comparison. */ private Comparison getComparison(IStructuredSelection selection) { ModelReview currentModelReview = getCurrentModelReview(); if (currentModelReview != null) { return currentModelReview.getSelectedDiagramComparison(); } return null; } @Override protected void updateValues() { if (viewInitialized) { ModelReview modelReview = getCurrentModelReview(); if (modelReview == null) { /* no active model review -> clear diff viewer if necessary */ if (diffViewer != null && diffViewer.getInput() != null) { diffViewer.setInput(null); diffViewer.refresh(); } } } } }
fixes incorrect comparison in property diff causing missing entries
plugins/at.bitandart.zoubek.mervin/src/at/bitandart/zoubek/mervin/property/diff/PropertyDiffView.java
fixes incorrect comparison in property diff causing missing entries
<ide><path>lugins/at.bitandart.zoubek.mervin/src/at/bitandart/zoubek/mervin/property/diff/PropertyDiffView.java <ide> */ <ide> private Object createInputFromSelection(IStructuredSelection selection) { <ide> <del> Comparison comparison = getComparison(selection); <add> ModelReview currentModelReview = getCurrentModelReview(); <add> Comparison modelComparison = getModelComparison(); <add> Comparison diagramComparison = getDiagramComparison(); <ide> <ide> List<SelectionEntry> modelEntries = new ArrayList<>(selection.size()); <ide> <del> if (comparison != null) { <add> if (modelComparison != null || diagramComparison != null) { <ide> Iterator<?> selectionIterator = selection.iterator(); <ide> int selectionIndex = 1; <ide> while (selectionIterator.hasNext()) { <ide> EObject selectedSemanticModelElement = diagramModelHelper.getSemanticModel(object); <ide> View selectedNotationModelElement = diagramModelHelper.getNotationModel(object); <ide> <del> ModelReview currentModelReview = getCurrentModelReview(); <ide> if (currentModelReview != null) { <ide> <ide> View originalNotationModelElement = (View) currentModelReview.getUnifiedModelMap() <ide> } <ide> } <ide> <del> Match semanticModelMatch = comparison.getMatch(selectedSemanticModelElement); <del> Match notationModelMatch = comparison.getMatch(selectedNotationModelElement); <add> Match semanticModelMatch = null; <add> if (modelComparison != null) { <add> semanticModelMatch = modelComparison.getMatch(selectedSemanticModelElement); <add> } <add> <add> Match notationModelMatch = null; <add> if (diagramComparison != null) { <add> notationModelMatch = diagramComparison.getMatch(selectedNotationModelElement); <add> } <ide> <ide> /* <ide> * create an entry only if the selection contains a model <ide> } <ide> <ide> /** <del> * returns the comparison associated with the given selection. <del> * <del> * @param selection <del> * the selection to get the comparison for. <del> * @return the comparison. <del> */ <del> private Comparison getComparison(IStructuredSelection selection) { <add> * @return the diagram comparison to use for this view. <add> */ <add> private Comparison getDiagramComparison() { <ide> <ide> ModelReview currentModelReview = getCurrentModelReview(); <ide> if (currentModelReview != null) { <ide> return null; <ide> } <ide> <add> /** <add> * @return the model comparison to use for this view. <add> */ <add> private Comparison getModelComparison() { <add> <add> ModelReview currentModelReview = getCurrentModelReview(); <add> if (currentModelReview != null) { <add> return currentModelReview.getSelectedModelComparison(); <add> } <add> <add> return null; <add> } <add> <ide> @Override <ide> protected void updateValues() { <ide>
Java
apache-2.0
error: pathspec 'chapter_004/src/main/java/Iterator/IteratorArrayNumbers.java' did not match any file(s) known to git
8e95235c9fb395e71333faff7beaa3317ce58bc3
1
SergeyI88/InduikovS
package Iterator; import java.util.Iterator; /** * Created by admin on 26.05.2017. */ public class IteratorArrayNumbers implements Iterator<Integer> { public static void main(String[] args) { int[] a = {54, 434, 32, 5, 11, 13, 17, 19, 192, 7, 74, 28, 9, 13}; IteratorArrayNumbers iteratorArrayNumbers = new IteratorArrayNumbers(a); while (iteratorArrayNumbers.hasNext()) { iteratorArrayNumbers.next(); } } private int index = 0; private int[] a; public IteratorArrayNumbers(int[] a) { this.a = a; } @Override public boolean hasNext() { int j = index; for (; j < a.length; j++) { int temp = 2; int i = a[j]; if (i == 3 || i == 5 || i == 7) { return true; } int k = 1; while (temp != 10) { if (i % temp++ == 0) { k = 0; } } if (k == 1) { return true; } } return false; } @Override public Integer next() { for(; index < a.length;) { if (a[index] == 3 || a[index] == 5 || a[index] == 7) { return a[index++]; } int temp = 2; int k = 0; while (temp != 10) { if (a[index] % temp++ == 0) { index++; k = 1; break; } } if (k != 1){ System.out.println(a[index]); return a[index++]; } } return null; } @Override public void remove() { } }
chapter_004/src/main/java/Iterator/IteratorArrayNumbers.java
task 150
chapter_004/src/main/java/Iterator/IteratorArrayNumbers.java
task 150
<ide><path>hapter_004/src/main/java/Iterator/IteratorArrayNumbers.java <add>package Iterator; <add> <add>import java.util.Iterator; <add> <add>/** <add> * Created by admin on 26.05.2017. <add> */ <add>public class IteratorArrayNumbers implements Iterator<Integer> { <add> public static void main(String[] args) { <add> int[] a = {54, 434, 32, 5, 11, 13, 17, 19, 192, 7, 74, 28, 9, 13}; <add> IteratorArrayNumbers iteratorArrayNumbers = new IteratorArrayNumbers(a); <add> while (iteratorArrayNumbers.hasNext()) { <add> iteratorArrayNumbers.next(); <add> } <add> } <add> <add> private int index = 0; <add> private int[] a; <add> <add> public IteratorArrayNumbers(int[] a) { <add> this.a = a; <add> } <add> <add> @Override <add> public boolean hasNext() { <add> int j = index; <add> for (; j < a.length; j++) { <add> int temp = 2; <add> int i = a[j]; <add> if (i == 3 || i == 5 || i == 7) { <add> return true; <add> } <add> int k = 1; <add> while (temp != 10) { <add> if (i % temp++ == 0) { <add> k = 0; <add> } <add> } <add> if (k == 1) { <add> return true; <add> } <add> } <add> return false; <add> } <add> <add> <add> @Override <add> public Integer next() { <add> for(; index < a.length;) { <add> if (a[index] == 3 || a[index] == 5 || a[index] == 7) { <add> return a[index++]; <add> } <add> int temp = 2; <add> int k = 0; <add> while (temp != 10) { <add> if (a[index] % temp++ == 0) { <add> index++; <add> k = 1; <add> break; <add> } <add> } <add> if (k != 1){ <add> System.out.println(a[index]); <add> return a[index++]; <add> } <add> } <add> return null; <add> } <add> <add> @Override <add> public void remove() { <add> <add> } <add>}
JavaScript
mit
1cfcd3376db06134f911dd2262f305e517623d7b
0
wearepush/redux-starter
import React, { StrictMode } from 'react'; import { renderToNodeStream } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom/server'; import { matchRoutes } from 'react-router-dom'; import { Provider } from 'react-redux'; import { createMemoryHistory } from 'history'; import { HelmetProvider } from 'react-helmet-async'; import getRoutes from '../../routes/routes'; import Html from './html'; import ApiClient from '../../helpers/ApiClient'; import configureStore from '../../redux/store'; import { isSSR, host, port, ssl } from '../../../config/consts'; import { initialState as usersInitialState } from '../../redux/reducers/users/users'; import RootRoutes from '../../components/Root/RootRoutes'; export const helmetContext = {}; export default function createSSR(assets) { return (req, res) => { const context = {}; const history = createMemoryHistory({ initialEntries: [req.url], }); const client = new ApiClient({ port, host, ssl, }); const { cookies = {} } = req; const { testData } = cookies; const initialState = { users: { ...usersInitialState, ...(testData && { testData: JSON.parse(testData) }), }, }; const store = configureStore(history, client, initialState); if (!isSSR) { const content = ( <StrictMode> <Html assets={assets} store={store} /> </StrictMode> ); res.write('<!doctype html>'); const stream = renderToNodeStream(content); stream.pipe(res); return; } if (context.status === 302) { res.redirect(302, context.url); return; } const routes = getRoutes(store); const branch = matchRoutes(routes, req.url); const promises = branch.map((data) => { const fetchData = data.route?.element?.type?.fetchData; if (fetchData instanceof Function) { return fetchData(store) .then((response) => Promise.resolve(response)) .catch((error) => Promise.reject(error)); } return Promise.resolve(); }); const onEnd = (_res) => { const component = ( <HelmetProvider context={helmetContext}> <Provider store={store}> <StaticRouter location={req.url} context={context}> <RootRoutes routes={routes} /> </StaticRouter> </Provider> </HelmetProvider> ); const content = ( <StrictMode> <Html assets={assets} component={component} store={store} /> </StrictMode> ); if (_res && _res.response && _res.response.status) { res.status(_res.response.status); } else { res.status(200); } res.write('<!doctype html>'); const stream = renderToNodeStream(content); stream.pipe(res); }; Promise.all(promises).then(onEnd).catch(onEnd); }; }
src/server/SSR/createSSR.js
import React, { StrictMode } from 'react'; import { renderToNodeStream } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom/server'; import { matchRoutes } from 'react-router-dom'; import { Provider } from 'react-redux'; import { createMemoryHistory } from 'history'; import { HelmetProvider } from 'react-helmet-async'; import getRoutes from '../../routes/routes'; import Html from './html'; import ApiClient from '../../helpers/ApiClient'; import configureStore from '../../redux/store'; import { isSSR, host, port, ssl } from '../../../config/consts'; import { initialState as usersInitialState } from '../../redux/reducers/users/users'; import RootRoutes from '../../components/Root/RootRoutes'; export const helmetContext = {}; export default function createSSR(assets) { return (req, res) => { const context = {}; const history = createMemoryHistory({ initialEntries: [req.url], }); const client = new ApiClient({ port, host, ssl, }); const { cookies = {} } = req; const { testData } = cookies; const initialState = { users: { ...usersInitialState, ...(testData && { testData: JSON.parse(testData) }), }, }; const store = configureStore(history, client, initialState); if (!isSSR) { const content = ( <StrictMode> <Html assets={assets} store={store} /> </StrictMode> ); res.write('<!doctype html>'); const stream = renderToNodeStream(content); stream.pipe(res, { end: false }); stream.on('end', () => { res.end(); }); return; } if (context.status === 302) { res.redirect(302, context.url); return; } const routes = getRoutes(store); const branch = matchRoutes(routes, req.url); const promises = branch.map((data) => { const fetchData = data.route?.element?.type?.fetchData; if (fetchData instanceof Function) { return fetchData(store) .then((response) => Promise.resolve(response)) .catch((error) => Promise.reject(error)); } return Promise.resolve(); }); const onEnd = (_res) => { const component = ( <HelmetProvider context={helmetContext}> <Provider store={store}> <StaticRouter location={req.url} context={context}> <RootRoutes routes={routes} /> </StaticRouter> </Provider> </HelmetProvider> ); const content = ( <StrictMode> <Html assets={assets} component={component} store={store} /> </StrictMode> ); if (_res && _res.response && _res.response.status) { res.status(_res.response.status); } else { res.status(200); } res.write('<!doctype html>'); const stream = renderToNodeStream(content); stream.pipe(res, { end: false }); stream.on('end', () => { res.end(); }); }; Promise.all(promises).then(onEnd).catch(onEnd); }; }
feat: update react stream
src/server/SSR/createSSR.js
feat: update react stream
<ide><path>rc/server/SSR/createSSR.js <ide> ); <ide> res.write('<!doctype html>'); <ide> const stream = renderToNodeStream(content); <del> stream.pipe(res, { end: false }); <del> stream.on('end', () => { <del> res.end(); <del> }); <add> stream.pipe(res); <ide> return; <ide> } <ide> <ide> <ide> res.write('<!doctype html>'); <ide> const stream = renderToNodeStream(content); <del> stream.pipe(res, { end: false }); <del> stream.on('end', () => { <del> res.end(); <del> }); <add> stream.pipe(res); <ide> }; <ide> <ide> Promise.all(promises).then(onEnd).catch(onEnd);
Java
agpl-3.0
4f7ac923be37bbf3a9b7cd2e098c10947af31c8a
0
KinshipSoftware/KinOathKinshipArchiver,KinshipSoftware/KinOathKinshipArchiver,PeterWithers/temp-to-delete1,PeterWithers/temp-to-delete1
package nl.mpi.kinnate.gedcomimport; import java.util.ArrayList; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.DataTypes.RelationType; /** * Document : ImportLineStructure Created on : Jul 30, 2012, 9:23:36 AM * * @author Peter Withers */ public abstract class ImportLineStructure { int gedcomLevel = 0; String currentID = null; String entityType = null; boolean isFileHeader = false; boolean incompleteLine = false; private int currentFieldIndex = 0; protected class RelationEntry { protected String egoIdString; protected String alterIdString; protected DataTypes.RelationType relationType; protected String customType; public RelationEntry(String egoIdString, String alterIdString, RelationType relationType, String customType) { this.egoIdString = egoIdString; this.alterIdString = alterIdString; this.relationType = relationType; this.customType = customType; } } protected class FieldEntry { protected String lineContents = null; protected String currentName = null; protected FieldEntry(String currentName, String lineContents) throws ImportException { if (currentName == null) { throw new ImportException("Cannot have null names to a field."); } this.currentName = currentName.trim(); if (lineContents != null) { this.lineContents = lineContents; //.trim(); } } } ArrayList<FieldEntry> fieldEntryList = new ArrayList<FieldEntry>(); ArrayList<RelationEntry> relationEntryList = new ArrayList<RelationEntry>(); public ImportLineStructure(String lineString, ArrayList<String> gedcomLevelStrings) { } protected void addFieldEntry(String currentName, String lineContents) throws ImportException { fieldEntryList.add(new FieldEntry(currentName, lineContents)); } protected void addRelationEntry(String egoIdString, String alterIdString, RelationType relationType, String customType) throws ImportException { relationEntryList.add(new RelationEntry(egoIdString, alterIdString, relationType, customType)); } protected FieldEntry getCurrentField() { return fieldEntryList.get(currentFieldIndex); } protected void moveToNextField() { currentFieldIndex++; } protected boolean hasCurrentField() { return currentFieldIndex < fieldEntryList.size(); } public RelationEntry[] getRelationList() { return relationEntryList.toArray(new RelationEntry[0]); } public String getCurrentID() throws ImportException { if (currentID == null) { // new Exception().printStackTrace(); throw new ImportException("CurrentID has not been set"); } return currentID; } public String getCurrentName() throws ImportException { if (getCurrentField().currentName == null) { // new Exception().printStackTrace(); throw new ImportException("CurrentName has not been set"); } return getCurrentField().currentName; } public int getGedcomLevel() { return gedcomLevel; } public boolean hasLineContents() { return hasCurrentField() && getCurrentField().lineContents != null; } public String getLineContents() throws ImportException { if (!hasCurrentField() || getCurrentField().lineContents == null) { // new Exception().printStackTrace(); throw new ImportException("LineContents has not been set"); } return getCurrentField().lineContents; } public String getEntityType() { return entityType; } public boolean isFileHeader() { return isFileHeader; } public boolean isContinueLine() { return false; } public boolean isContinueLineBreak() { return false; } public boolean isEndOfFileMarker() { return false; } public boolean isIncompleteLine() { return incompleteLine; } abstract boolean isRelation(); }
desktop/src/main/java/nl/mpi/kinnate/gedcomimport/ImportLineStructure.java
package nl.mpi.kinnate.gedcomimport; import java.util.ArrayList; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.DataTypes.RelationType; /** * Document : ImportLineStructure * Created on : Jul 30, 2012, 9:23:36 AM * Author : Peter Withers */ public abstract class ImportLineStructure { int gedcomLevel = 0; String currentID = null; String entityType = null; boolean isFileHeader = false; boolean incompleteLine = false; private int currentFieldIndex = 0; protected class RelationEntry { protected String egoIdString; protected String alterIdString; protected DataTypes.RelationType relationType; protected String customType; public RelationEntry(String egoIdString, String alterIdString, RelationType relationType, String customType) { this.egoIdString = egoIdString; this.alterIdString = alterIdString; this.relationType = relationType; this.customType = customType; } } protected class FieldEntry { protected String lineContents = null; protected String currentName = null; protected FieldEntry(String currentName, String lineContents) throws ImportException { if (currentName == null) { throw new ImportException("Cannot have null names to a field."); } this.currentName = currentName.trim(); if (lineContents != null) { this.lineContents = lineContents.trim(); } } } ArrayList<FieldEntry> fieldEntryList = new ArrayList<FieldEntry>(); ArrayList<RelationEntry> relationEntryList = new ArrayList<RelationEntry>(); public ImportLineStructure(String lineString, ArrayList<String> gedcomLevelStrings) { } protected void addFieldEntry(String currentName, String lineContents) throws ImportException { fieldEntryList.add(new FieldEntry(currentName, lineContents)); } protected void addRelationEntry(String egoIdString, String alterIdString, RelationType relationType, String customType) throws ImportException { relationEntryList.add(new RelationEntry(egoIdString, alterIdString, relationType, customType)); } protected FieldEntry getCurrentField() { return fieldEntryList.get(currentFieldIndex); } protected void moveToNextField() { currentFieldIndex++; } protected boolean hasCurrentField() { return currentFieldIndex < fieldEntryList.size(); } public RelationEntry[] getRelationList() { return relationEntryList.toArray(new RelationEntry[0]); } public String getCurrentID() throws ImportException { if (currentID == null) { // new Exception().printStackTrace(); throw new ImportException("CurrentID has not been set"); } return currentID; } public String getCurrentName() throws ImportException { if (getCurrentField().currentName == null) { // new Exception().printStackTrace(); throw new ImportException("CurrentName has not been set"); } return getCurrentField().currentName; } public int getGedcomLevel() { return gedcomLevel; } public boolean hasLineContents() { return hasCurrentField() && getCurrentField().lineContents != null; } public String getLineContents() throws ImportException { if (!hasCurrentField() || getCurrentField().lineContents == null) { // new Exception().printStackTrace(); throw new ImportException("LineContents has not been set"); } return getCurrentField().lineContents; } public String getEntityType() { return entityType; } public boolean isFileHeader() { return isFileHeader; } public boolean isContinueLine() { return false; } public boolean isContinueLineBreak() { return false; } public boolean isEndOfFileMarker() { return false; } public boolean isIncompleteLine() { return incompleteLine; } abstract boolean isRelation(); }
Corrected some of the import code for the single file export format. Made the identifier creation code on import to be more consistent in its behaviour on re-import. refs #2248 #2097
desktop/src/main/java/nl/mpi/kinnate/gedcomimport/ImportLineStructure.java
Corrected some of the import code for the single file export format. Made the identifier creation code on import to be more consistent in its behaviour on re-import. refs #2248 #2097
<ide><path>esktop/src/main/java/nl/mpi/kinnate/gedcomimport/ImportLineStructure.java <ide> import nl.mpi.kinnate.kindata.DataTypes.RelationType; <ide> <ide> /** <del> * Document : ImportLineStructure <del> * Created on : Jul 30, 2012, 9:23:36 AM <del> * Author : Peter Withers <add> * Document : ImportLineStructure Created on : Jul 30, 2012, 9:23:36 AM <add> * <add> * @author Peter Withers <ide> */ <ide> public abstract class ImportLineStructure { <ide> <ide> } <ide> this.currentName = currentName.trim(); <ide> if (lineContents != null) { <del> this.lineContents = lineContents.trim(); <add> this.lineContents = lineContents; //.trim(); <ide> } <ide> } <ide> }
Java
apache-2.0
2ded583379db4932d3b634b7c4c0801a2628467f
0
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
/* * FieldViewer.java * * Created on 1. Mai 2008, 00:02 */ package de.naoth.rc.dialogs; import com.google.protobuf.InvalidProtocolBufferException; import de.naoth.rc.core.dialog.AbstractDialog; import de.naoth.rc.core.dialog.DialogPlugin; import de.naoth.rc.RobotControl; import de.naoth.rc.components.PNGExportFileType; import de.naoth.rc.components.PlainPDFExportFileType; import de.naoth.rc.core.dialog.RCDialog; import de.naoth.rc.drawings.Drawable; import de.naoth.rc.drawings.DrawingCollection; import de.naoth.rc.drawings.DrawingOnField; import de.naoth.rc.drawings.DrawingsContainer; import de.naoth.rc.drawings.FieldDrawingS3D2011; import de.naoth.rc.drawings.FieldDrawingSPL2012; import de.naoth.rc.drawings.FieldDrawingSPL2013; import de.naoth.rc.drawings.FieldDrawingSPL2013BlackWhite; import de.naoth.rc.drawings.LocalFieldDrawing; import de.naoth.rc.drawings.RadarDrawing; import de.naoth.rc.drawings.StrokePlot; import de.naoth.rc.drawingmanager.DrawingEventManager; import de.naoth.rc.manager.DebugDrawingManager; import de.naoth.rc.manager.ImageManagerBottom; import de.naoth.rc.core.manager.ObjectListener; import de.naoth.rc.dataformats.SPLMessage; import de.naoth.rc.drawings.Circle; import de.naoth.rc.drawings.FieldDrawingSPL3x4; import de.naoth.rc.drawings.Robot; import de.naoth.rc.drawings.Text; import de.naoth.rc.logmanager.BlackBoard; import de.naoth.rc.logmanager.LogDataFrame; import de.naoth.rc.logmanager.LogFileEventManager; import de.naoth.rc.logmanager.LogFrameListener; import de.naoth.rc.manager.DebugDrawingManagerMotion; import de.naoth.rc.manager.PlotDataManager; import de.naoth.rc.math.Vector2D; import de.naoth.rc.messages.FrameworkRepresentations; import de.naoth.rc.messages.FrameworkRepresentations.RobotInfo; import de.naoth.rc.messages.Messages.PlotItem; import de.naoth.rc.messages.Messages.Plots; import de.naoth.rc.messages.TeamMessageOuterClass; import de.naoth.rc.messages.TeamMessageOuterClass.TeamMessage; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.Timer; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import org.freehep.graphicsio.emf.EMFExportFileType; import org.freehep.graphicsio.java.JAVAExportFileType; import org.freehep.graphicsio.ps.EPSExportFileType; import org.freehep.graphicsio.svg.SVGExportFileType; import org.freehep.util.export.ExportDialog; /** * * @author Heinrich Mellmann */ public class FieldViewer extends AbstractDialog implements ActionListener { @RCDialog(category = RCDialog.Category.View, name = "Field") @PluginImplementation public static class Plugin extends DialogPlugin<FieldViewer> { @InjectPlugin public static RobotControl parent; @InjectPlugin public static DebugDrawingManager debugDrawingManager; @InjectPlugin public static DebugDrawingManagerMotion debugDrawingManagerMotion; @InjectPlugin public static PlotDataManager plotDataManager; @InjectPlugin public static ImageManagerBottom imageManager; @InjectPlugin public static DrawingEventManager drawingEventManager; @InjectPlugin public static LogFileEventManager logFileEventManager; }//end Plugin private final Timer drawingTimer; // drawing buffer for concurrent access; every "source" gets its own "buffer" private ConcurrentHashMap<Class<?>, Drawable> drawingBuffers = new ConcurrentHashMap<>(); private final PlotDataListener plotDataListener; private final StrokePlot strokePlot; private final LogFrameListener logFrameListener; // create new classes, so the received drawings are stored into different buffers private class DrawingsListenerMotion extends DrawingsListener{} private class DrawingsListenerCognition extends DrawingsListener{} private final DrawingsListenerMotion drawingsListenerMotion = new DrawingsListenerMotion(); private final DrawingsListenerCognition drawingsListenerCognition = new DrawingsListenerCognition(); // this is ued as an exportbuffer when the field issaved as image private BufferedImage exportBuffer = null; // TODO: this is a hack private static de.naoth.rc.components.DynamicCanvasPanel canvasExport = null; public static de.naoth.rc.components.DynamicCanvasPanel getCanvas() { return canvasExport; } public FieldViewer() { initComponents(); this.cbBackground.setModel( new javax.swing.DefaultComboBoxModel( new Drawable[] { new FieldDrawingSPL2013(), new FieldDrawingSPL2012(), new FieldDrawingS3D2011(), new FieldDrawingSPL3x4(), new LocalFieldDrawing(), new RadarDrawing(), new FieldDrawingSPL2013BlackWhite() } )); this.plotDataListener = new PlotDataListener(); this.logFrameListener = new LogFrameDrawer(); this.fieldCanvas.setBackgroundDrawing((Drawable)this.cbBackground.getSelectedItem()); this.fieldCanvas.setToolTipText(""); this.fieldCanvas.setFitToViewport(this.btFitToView.isSelected()); canvasExport = this.fieldCanvas; Plugin.drawingEventManager.addListener((Drawable drawing, Object src) -> { // add drawing of the source to the drawing buffer drawingBuffers.put(src.getClass(), drawing); }); // intialize the field resetView(); this.fieldCanvas.setAntializing(btAntializing.isSelected()); this.fieldCanvas.repaint(); this.fieldCanvas.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && !e.isConsumed()) { e.consume(); fieldCanvas.fitToViewport(); } } }); this.strokePlot = new StrokePlot(300); // schedules canvas drawing at a fixed rate, should prevent "flickering" this.drawingTimer = new Timer(300, this); this.drawingTimer.start(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPopupMenu = new javax.swing.JPopupMenu(); jMenuItemExport = new javax.swing.JMenuItem(); coordsPopup = new javax.swing.JDialog(); jToolBar1 = new javax.swing.JToolBar(); btReceiveDrawings = new javax.swing.JToggleButton(); btLog = new javax.swing.JToggleButton(); btClean = new javax.swing.JButton(); cbBackground = new javax.swing.JComboBox(); btRotate = new javax.swing.JButton(); btFitToView = new javax.swing.JToggleButton(); btAntializing = new javax.swing.JCheckBox(); btCollectDrawings = new javax.swing.JCheckBox(); cbExportOnDrawing = new javax.swing.JCheckBox(); btTrace = new javax.swing.JCheckBox(); jSlider1 = new javax.swing.JSlider(); drawingPanel = new javax.swing.JPanel(); fieldCanvas = new de.naoth.rc.components.DynamicCanvasPanel(); jMenuItemExport.setText("Export"); jMenuItemExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemExportActionPerformed(evt); } }); jPopupMenu.add(jMenuItemExport); javax.swing.GroupLayout coordsPopupLayout = new javax.swing.GroupLayout(coordsPopup.getContentPane()); coordsPopup.getContentPane().setLayout(coordsPopupLayout); coordsPopupLayout.setHorizontalGroup( coordsPopupLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 114, Short.MAX_VALUE) ); coordsPopupLayout.setVerticalGroup( coordsPopupLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 38, Short.MAX_VALUE) ); jToolBar1.setFloatable(false); jToolBar1.setRollover(true); btReceiveDrawings.setText("Receive"); btReceiveDrawings.setFocusable(false); btReceiveDrawings.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btReceiveDrawings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btReceiveDrawings.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btReceiveDrawingsActionPerformed(evt); } }); jToolBar1.add(btReceiveDrawings); btLog.setText("Log"); btLog.setFocusable(false); btLog.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btLog.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btLogActionPerformed(evt); } }); jToolBar1.add(btLog); btClean.setText("Clean"); btClean.setFocusable(false); btClean.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btClean.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btClean.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCleanActionPerformed(evt); } }); jToolBar1.add(btClean); cbBackground.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SPL2013", "SPL2012", "S3D2011", "RADAR", "LOCAL" })); cbBackground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbBackgroundActionPerformed(evt); } }); jToolBar1.add(cbBackground); btRotate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/naoth/rc/res/rotate_ccw.png"))); // NOI18N btRotate.setToolTipText("Rotate the coordinates by 90°"); btRotate.setFocusable(false); btRotate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btRotate.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btRotate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btRotateActionPerformed(evt); } }); jToolBar1.add(btRotate); btFitToView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/freehep/swing/images/0_MoveCursor.gif"))); // NOI18N btFitToView.setSelected(true); btFitToView.setToolTipText("auto-zoom canvas on resizing and rotation"); btFitToView.setFocusable(false); btFitToView.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btFitToView.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btFitToView.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btFitToViewActionPerformed(evt); } }); jToolBar1.add(btFitToView); btAntializing.setText("Antialiazing"); btAntializing.setFocusable(false); btAntializing.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btAntializing.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btAntializing.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btAntializingActionPerformed(evt); } }); jToolBar1.add(btAntializing); btCollectDrawings.setText("Collect"); btCollectDrawings.setFocusable(false); btCollectDrawings.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btCollectDrawings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btCollectDrawings.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCollectDrawingsActionPerformed(evt); } }); jToolBar1.add(btCollectDrawings); cbExportOnDrawing.setText("ExportOnDrawing"); cbExportOnDrawing.setFocusable(false); jToolBar1.add(cbExportOnDrawing); btTrace.setText("Trace"); btTrace.setFocusable(false); btTrace.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btTrace.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jToolBar1.add(btTrace); jSlider1.setMaximum(255); jSlider1.setValue(247); jSlider1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jSlider1StateChanged(evt); } }); jToolBar1.add(jSlider1); drawingPanel.setBackground(new java.awt.Color(247, 247, 247)); drawingPanel.setLayout(new java.awt.BorderLayout()); fieldCanvas.setBackground(new java.awt.Color(247, 247, 247)); fieldCanvas.setComponentPopupMenu(jPopupMenu); fieldCanvas.setOffsetX(350.0); fieldCanvas.setOffsetY(200.0); fieldCanvas.setScale(0.07); javax.swing.GroupLayout fieldCanvasLayout = new javax.swing.GroupLayout(fieldCanvas); fieldCanvas.setLayout(fieldCanvasLayout); fieldCanvasLayout.setHorizontalGroup( fieldCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 674, Short.MAX_VALUE) ); fieldCanvasLayout.setVerticalGroup( fieldCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 363, Short.MAX_VALUE) ); drawingPanel.add(fieldCanvas, java.awt.BorderLayout.CENTER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(drawingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(drawingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void btReceiveDrawingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReceiveDrawingsActionPerformed if(btReceiveDrawings.isSelected()) { if(Plugin.parent.checkConnected()) { Plugin.debugDrawingManager.addListener(drawingsListenerCognition); Plugin.debugDrawingManagerMotion.addListener(drawingsListenerMotion); Plugin.plotDataManager.addListener(plotDataListener); } else { btReceiveDrawings.setSelected(false); } } else { Plugin.debugDrawingManager.removeListener(drawingsListenerCognition); Plugin.debugDrawingManagerMotion.removeListener(drawingsListenerMotion); Plugin.plotDataManager.removeListener(plotDataListener); } }//GEN-LAST:event_btReceiveDrawingsActionPerformed private void jMenuItemExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExportActionPerformed ExportDialog export = new ExportDialog("FieldViewer", false); // add the image types for export export.addExportFileType(new SVGExportFileType()); export.addExportFileType(new PlainPDFExportFileType()); export.addExportFileType(new EPSExportFileType()); export.addExportFileType(new EMFExportFileType()); export.addExportFileType(new JAVAExportFileType()); export.addExportFileType(new PNGExportFileType()); export.showExportDialog(this, "Export view as ...", this.fieldCanvas, "export"); }//GEN-LAST:event_jMenuItemExportActionPerformed private void btAntializingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAntializingActionPerformed this.fieldCanvas.setAntializing(btAntializing.isSelected()); this.fieldCanvas.repaint(); }//GEN-LAST:event_btAntializingActionPerformed private void btCollectDrawingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCollectDrawingsActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btCollectDrawingsActionPerformed private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged int v = this.jSlider1.getValue(); this.fieldCanvas.setBackground(new Color(v,v,v)); this.drawingPanel.repaint(); }//GEN-LAST:event_jSlider1StateChanged private void btCleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCleanActionPerformed this.strokePlot.clear(); resetView(); this.fieldCanvas.repaint(); }//GEN-LAST:event_btCleanActionPerformed private void cbBackgroundActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbBackgroundActionPerformed {//GEN-HEADEREND:event_cbBackgroundActionPerformed this.fieldCanvas.setBackgroundDrawing((Drawable)this.cbBackground.getSelectedItem()); this.fieldCanvas.repaint(); // TODO: should this be inside the DynamicCanvasPanel? if(this.fieldCanvas.isFitToViewport()) { this.fieldCanvas.fitToViewport(); } }//GEN-LAST:event_cbBackgroundActionPerformed private void btRotateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRotateActionPerformed this.fieldCanvas.setRotation(this.fieldCanvas.getRotation() + Math.PI*0.5); // TODO: should this be inside the DynamicCanvasPanel? if(this.fieldCanvas.isFitToViewport()) { this.fieldCanvas.fitToViewport(); } this.fieldCanvas.repaint(); }//GEN-LAST:event_btRotateActionPerformed private void btFitToViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFitToViewActionPerformed fieldCanvas.setFitToViewport(this.btFitToView.isSelected()); }//GEN-LAST:event_btFitToViewActionPerformed private void btLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLogActionPerformed if(btLog.isSelected()) { Plugin.logFileEventManager.addListener(logFrameListener); } else { Plugin.logFileEventManager.removeListener(logFrameListener); } }//GEN-LAST:event_btLogActionPerformed final void resetView() { this.fieldCanvas.getDrawingList().clear(); if(btTrace.isSelected()) { this.fieldCanvas.getDrawingList().add(this.strokePlot); } drawingBuffers.clear(); }//end resetView private void exportCanvasToPNG() { long l = java.lang.System.currentTimeMillis(); File file = new File("./fieldViewerExport-"+l+".png"); if(exportBuffer == null || exportBuffer.getWidth() != this.fieldCanvas.getWidth() || exportBuffer.getHeight() != this.fieldCanvas.getHeight()) { exportBuffer = new BufferedImage(this.fieldCanvas.getWidth(), this.fieldCanvas.getHeight(), BufferedImage.TYPE_INT_ARGB); } Graphics2D g2d = exportBuffer.createGraphics(); this.fieldCanvas.paintAll(g2d); try { ImageIO.write(exportBuffer, "PNG", file); } catch(IOException ex) { ex.printStackTrace(System.err); } } private class DrawingsListener implements ObjectListener<DrawingsContainer> { @Override public void newObjectReceived(DrawingsContainer objectList) { if(objectList != null) { DrawingCollection drawingCollection = objectList.get(DrawingOnField.class); if(drawingCollection == null || drawingCollection.isEmpty()) { return; } // add received drawings to buffer drawingBuffers.put(this.getClass(), drawingCollection); if(cbExportOnDrawing.isSelected()) { SwingUtilities.invokeLater(new Runnable() { public void run() { exportCanvasToPNG(); } }); } } } @Override public void errorOccured(String cause) { btReceiveDrawings.setSelected(false); Plugin.debugDrawingManager.removeListener(this); Plugin.debugDrawingManagerMotion.removeListener(this); } } class LogFrameDrawer implements LogFrameListener { private void drawTeamMessages(BlackBoard b, DrawingCollection dc) { Optional<String> ownBodyID = getOwnBodyID(b); LogDataFrame teamMessageFrame = b.get("TeamMessage"); if(teamMessageFrame != null) { try { TeamMessage teamMessage = TeamMessage.parseFrom(teamMessageFrame.getData()); for(int i=0; i < teamMessage.getDataCount(); i++) { TeamMessage.Data robotMsg = teamMessage.getData(i); SPLMessage splMsg = SPLMessage.parseFrom(robotMsg); if(!splMsg.user.getIsPenalized()) { boolean isOwnMsg = false; if(ownBodyID.isPresent()) { isOwnMsg = ownBodyID.get().equals(splMsg.user.getBodyID()); } splMsg.draw(dc, isOwnMsg ? Color.red : Color.black, false); } } } catch (InvalidProtocolBufferException ex) { Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex); } } } private Optional<String> getOwnBodyID(BlackBoard b) { LogDataFrame robotInfoFrame = b.get("RobotInfo"); if(robotInfoFrame != null) { try { RobotInfo robotInfo = RobotInfo.parseFrom(robotInfoFrame.getData()); return Optional.of(robotInfo.getBodyID()); } catch (InvalidProtocolBufferException ex) { Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex); } } return Optional.empty(); } @Override public void newFrame(BlackBoard b) { DrawingCollection dc = new DrawingCollection(); drawTeamMessages(b, dc); drawingBuffers.put(this.getClass(), dc); } } class PlotDataListener implements ObjectListener<Plots> { @Override public void errorOccured(String cause) { btReceiveDrawings.setSelected(false); Plugin.plotDataManager.removeListener(this); } @Override public void newObjectReceived(Plots data) { if (data == null) return; for(PlotItem item : data.getPlotsList()) { if(item.getType() == PlotItem.PlotType.Plot2D && item.hasX() && item.hasY()) { strokePlot.addStroke(item.getName(), Color.blue); strokePlot.setEnabled(item.getName(), true); strokePlot.plot(item.getName(), new Vector2D(item.getX(), item.getY())); } else if(item.getType() == PlotItem.PlotType.Origin2D && item.hasX() && item.hasY() && item.hasRotation()) { strokePlot.setRotation(item.getRotation()); } } //end for }//end newObjectReceived }//end class PlotDataListener class DrawingBuffer extends DrawingCollection { private int maxNumberOfEnties; public DrawingBuffer(int maxNumberOfEnties) { this.maxNumberOfEnties = maxNumberOfEnties; } @Override public void add(Drawable d) { if(maxNumberOfEnties > 0 && this.drawables.size() >= maxNumberOfEnties) { this.drawables.remove(0); } super.add(d); } public void clear() { this.drawables.clear(); } } @Override public void dispose() { // remove all the registered listeners Plugin.debugDrawingManager.removeListener(drawingsListenerCognition); Plugin.debugDrawingManagerMotion.removeListener(drawingsListenerMotion); Plugin.plotDataManager.removeListener(plotDataListener); } @Override public void actionPerformed(ActionEvent e) { // clear old field drawings if(!btCollectDrawings.isSelected()) { fieldCanvas.getDrawingList().clear(); // removed it! in order to continue drawing strokes, we have to "re-add" it if(btTrace.isSelected()) { this.fieldCanvas.getDrawingList().add(this.strokePlot); } } // add buffered drawings to field drawing list drawingBuffers.forEach((s,b)->{fieldCanvas.getDrawingList().add(b);}); // re-draw field fieldCanvas.repaint(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox btAntializing; private javax.swing.JButton btClean; private javax.swing.JCheckBox btCollectDrawings; private javax.swing.JToggleButton btFitToView; private javax.swing.JToggleButton btLog; private javax.swing.JToggleButton btReceiveDrawings; private javax.swing.JButton btRotate; private javax.swing.JCheckBox btTrace; private javax.swing.JComboBox cbBackground; private javax.swing.JCheckBox cbExportOnDrawing; private javax.swing.JDialog coordsPopup; private javax.swing.JPanel drawingPanel; private de.naoth.rc.components.DynamicCanvasPanel fieldCanvas; private javax.swing.JMenuItem jMenuItemExport; private javax.swing.JPopupMenu jPopupMenu; private javax.swing.JSlider jSlider1; private javax.swing.JToolBar jToolBar1; // End of variables declaration//GEN-END:variables }
RobotControl/RobotControlGUI/src/de/naoth/rc/dialogs/FieldViewer.java
/* * FieldViewer.java * * Created on 1. Mai 2008, 00:02 */ package de.naoth.rc.dialogs; import com.google.protobuf.InvalidProtocolBufferException; import de.naoth.rc.core.dialog.AbstractDialog; import de.naoth.rc.core.dialog.DialogPlugin; import de.naoth.rc.RobotControl; import de.naoth.rc.components.PNGExportFileType; import de.naoth.rc.components.PlainPDFExportFileType; import de.naoth.rc.core.dialog.RCDialog; import de.naoth.rc.drawings.Drawable; import de.naoth.rc.drawings.DrawingCollection; import de.naoth.rc.drawings.DrawingOnField; import de.naoth.rc.drawings.DrawingsContainer; import de.naoth.rc.drawings.FieldDrawingS3D2011; import de.naoth.rc.drawings.FieldDrawingSPL2012; import de.naoth.rc.drawings.FieldDrawingSPL2013; import de.naoth.rc.drawings.FieldDrawingSPL2013BlackWhite; import de.naoth.rc.drawings.LocalFieldDrawing; import de.naoth.rc.drawings.RadarDrawing; import de.naoth.rc.drawings.StrokePlot; import de.naoth.rc.drawingmanager.DrawingEventManager; import de.naoth.rc.manager.DebugDrawingManager; import de.naoth.rc.manager.ImageManagerBottom; import de.naoth.rc.core.manager.ObjectListener; import de.naoth.rc.dataformats.SPLMessage; import de.naoth.rc.drawings.Circle; import de.naoth.rc.drawings.FieldDrawingSPL3x4; import de.naoth.rc.drawings.Robot; import de.naoth.rc.drawings.Text; import de.naoth.rc.logmanager.BlackBoard; import de.naoth.rc.logmanager.LogDataFrame; import de.naoth.rc.logmanager.LogFileEventManager; import de.naoth.rc.logmanager.LogFrameListener; import de.naoth.rc.manager.DebugDrawingManagerMotion; import de.naoth.rc.manager.PlotDataManager; import de.naoth.rc.math.Vector2D; import de.naoth.rc.messages.FrameworkRepresentations; import de.naoth.rc.messages.FrameworkRepresentations.RobotInfo; import de.naoth.rc.messages.Messages.PlotItem; import de.naoth.rc.messages.Messages.Plots; import de.naoth.rc.messages.TeamMessageOuterClass; import de.naoth.rc.messages.TeamMessageOuterClass.TeamMessage; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.Timer; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.injections.InjectPlugin; import org.freehep.graphicsio.emf.EMFExportFileType; import org.freehep.graphicsio.java.JAVAExportFileType; import org.freehep.graphicsio.ps.EPSExportFileType; import org.freehep.graphicsio.svg.SVGExportFileType; import org.freehep.util.export.ExportDialog; /** * * @author Heinrich Mellmann */ public class FieldViewer extends AbstractDialog implements ActionListener { @RCDialog(category = RCDialog.Category.View, name = "Field") @PluginImplementation public static class Plugin extends DialogPlugin<FieldViewer> { @InjectPlugin public static RobotControl parent; @InjectPlugin public static DebugDrawingManager debugDrawingManager; @InjectPlugin public static DebugDrawingManagerMotion debugDrawingManagerMotion; @InjectPlugin public static PlotDataManager plotDataManager; @InjectPlugin public static ImageManagerBottom imageManager; @InjectPlugin public static DrawingEventManager drawingEventManager; @InjectPlugin public static LogFileEventManager logFileEventManager; }//end Plugin private final Timer drawingTimer; // drawing buffer for concurrent access; every "source" gets its own "buffer" private ConcurrentHashMap<Class<?>, Drawable> drawingBuffers = new ConcurrentHashMap<>(); private final PlotDataListener plotDataListener; private final StrokePlot strokePlot; private final LogFrameListener logFrameListener; // create new classes, so the received drawings are stored into different buffers private class DrawingsListenerMotion extends DrawingsListener{} private class DrawingsListenerCognition extends DrawingsListener{} private final DrawingsListenerMotion drawingsListenerMotion = new DrawingsListenerMotion(); private final DrawingsListenerCognition drawingsListenerCognition = new DrawingsListenerCognition(); // this is ued as an exportbuffer when the field issaved as image private BufferedImage exportBuffer = null; // TODO: this is a hack private static de.naoth.rc.components.DynamicCanvasPanel canvasExport = null; public static de.naoth.rc.components.DynamicCanvasPanel getCanvas() { return canvasExport; } public FieldViewer() { initComponents(); this.cbBackground.setModel( new javax.swing.DefaultComboBoxModel( new Drawable[] { new FieldDrawingSPL2013(), new FieldDrawingSPL2012(), new FieldDrawingS3D2011(), new FieldDrawingSPL3x4(), new LocalFieldDrawing(), new RadarDrawing(), new FieldDrawingSPL2013BlackWhite() } )); this.plotDataListener = new PlotDataListener(); this.logFrameListener = new LogFrameDrawer(); this.fieldCanvas.setBackgroundDrawing((Drawable)this.cbBackground.getSelectedItem()); this.fieldCanvas.setToolTipText(""); this.fieldCanvas.setFitToViewport(this.btFitToView.isSelected()); canvasExport = this.fieldCanvas; Plugin.drawingEventManager.addListener((Drawable drawing, Object src) -> { // add drawing of the source to the drawing buffer drawingBuffers.put(src.getClass(), drawing); }); // intialize the field resetView(); this.fieldCanvas.setAntializing(btAntializing.isSelected()); this.fieldCanvas.repaint(); this.fieldCanvas.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && !e.isConsumed()) { e.consume(); fieldCanvas.fitToViewport(); } } }); this.strokePlot = new StrokePlot(300); // schedules canvas drawing at a fixed rate, should prevent "flickering" this.drawingTimer = new Timer(300, this); this.drawingTimer.start(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPopupMenu = new javax.swing.JPopupMenu(); jMenuItemExport = new javax.swing.JMenuItem(); coordsPopup = new javax.swing.JDialog(); jToolBar1 = new javax.swing.JToolBar(); btReceiveDrawings = new javax.swing.JToggleButton(); btLog = new javax.swing.JToggleButton(); btClean = new javax.swing.JButton(); cbBackground = new javax.swing.JComboBox(); btRotate = new javax.swing.JButton(); btFitToView = new javax.swing.JToggleButton(); btAntializing = new javax.swing.JCheckBox(); btCollectDrawings = new javax.swing.JCheckBox(); cbExportOnDrawing = new javax.swing.JCheckBox(); btTrace = new javax.swing.JCheckBox(); jSlider1 = new javax.swing.JSlider(); drawingPanel = new javax.swing.JPanel(); fieldCanvas = new de.naoth.rc.components.DynamicCanvasPanel(); jMenuItemExport.setText("Export"); jMenuItemExport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItemExportActionPerformed(evt); } }); jPopupMenu.add(jMenuItemExport); javax.swing.GroupLayout coordsPopupLayout = new javax.swing.GroupLayout(coordsPopup.getContentPane()); coordsPopup.getContentPane().setLayout(coordsPopupLayout); coordsPopupLayout.setHorizontalGroup( coordsPopupLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 114, Short.MAX_VALUE) ); coordsPopupLayout.setVerticalGroup( coordsPopupLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 38, Short.MAX_VALUE) ); jToolBar1.setFloatable(false); jToolBar1.setRollover(true); btReceiveDrawings.setText("Receive"); btReceiveDrawings.setFocusable(false); btReceiveDrawings.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btReceiveDrawings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btReceiveDrawings.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btReceiveDrawingsActionPerformed(evt); } }); jToolBar1.add(btReceiveDrawings); btLog.setText("Log"); btLog.setFocusable(false); btLog.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btLog.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btLog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btLogActionPerformed(evt); } }); jToolBar1.add(btLog); btClean.setText("Clean"); btClean.setFocusable(false); btClean.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btClean.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btClean.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCleanActionPerformed(evt); } }); jToolBar1.add(btClean); cbBackground.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SPL2013", "SPL2012", "S3D2011", "RADAR", "LOCAL" })); cbBackground.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbBackgroundActionPerformed(evt); } }); jToolBar1.add(cbBackground); btRotate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/naoth/rc/res/rotate_ccw.png"))); // NOI18N btRotate.setToolTipText("Rotate the coordinates by 90°"); btRotate.setFocusable(false); btRotate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btRotate.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btRotate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btRotateActionPerformed(evt); } }); jToolBar1.add(btRotate); btFitToView.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/freehep/swing/images/0_MoveCursor.gif"))); // NOI18N btFitToView.setSelected(true); btFitToView.setToolTipText("auto-zoom canvas on resizing and rotation"); btFitToView.setFocusable(false); btFitToView.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); btFitToView.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btFitToView.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btFitToViewActionPerformed(evt); } }); jToolBar1.add(btFitToView); btAntializing.setText("Antialiazing"); btAntializing.setFocusable(false); btAntializing.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btAntializing.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btAntializing.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btAntializingActionPerformed(evt); } }); jToolBar1.add(btAntializing); btCollectDrawings.setText("Collect"); btCollectDrawings.setFocusable(false); btCollectDrawings.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btCollectDrawings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); btCollectDrawings.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCollectDrawingsActionPerformed(evt); } }); jToolBar1.add(btCollectDrawings); cbExportOnDrawing.setText("ExportOnDrawing"); cbExportOnDrawing.setFocusable(false); jToolBar1.add(cbExportOnDrawing); btTrace.setText("Trace"); btTrace.setFocusable(false); btTrace.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); btTrace.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jToolBar1.add(btTrace); jSlider1.setMaximum(255); jSlider1.setValue(247); jSlider1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jSlider1StateChanged(evt); } }); jToolBar1.add(jSlider1); drawingPanel.setBackground(new java.awt.Color(247, 247, 247)); drawingPanel.setLayout(new java.awt.BorderLayout()); fieldCanvas.setBackground(new java.awt.Color(247, 247, 247)); fieldCanvas.setComponentPopupMenu(jPopupMenu); fieldCanvas.setOffsetX(350.0); fieldCanvas.setOffsetY(200.0); fieldCanvas.setScale(0.07); javax.swing.GroupLayout fieldCanvasLayout = new javax.swing.GroupLayout(fieldCanvas); fieldCanvas.setLayout(fieldCanvasLayout); fieldCanvasLayout.setHorizontalGroup( fieldCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 674, Short.MAX_VALUE) ); fieldCanvasLayout.setVerticalGroup( fieldCanvasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 363, Short.MAX_VALUE) ); drawingPanel.add(fieldCanvas, java.awt.BorderLayout.CENTER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(drawingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(drawingPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void btReceiveDrawingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReceiveDrawingsActionPerformed if(btReceiveDrawings.isSelected()) { if(Plugin.parent.checkConnected()) { Plugin.debugDrawingManager.addListener(drawingsListenerCognition); Plugin.debugDrawingManagerMotion.addListener(drawingsListenerMotion); Plugin.plotDataManager.addListener(plotDataListener); } else { btReceiveDrawings.setSelected(false); } } else { Plugin.debugDrawingManager.removeListener(drawingsListenerCognition); Plugin.debugDrawingManagerMotion.removeListener(drawingsListenerMotion); Plugin.plotDataManager.removeListener(plotDataListener); } }//GEN-LAST:event_btReceiveDrawingsActionPerformed private void jMenuItemExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExportActionPerformed ExportDialog export = new ExportDialog("FieldViewer", false); // add the image types for export export.addExportFileType(new SVGExportFileType()); export.addExportFileType(new PlainPDFExportFileType()); export.addExportFileType(new EPSExportFileType()); export.addExportFileType(new EMFExportFileType()); export.addExportFileType(new JAVAExportFileType()); export.addExportFileType(new PNGExportFileType()); export.showExportDialog(this, "Export view as ...", this.fieldCanvas, "export"); }//GEN-LAST:event_jMenuItemExportActionPerformed private void btAntializingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAntializingActionPerformed this.fieldCanvas.setAntializing(btAntializing.isSelected()); this.fieldCanvas.repaint(); }//GEN-LAST:event_btAntializingActionPerformed private void btCollectDrawingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCollectDrawingsActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btCollectDrawingsActionPerformed private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged int v = this.jSlider1.getValue(); this.fieldCanvas.setBackground(new Color(v,v,v)); this.drawingPanel.repaint(); }//GEN-LAST:event_jSlider1StateChanged private void btCleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCleanActionPerformed this.strokePlot.clear(); resetView(); this.fieldCanvas.repaint(); }//GEN-LAST:event_btCleanActionPerformed private void cbBackgroundActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_cbBackgroundActionPerformed {//GEN-HEADEREND:event_cbBackgroundActionPerformed this.fieldCanvas.setBackgroundDrawing((Drawable)this.cbBackground.getSelectedItem()); this.fieldCanvas.repaint(); // TODO: should this be inside the DynamicCanvasPanel? if(this.fieldCanvas.isFitToViewport()) { this.fieldCanvas.fitToViewport(); } }//GEN-LAST:event_cbBackgroundActionPerformed private void btRotateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btRotateActionPerformed this.fieldCanvas.setRotation(this.fieldCanvas.getRotation() + Math.PI*0.5); // TODO: should this be inside the DynamicCanvasPanel? if(this.fieldCanvas.isFitToViewport()) { this.fieldCanvas.fitToViewport(); } this.fieldCanvas.repaint(); }//GEN-LAST:event_btRotateActionPerformed private void btFitToViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFitToViewActionPerformed fieldCanvas.setFitToViewport(this.btFitToView.isSelected()); }//GEN-LAST:event_btFitToViewActionPerformed private void btLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLogActionPerformed if(btLog.isSelected()) { Plugin.logFileEventManager.addListener(logFrameListener); } else { Plugin.logFileEventManager.removeListener(logFrameListener); } }//GEN-LAST:event_btLogActionPerformed final void resetView() { this.fieldCanvas.getDrawingList().clear(); if(btTrace.isSelected()) { this.fieldCanvas.getDrawingList().add(this.strokePlot); } drawingBuffers.clear(); }//end resetView private void exportCanvasToPNG() { long l = java.lang.System.currentTimeMillis(); File file = new File("./fieldViewerExport-"+l+".png"); if(exportBuffer == null || exportBuffer.getWidth() != this.fieldCanvas.getWidth() || exportBuffer.getHeight() != this.fieldCanvas.getHeight()) { exportBuffer = new BufferedImage(this.fieldCanvas.getWidth(), this.fieldCanvas.getHeight(), BufferedImage.TYPE_INT_ARGB); } Graphics2D g2d = exportBuffer.createGraphics(); this.fieldCanvas.paintAll(g2d); try { ImageIO.write(exportBuffer, "PNG", file); } catch(IOException ex) { ex.printStackTrace(System.err); } } private class DrawingsListener implements ObjectListener<DrawingsContainer> { @Override public void newObjectReceived(DrawingsContainer objectList) { if(objectList != null) { DrawingCollection drawingCollection = objectList.get(DrawingOnField.class); if(drawingCollection == null || drawingCollection.isEmpty()) { return; } // add received drawings to buffer drawingBuffers.put(this.getClass(), drawingCollection); if(cbExportOnDrawing.isSelected()) { SwingUtilities.invokeLater(new Runnable() { public void run() { exportCanvasToPNG(); } }); } } } @Override public void errorOccured(String cause) { btReceiveDrawings.setSelected(false); Plugin.debugDrawingManager.removeListener(this); Plugin.debugDrawingManagerMotion.removeListener(this); } } class LogFrameDrawer implements LogFrameListener { private void drawTeamMessages(BlackBoard b, DrawingCollection dc) { Optional<String> ownBodyID = getOwnBodyID(b); LogDataFrame teamMessageFrame = b.get("TeamMessage"); if(teamMessageFrame != null) { try { TeamMessage teamMessage = TeamMessage.parseFrom(teamMessageFrame.getData()); for(int i=0; i < teamMessage.getDataCount(); i++) { TeamMessage.Data robotMsg = teamMessage.getData(i); SPLMessage splMsg = SPLMessage.parseFrom(robotMsg); boolean isOwnMsg = false; if(ownBodyID.isPresent()) { isOwnMsg = ownBodyID.get().equals(splMsg.user.getBodyID()); } splMsg.draw(dc, isOwnMsg ? Color.red : Color.black, false); } } catch (InvalidProtocolBufferException ex) { Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex); } } } private Optional<String> getOwnBodyID(BlackBoard b) { LogDataFrame robotInfoFrame = b.get("RobotInfo"); if(robotInfoFrame != null) { try { RobotInfo robotInfo = RobotInfo.parseFrom(robotInfoFrame.getData()); return Optional.of(robotInfo.getBodyID()); } catch (InvalidProtocolBufferException ex) { Logger.getLogger(FieldViewer.class.getName()).log(Level.SEVERE, null, ex); } } return Optional.empty(); } @Override public void newFrame(BlackBoard b) { DrawingCollection dc = new DrawingCollection(); drawTeamMessages(b, dc); drawingBuffers.put(this.getClass(), dc); } } class PlotDataListener implements ObjectListener<Plots> { @Override public void errorOccured(String cause) { btReceiveDrawings.setSelected(false); Plugin.plotDataManager.removeListener(this); } @Override public void newObjectReceived(Plots data) { if (data == null) return; for(PlotItem item : data.getPlotsList()) { if(item.getType() == PlotItem.PlotType.Plot2D && item.hasX() && item.hasY()) { strokePlot.addStroke(item.getName(), Color.blue); strokePlot.setEnabled(item.getName(), true); strokePlot.plot(item.getName(), new Vector2D(item.getX(), item.getY())); } else if(item.getType() == PlotItem.PlotType.Origin2D && item.hasX() && item.hasY() && item.hasRotation()) { strokePlot.setRotation(item.getRotation()); } } //end for }//end newObjectReceived }//end class PlotDataListener class DrawingBuffer extends DrawingCollection { private int maxNumberOfEnties; public DrawingBuffer(int maxNumberOfEnties) { this.maxNumberOfEnties = maxNumberOfEnties; } @Override public void add(Drawable d) { if(maxNumberOfEnties > 0 && this.drawables.size() >= maxNumberOfEnties) { this.drawables.remove(0); } super.add(d); } public void clear() { this.drawables.clear(); } } @Override public void dispose() { // remove all the registered listeners Plugin.debugDrawingManager.removeListener(drawingsListenerCognition); Plugin.debugDrawingManagerMotion.removeListener(drawingsListenerMotion); Plugin.plotDataManager.removeListener(plotDataListener); } @Override public void actionPerformed(ActionEvent e) { // clear old field drawings if(!btCollectDrawings.isSelected()) { fieldCanvas.getDrawingList().clear(); // removed it! in order to continue drawing strokes, we have to "re-add" it if(btTrace.isSelected()) { this.fieldCanvas.getDrawingList().add(this.strokePlot); } } // add buffered drawings to field drawing list drawingBuffers.forEach((s,b)->{fieldCanvas.getDrawingList().add(b);}); // re-draw field fieldCanvas.repaint(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox btAntializing; private javax.swing.JButton btClean; private javax.swing.JCheckBox btCollectDrawings; private javax.swing.JToggleButton btFitToView; private javax.swing.JToggleButton btLog; private javax.swing.JToggleButton btReceiveDrawings; private javax.swing.JButton btRotate; private javax.swing.JCheckBox btTrace; private javax.swing.JComboBox cbBackground; private javax.swing.JCheckBox cbExportOnDrawing; private javax.swing.JDialog coordsPopup; private javax.swing.JPanel drawingPanel; private de.naoth.rc.components.DynamicCanvasPanel fieldCanvas; private javax.swing.JMenuItem jMenuItemExport; private javax.swing.JPopupMenu jPopupMenu; private javax.swing.JSlider jSlider1; private javax.swing.JToolBar jToolBar1; // End of variables declaration//GEN-END:variables }
Don't show penalized players in field viewer for log files.
RobotControl/RobotControlGUI/src/de/naoth/rc/dialogs/FieldViewer.java
Don't show penalized players in field viewer for log files.
<ide><path>obotControl/RobotControlGUI/src/de/naoth/rc/dialogs/FieldViewer.java <ide> <ide> SPLMessage splMsg = SPLMessage.parseFrom(robotMsg); <ide> <del> boolean isOwnMsg = false; <del> if(ownBodyID.isPresent()) <del> { <del> isOwnMsg = ownBodyID.get().equals(splMsg.user.getBodyID()); <add> if(!splMsg.user.getIsPenalized()) { <add> boolean isOwnMsg = false; <add> if(ownBodyID.isPresent()) <add> { <add> isOwnMsg = ownBodyID.get().equals(splMsg.user.getBodyID()); <add> } <add> <add> splMsg.draw(dc, isOwnMsg ? Color.red : Color.black, false); <ide> } <del> <del> splMsg.draw(dc, isOwnMsg ? Color.red : Color.black, false); <ide> <ide> } <ide> } catch (InvalidProtocolBufferException ex) {
Java
apache-2.0
cec965bb6310ec15cd4928fc06e4651facd97b33
0
jjj117/airavata,gouravshenoy/airavata,anujbhan/airavata,jjj117/airavata,dogless/airavata,jjj117/airavata,anujbhan/airavata,apache/airavata,hasinitg/airavata,machristie/airavata,dogless/airavata,anujbhan/airavata,anujbhan/airavata,anujbhan/airavata,gouravshenoy/airavata,apache/airavata,gouravshenoy/airavata,apache/airavata,gouravshenoy/airavata,hasinitg/airavata,glahiru/airavata,dogless/airavata,apache/airavata,gouravshenoy/airavata,gouravshenoy/airavata,apache/airavata,machristie/airavata,apache/airavata,dogless/airavata,apache/airavata,jjj117/airavata,glahiru/airavata,hasinitg/airavata,hasinitg/airavata,glahiru/airavata,glahiru/airavata,hasinitg/airavata,machristie/airavata,apache/airavata,glahiru/airavata,anujbhan/airavata,dogless/airavata,machristie/airavata,jjj117/airavata,jjj117/airavata,gouravshenoy/airavata,machristie/airavata,machristie/airavata,machristie/airavata,dogless/airavata,anujbhan/airavata,hasinitg/airavata
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.gfac.handler; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.schmizz.sshj.connection.ConnectionException; import net.schmizz.sshj.transport.TransportException; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.gfac.GFacException; import org.apache.airavata.gfac.context.JobExecutionContext; import org.apache.airavata.gfac.context.security.GSISecurityContext; import org.apache.airavata.gfac.context.security.SSHSecurityContext; import org.apache.airavata.gfac.provider.GFacProviderException; import org.apache.airavata.gfac.utils.GFacUtils; import org.apache.airavata.gfac.utils.OutputUtils; import org.apache.airavata.gsi.ssh.api.Cluster; import org.apache.airavata.gsi.ssh.util.SSHUtils; import org.apache.airavata.model.workspace.experiment.*; import org.apache.airavata.persistance.registry.jpa.model.DataTransferDetail; import org.apache.airavata.registry.cpi.ChildDataType; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.URIParameterType; import org.apache.xmlbeans.XmlException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SCPOutputHandler extends AbstractHandler{ private static final Logger log = LoggerFactory.getLogger(SCPOutputHandler.class); public void invoke(JobExecutionContext jobExecutionContext) throws GFacHandlerException, GFacException { super.invoke(jobExecutionContext); DataTransferDetails detail = new DataTransferDetails(); TransferStatus status = new TransferStatus(); ApplicationDeploymentDescriptionType app = jobExecutionContext.getApplicationContext() .getApplicationDeploymentDescription().getType(); try { Cluster cluster = null; if (jobExecutionContext.getSecurityContext(GSISecurityContext.GSI_SECURITY_CONTEXT) != null) { cluster = ((GSISecurityContext) jobExecutionContext.getSecurityContext(GSISecurityContext.GSI_SECURITY_CONTEXT)).getPbsCluster(); } else { cluster = ((SSHSecurityContext) jobExecutionContext.getSecurityContext(SSHSecurityContext.SSH_SECURITY_CONTEXT)).getPbsCluster(); } if (cluster == null) { throw new GFacProviderException("Security context is not set properly"); } else { log.info("Successfully retrieved the Security Context"); } // Get the Stdouts and StdErrs String timeStampedServiceName = GFacUtils.createUniqueNameForService(jobExecutionContext.getServiceName()); TaskDetails taskData = jobExecutionContext.getTaskData(); String outputDataDir = null; File localStdOutFile; File localStdErrFile; if (taskData.getAdvancedOutputDataHandling() != null) { outputDataDir = taskData.getAdvancedOutputDataHandling().getOutputDataDir(); } if(outputDataDir == null) { outputDataDir = File.separator + "tmp"; } outputDataDir = outputDataDir + File.separator + jobExecutionContext.getExperimentID() + "-" +jobExecutionContext.getTaskData().getTaskID(); (new File(outputDataDir)).mkdirs(); app.setOutputDataDirectory(outputDataDir); // These will be useful if we are doing third party transfer localStdOutFile = new File(outputDataDir + File.separator + timeStampedServiceName + "stdout"); localStdErrFile = new File(outputDataDir + File.separator + timeStampedServiceName + "stderr"); // cluster.makeDirectory(outputDataDir); cluster.scpFrom(app.getStandardOutput(), localStdOutFile.getAbsolutePath()); cluster.scpFrom(app.getStandardError(), localStdErrFile.getAbsolutePath()); String stdOutStr = GFacUtils.readFileToString(localStdOutFile.getAbsolutePath()); String stdErrStr = GFacUtils.readFileToString(localStdErrFile.getAbsolutePath()); status.setTransferState(TransferState.COMPLETE); detail.setTransferStatus(status); detail.setTransferDescription("STDOUT:" + stdOutStr); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); status.setTransferState(TransferState.COMPLETE); detail.setTransferStatus(status); detail.setTransferDescription("STDERR:" + stdErrStr); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); Map<String, ActualParameter> stringMap = new HashMap<String, ActualParameter>(); Map<String, Object> output = jobExecutionContext.getOutMessageContext().getParameters(); Set<String> keys = output.keySet(); for (String paramName : keys) { ActualParameter actualParameter = (ActualParameter) output.get(paramName); if ("URI".equals(actualParameter.getType().getType().toString())) { List<String> outputList = cluster.listDirectory(app.getOutputDataDirectory()); if (outputList.size() == 0 || outputList.get(0).isEmpty()) { stringMap = OutputUtils.fillOutputFromStdout(output, stdOutStr, stdErrStr); } else { String valueList = outputList.get(0); cluster.scpFrom(valueList, outputDataDir); ((URIParameterType) actualParameter.getType()).setValue(valueList); stringMap = new HashMap<String, ActualParameter>(); stringMap.put(paramName, actualParameter); } }else{ stringMap = OutputUtils.fillOutputFromStdout(output, stdOutStr, stdErrStr); } } if (stringMap == null || stringMap.isEmpty()) { throw new GFacHandlerException( "Empty Output returned from the Application, Double check the application" + "and ApplicationDescriptor output Parameter Names"); } status.setTransferState(TransferState.DOWNLOAD); detail.setTransferStatus(status); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); app.setStandardError(localStdErrFile.getAbsolutePath()); app.setStandardOutput(localStdOutFile.getAbsolutePath()); if (outputDataDir != null) { app.setOutputDataDirectory(outputDataDir); } } catch (XmlException e) { throw new GFacHandlerException("Cannot read output:" + e.getMessage(), e); } catch (ConnectionException e) { throw new GFacHandlerException(e.getMessage(), e); } catch (TransportException e) { throw new GFacHandlerException(e.getMessage(), e); } catch (IOException e) { throw new GFacHandlerException(e.getMessage(), e); } catch (Exception e) { try { status.setTransferState(TransferState.FAILED); detail.setTransferStatus(status); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); GFacUtils.saveErrorDetails(e.getLocalizedMessage(), CorrectiveAction.CONTACT_SUPPORT, ErrorCategory.FILE_SYSTEM_FAILURE, jobExecutionContext.getTaskData().getTaskID()); } catch (Exception e1) { throw new GFacHandlerException("Error persisting status", e1, e1.getLocalizedMessage()); } throw new GFacHandlerException("Error in retrieving results", e); } } public void initProperties(Map<String, String> properties) throws GFacHandlerException, GFacException { } }
modules/gfac/gfac-core/src/main/java/org/apache/airavata/gfac/handler/SCPOutputHandler.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.gfac.handler; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import net.schmizz.sshj.connection.ConnectionException; import net.schmizz.sshj.transport.TransportException; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.gfac.GFacException; import org.apache.airavata.gfac.context.JobExecutionContext; import org.apache.airavata.gfac.context.security.GSISecurityContext; import org.apache.airavata.gfac.context.security.SSHSecurityContext; import org.apache.airavata.gfac.provider.GFacProviderException; import org.apache.airavata.gfac.utils.GFacUtils; import org.apache.airavata.gfac.utils.OutputUtils; import org.apache.airavata.gsi.ssh.api.Cluster; import org.apache.airavata.gsi.ssh.util.SSHUtils; import org.apache.airavata.model.workspace.experiment.*; import org.apache.airavata.persistance.registry.jpa.model.DataTransferDetail; import org.apache.airavata.registry.cpi.ChildDataType; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.URIParameterType; import org.apache.xmlbeans.XmlException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SCPOutputHandler extends AbstractHandler{ private static final Logger log = LoggerFactory.getLogger(SCPOutputHandler.class); public void invoke(JobExecutionContext jobExecutionContext) throws GFacHandlerException, GFacException { super.invoke(jobExecutionContext); DataTransferDetails detail = new DataTransferDetails(); TransferStatus status = new TransferStatus(); ApplicationDeploymentDescriptionType app = jobExecutionContext.getApplicationContext() .getApplicationDeploymentDescription().getType(); try { Cluster cluster = null; if (jobExecutionContext.getSecurityContext(GSISecurityContext.GSI_SECURITY_CONTEXT) != null) { cluster = ((GSISecurityContext) jobExecutionContext.getSecurityContext(GSISecurityContext.GSI_SECURITY_CONTEXT)).getPbsCluster(); } else { cluster = ((SSHSecurityContext) jobExecutionContext.getSecurityContext(SSHSecurityContext.SSH_SECURITY_CONTEXT)).getPbsCluster(); } if (cluster == null) { throw new GFacProviderException("Security context is not set properly"); } else { log.info("Successfully retrieved the Security Context"); } // Get the Stdouts and StdErrs String timeStampedServiceName = GFacUtils.createUniqueNameForService(jobExecutionContext.getServiceName()); TaskDetails taskData = jobExecutionContext.getTaskData(); String outputDataDir = null; File localStdOutFile; File localStdErrFile; if (taskData.getAdvancedOutputDataHandling() != null) { outputDataDir = taskData.getAdvancedOutputDataHandling().getOutputDataDir(); } if(outputDataDir == null) { outputDataDir = File.separator + "tmp"; } outputDataDir = outputDataDir + jobExecutionContext.getExperimentID() + "-" +jobExecutionContext.getTaskData().getTaskID(); (new File(outputDataDir)).mkdirs(); app.setOutputDataDirectory(outputDataDir); // These will be useful if we are doing third party transfer localStdOutFile = new File(outputDataDir + File.separator + timeStampedServiceName + "stdout"); localStdErrFile = new File(outputDataDir + File.separator + timeStampedServiceName + "stderr"); // cluster.makeDirectory(outputDataDir); cluster.scpFrom(app.getStandardOutput(), localStdOutFile.getAbsolutePath()); cluster.scpFrom(app.getStandardError(), localStdErrFile.getAbsolutePath()); String stdOutStr = GFacUtils.readFileToString(localStdOutFile.getAbsolutePath()); String stdErrStr = GFacUtils.readFileToString(localStdErrFile.getAbsolutePath()); status.setTransferState(TransferState.COMPLETE); detail.setTransferStatus(status); detail.setTransferDescription("STDOUT:" + stdOutStr); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); status.setTransferState(TransferState.COMPLETE); detail.setTransferStatus(status); detail.setTransferDescription("STDERR:" + stdErrStr); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); Map<String, ActualParameter> stringMap = new HashMap<String, ActualParameter>(); Map<String, Object> output = jobExecutionContext.getOutMessageContext().getParameters(); Set<String> keys = output.keySet(); for (String paramName : keys) { ActualParameter actualParameter = (ActualParameter) output.get(paramName); if ("URI".equals(actualParameter.getType().getType().toString())) { List<String> outputList = cluster.listDirectory(app.getOutputDataDirectory()); if (outputList.size() == 0 || outputList.get(0).isEmpty()) { stringMap = OutputUtils.fillOutputFromStdout(output, stdOutStr, stdErrStr); } else { String valueList = outputList.get(0); cluster.scpFrom(valueList, outputDataDir); ((URIParameterType) actualParameter.getType()).setValue(valueList); stringMap = new HashMap<String, ActualParameter>(); stringMap.put(paramName, actualParameter); } }else{ stringMap = OutputUtils.fillOutputFromStdout(output, stdOutStr, stdErrStr); } } if (stringMap == null || stringMap.isEmpty()) { throw new GFacHandlerException( "Empty Output returned from the Application, Double check the application" + "and ApplicationDescriptor output Parameter Names"); } status.setTransferState(TransferState.DOWNLOAD); detail.setTransferStatus(status); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); app.setStandardError(localStdErrFile.getAbsolutePath()); app.setStandardOutput(localStdOutFile.getAbsolutePath()); if (outputDataDir != null) { app.setOutputDataDirectory(outputDataDir); } } catch (XmlException e) { throw new GFacHandlerException("Cannot read output:" + e.getMessage(), e); } catch (ConnectionException e) { throw new GFacHandlerException(e.getMessage(), e); } catch (TransportException e) { throw new GFacHandlerException(e.getMessage(), e); } catch (IOException e) { throw new GFacHandlerException(e.getMessage(), e); } catch (Exception e) { try { status.setTransferState(TransferState.FAILED); detail.setTransferStatus(status); registry.add(ChildDataType.DATA_TRANSFER_DETAIL,detail, jobExecutionContext.getTaskData().getTaskID()); GFacUtils.saveErrorDetails(e.getLocalizedMessage(), CorrectiveAction.CONTACT_SUPPORT, ErrorCategory.FILE_SYSTEM_FAILURE, jobExecutionContext.getTaskData().getTaskID()); } catch (Exception e1) { throw new GFacHandlerException("Error persisting status", e1, e1.getLocalizedMessage()); } throw new GFacHandlerException("Error in retrieving results", e); } } public void initProperties(Map<String, String> properties) throws GFacHandlerException, GFacException { } }
fixing scpout
modules/gfac/gfac-core/src/main/java/org/apache/airavata/gfac/handler/SCPOutputHandler.java
fixing scpout
<ide><path>odules/gfac/gfac-core/src/main/java/org/apache/airavata/gfac/handler/SCPOutputHandler.java <ide> if(outputDataDir == null) { <ide> outputDataDir = File.separator + "tmp"; <ide> } <del> outputDataDir = outputDataDir + jobExecutionContext.getExperimentID() + "-" +jobExecutionContext.getTaskData().getTaskID(); <add> outputDataDir = outputDataDir + File.separator + jobExecutionContext.getExperimentID() + "-" +jobExecutionContext.getTaskData().getTaskID(); <ide> (new File(outputDataDir)).mkdirs(); <ide> app.setOutputDataDirectory(outputDataDir); // These will be useful if we are doing third party transfer <ide>
Java
apache-2.0
e9a851e868c8c30cf5236d222a24ea6d5d79165c
0
ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-core,ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-core,ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-core
/* Copyright 2015 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.cordovaplugins.core; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.*; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger.LEVEL; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import java.util.ArrayList; import java.util.Iterator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class CDVMFPLogger extends CordovaPlugin { private static final Logger mfpLogger = Logger.getLogger(Logger.INTERNAL_PREFIX + "CDVMFPLogger"); @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { mfpLogger.debug("execute :: action = " + action); if("storeLogs".equals(action)) { boolean shouldStoreLogs = args.getBoolean(0); Logger.storeLogs(shouldStoreLogs); return true; } else if("isStoringLogs".equals(action)) { this.isStoringLogs(callbackContext); return true; } else if("getMaxLogStoreSize".equals(action)) { this.getMaxLogStoreSize(callbackContext); return true; } else if("setMaxLogStoreSize".equals(action)) { int newStoreSize = args.getInt(0); Logger.setMaxLogStoreSize(newStoreSize); callbackContext.success(); return true; } else if("getLogLevel".equals(action)) { this.getLogLevel(callbackContext); return true; } else if("setLogLevel".equals(action)) { LEVEL newLevel = LEVEL.fromString(args.getString(0)); Logger.setLogLevel(newLevel); callbackContext.success(); return true; } else if("setSDKDebugLoggingEnabled".equals(action)) { boolean debugEnabled = args.getBoolean(0); Logger.setSDKDebugLoggingEnabled(debugEnabled); callbackContext.success(); return true; } else if("isSDKDebugLoggingEnabled".equals(action)) { this.isSDKDebugLoggingEnabled(callbackContext); return true; } else if("isUncaughtExceptionDetected".equals(action)) { String uncaughtExceptionFlag = String.valueOf(Logger.isUnCaughtExceptionDetected()); callbackContext.success(uncaughtExceptionFlag); return true; } else if("send".equals(action)) { this.send(callbackContext); return true; } else if("fatal".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.fatal(message); callbackContext.success(); return true; } else if("error".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.error(message); callbackContext.success(); return true; } else if("warn".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.warn(message); callbackContext.success(); return true; } else if("info".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.info(message); callbackContext.success(); return true; } else if("debug".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.debug(message); callbackContext.success(); return true; } return false; } public void getMaxLogStoreSize(final CallbackContext callbackContext) { final int maxStoreSize = Logger.getMaxLogStoreSize(); cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(maxStoreSize); } }); } public void isStoringLogs(final CallbackContext callbackContext){ final int isStoring = Logger.isStoringLogs() ? 1 : 0; cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(isStoring); } }); } public void getLogLevel(final CallbackContext callbackContext) { final String currentLevel = String.valueOf(Logger.getLogLevel()); cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(currentLevel); } }); } public void isSDKDebugLoggingEnabled(final CallbackContext callbackContext) { final int SDKDebugLoggingEnabled = Logger.isSDKDebugLoggingEnabled() ? 1 : 0; cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(SDKDebugLoggingEnabled); } }); } /** * Sends non-Analytics logs to the server * @param callbackContext Callback that will indicate whether the request succeeded or failed */ public void send(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { Logger.send(new ResponseListener() { @Override public void onSuccess(Response r) { callbackContext.success("send(): Successfully sent logs"); } @Override public void onFailure(Response r, Throwable t, JSONObject extendedInfo) { callbackContext.error("send(): Failed to send logs"); } }); } }); } }
src/android/CDVMFPLogger.java
/* Copyright 2015 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.cordovaplugins.core; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.*; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger.LEVEL; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; import java.util.ArrayList; import java.util.Iterator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class CDVMFPLogger extends CordovaPlugin { private static final Logger mfpLogger = Logger.getLogger(Logger.INTERNAL_PREFIX + "CDVMFPLogger"); @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { mfpLogger.debug("execute :: action = " + action); if("storeLogs".equals(action)) { boolean shouldStoreLogs = args.getBoolean(0); Logger.storeLogs(shouldStoreLogs); return true; } else if("isStoringLogs".equals(action)) { this.isStoringLogs(callbackContext); return true; } else if("getMaxLogStoreSize".equals(action)) { this.getMaxLogStoreSize(callbackContext); return true; } else if("setMaxLogStoreSize".equals(action)) { int newStoreSize = args.getInt(0); Logger.setMaxLogStoreSize(newStoreSize); callbackContext.success(); return true; } else if("getLogLevel".equals(action)) { this.getLogLevel(callbackContext); return true; } else if("setLogLevel".equals(action)) { LEVEL newLevel = LEVEL.fromString(args.getString(0)); Logger.setLogLevel(newLevel); callbackContext.success(); return true; } else if("setSDKDebugLoggingEnabled".equals(action)) { boolean debugEnabled = args.getBoolean(0); Logger.setSDKDebugLoggingEnabled(debugEnabled); callbackContext.success(); return true; } else if("isSDKDebugLoggingEnabled".equals(action)) { this.isSDKDebugLoggingEnabled(callbackContext); return true; } else if("isUncaughtExceptionDetected".equals(action)) { String uncaughtExceptionFlag = String.valueOf(Logger.isUnCaughtExceptionDetected()); callbackContext.success(uncaughtExceptionFlag); return true; } else if("send".equals(action)) { this.send(callbackContext); return true; } else if("analytics".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); JSONObject meta = args.getJSONObject(2); Logger instance = Logger.getLogger(packageName); instance.analytics(message, meta); callbackContext.success(); return true; } else if("fatal".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.fatal(message); callbackContext.success(); return true; } else if("error".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.error(message); callbackContext.success(); return true; } else if("warn".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.warn(message); callbackContext.success(); return true; } else if("info".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.info(message); callbackContext.success(); return true; } else if("debug".equals(action)) { String packageName = args.getString(0); String message = args.getString(1); Logger instance = Logger.getLogger(packageName); instance.debug(message); callbackContext.success(); return true; } return false; } public void getMaxLogStoreSize(final CallbackContext callbackContext) { final int maxStoreSize = Logger.getMaxLogStoreSize(); cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(maxStoreSize); } }); } public void isStoringLogs(final CallbackContext callbackContext){ final int isStoring = Logger.isStoringLogs() ? 1 : 0; cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(isStoring); } }); } public void getLogLevel(final CallbackContext callbackContext) { final String currentLevel = String.valueOf(Logger.getLogLevel()); cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(currentLevel); } }); } public void isSDKDebugLoggingEnabled(final CallbackContext callbackContext) { final int SDKDebugLoggingEnabled = Logger.isSDKDebugLoggingEnabled() ? 1 : 0; cordova.getThreadPool().execute(new Runnable() { public void run() { callbackContext.success(SDKDebugLoggingEnabled); } }); } /** * Sends non-Analytics logs to the server * @param callbackContext Callback that will indicate whether the request succeeded or failed */ public void send(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { public void run() { Logger.send(new ResponseListener() { @Override public void onSuccess(Response r) { callbackContext.success("send(): Successfully sent logs"); } @Override public void onFailure(Response r, Throwable t, JSONObject extendedInfo) { callbackContext.error("send(): Failed to send logs"); } }); } }); } }
removed transparency for using analytics level. Use Analytics.log
src/android/CDVMFPLogger.java
removed transparency for using analytics level. Use Analytics.log
<ide><path>rc/android/CDVMFPLogger.java <ide> this.send(callbackContext); <ide> return true; <ide> <del> } else if("analytics".equals(action)) { <del> String packageName = args.getString(0); <del> String message = args.getString(1); <del> JSONObject meta = args.getJSONObject(2); <del> <del> Logger instance = Logger.getLogger(packageName); <del> instance.analytics(message, meta); <del> <del> callbackContext.success(); <del> return true; <ide> } else if("fatal".equals(action)) { <ide> String packageName = args.getString(0); <ide> String message = args.getString(1);
Java
mit
e5c66deb9621eddb30d2be012283d9fe3255e79d
0
yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods
package net.maizegenetics.stats.EMMA; import java.util.ArrayList; import java.util.Arrays; import org.apache.log4j.Logger; import net.maizegenetics.jGLiM.AbstractLinearModel; import net.maizegenetics.jGLiM.LinearModelUtils; import net.maizegenetics.matrixalgebra.Matrix.DoubleMatrix; import net.maizegenetics.matrixalgebra.Matrix.DoubleMatrixFactory; import net.maizegenetics.matrixalgebra.decomposition.EJMLEigenvalueDecomposition; import net.maizegenetics.matrixalgebra.decomposition.EigenvalueDecomposition; public class EMMAforDoubleMatrix { private static final Logger myLogger = Logger.getLogger(EMMAforDoubleMatrix.class); protected DoubleMatrix y; protected double[] lambda; protected double[] eta2; protected double c; protected int N; protected int q; protected int Nran; protected int dfMarker = 0; // protected boolean noZ; protected DoubleMatrix X; protected DoubleMatrix A; protected DoubleMatrix Z = null; // protected DoubleMatrix transZ; protected DoubleMatrix K; protected EigenvalueDecomposition eig; protected EigenvalueDecomposition eigA; protected DoubleMatrix U; protected DoubleMatrix invH; protected DoubleMatrix invXHX; protected DoubleMatrix beta; protected DoubleMatrix Xbeta; protected double ssModel; protected double ssError; protected double SST; protected double Rsq; protected int dfModel; protected int dfError; protected double delta; protected double varResidual; protected double varRandomEffect; protected DoubleMatrix blup; protected DoubleMatrix pred; protected DoubleMatrix res; protected double lnLikelihood; protected boolean findDelta = true; protected double lowerlimit = 1e-5; protected double upperlimit = 1e5; protected int nregions = 100; protected double convergence = 1e-10; protected int maxiter = 50; protected int subintervalCount = 0; public EMMAforDoubleMatrix(DoubleMatrix y, DoubleMatrix fixed, DoubleMatrix kin, int nAlleles) { this(y, fixed, kin, nAlleles, Double.NaN); } /** * This constructor assumes that Z is the identity matrix for calculating blups, predicted values and residuals. If that is not true use * the contstructor that explicity takes Z. This constructor treats A as ZKZ' so it can be used if blups and residuals are not needed. * @param data * @param fixed * @param kin * @param nAlleles * @param delta */ public EMMAforDoubleMatrix(DoubleMatrix data, DoubleMatrix fixed, DoubleMatrix kin, int nAlleles, double delta) { //throw an error if X is less than full column rank dfModel = fixed.numberOfColumns(); int rank = fixed.columnRank(); if (rank < dfModel) throw new IllegalArgumentException("The fixed effect design matrix has less than full column rank. The analysis will not be run."); if (!Double.isNaN(delta)) { this.delta = delta; findDelta = false; } y = data; if (y.numberOfColumns() > 1 && y.numberOfRows() == 1) this.y = y.transpose(); N = y.numberOfRows(); X = fixed; q = X.numberOfColumns(); A = kin; Z = DoubleMatrixFactory.DEFAULT.identity(A.numberOfRows()); Nran = A.numberOfRows(); dfMarker = nAlleles - 1; init(); } /** * This constructor should be used when Z is not the identity matrix. Z is needed to calculate blups and residuals. * @param data * @param fixed * @param kin * @param inZ * @param nAlleles * @param delta */ public EMMAforDoubleMatrix(DoubleMatrix data, DoubleMatrix fixed, DoubleMatrix kin, DoubleMatrix inZ, int nAlleles, double delta) { //I created this constructor becuase it seems that the previous constructor assumes that Z is the identity matrix dfModel = fixed.numberOfColumns(); int rank = fixed.columnRank(); if (rank < dfModel) throw new IllegalArgumentException("The fixed effect design matrix has less than full column rank. The analysis will not be run."); if (!Double.isNaN(delta)) { this.delta = delta; findDelta = false; } y = data; if (y.numberOfColumns() > 1 && y.numberOfRows() == 1) this.y = y.transpose(); N = y.numberOfRows(); X = fixed; q = X.numberOfColumns(); Z = inZ; K = kin; A = Z.mult(K).tcrossproduct(Z); Nran = A.numberOfRows(); dfMarker = nAlleles - 1; init(); } protected void init() { int nreml = N - q; c = nreml * Math.log(nreml / 2 / Math.PI) - nreml; lambda = new double[nreml]; //find the eigenvalues of A eigA = A.getEigenvalueDecomposition(); double[] eigenvalA = eigA.getEigenvalues(); int n = eigenvalA.length; double min = eigenvalA[0]; for (int i = 1; i < n; i++) min = Math.min(min, eigenvalA[i]); double bend = 0.0; if (min < 0.01) bend = -1 * min + 0.5; //S = I - X inv(X'X) X' //X is assumed to be of full column rank, i.e. X'X is non-singular DoubleMatrix[] XtXGM = X.getXtXGM(); DoubleMatrix XtX = XtXGM[0]; DoubleMatrix S = XtXGM[2]; DoubleMatrix G = XtXGM[1]; //determine the s //add bend to the diagonal of A //this is necessary to get correct decomposition of SAS DoubleMatrix A1 = A.copy(); n = A1.numberOfRows(); for (int i = 0; i < n; i++) A1.set(i, i, A1.get(i, i) + bend); DoubleMatrix SAS = S.mult(A1.mult(S)); //decompose SAS eig = SAS.getEigenvalueDecomposition(); //which are the zero eigenvalues? double[] eigenval = eig.getEigenvalues(); int[] ndx = getSortedIndexofAbsoluteValues(eigenval); int[] eigndx = new int[nreml]; for (int i = 0; i < nreml; i++) eigndx[i] = ndx[i]; //sort V to get U DoubleMatrix V = eig.getEigenvectors(); U = V.getSelection(null, ndx); //derive lambda for (int i = 0; i < nreml; i++) lambda[i] = eigenval[eigndx[i]] - bend; } private int[] getSortedIndexofAbsoluteValues(double[] values) { int n = values.length; int[] index = new int[n]; class Pair implements Comparable<Pair> { int order; double absvalue; Pair(int order, double value){ this.order = order; this.absvalue = Math.abs(value); } @Override public int compareTo(Pair other) { if (absvalue < other.absvalue) return 1; if (absvalue > other.absvalue) return -1; return 0; } } Pair[] valuePairs = new Pair[n]; for (int i = 0; i < n; i++) { valuePairs[i] = new Pair(i, values[i]); } Arrays.sort(valuePairs); for (int i = 0; i < n; i++) index[i] = valuePairs[i].order; return index; } public void solve() { //calculate eta squared DoubleMatrix eta = U.crossproduct(y); int nrows = eta.numberOfRows(); eta2 = new double[nrows]; for (int i = 0; i < nrows; i++) eta2[i] = eta.get(i, 0) * eta.get(i, 0); if (findDelta) { double[] interval = new double[]{lowerlimit, upperlimit}; delta = findDeltaInInterval(interval); } lnLikelihood = lnlk(delta); invH = inverseH(delta); beta = calculateBeta(); blup = calculateBLUP(); pred = calculatePred(); res = calculateRes(); double genvar = getGenvar(beta); dfModel = q - 1; dfError = N - q; varResidual = genvar * delta; varRandomEffect = genvar; } private double findDeltaInInterval(double[] interval) { double[][] d = scanlnlk(interval[0], interval[1]); double[][] sgnchange = findSignChanges(d); int nchanges = sgnchange.length; double[] bestd = new double[]{Double.NaN, Double.NaN, Double.NaN}; int n = d.length; //find the element of d with maximum ln Likelihood (bestd) for (int i = 0; i < n; i++) { if (Double.isNaN(bestd[1])) bestd = d[i]; else if (!Double.isNaN(d[i][1]) && d[i][1] > bestd[1]) bestd = d[i]; } double bestdelta = bestd[0]; double lkDelta = bestd[1]; for (int i = 0; i < nchanges; i++) { double newdelta = findMaximum(sgnchange[i]); if (!Double.isNaN(newdelta)) { double newlk = lnlk(newdelta); if (!Double.isNaN(newlk) && newlk > lkDelta) { bestdelta = newdelta; lkDelta = newlk; } } } return bestdelta; } private double lnlk(double delta) { double term1 = 0; double term2 = 0; int n = N - q; for (int i = 0; i < n; i++) { double val = (lambda[i] + delta); if (val < 0) return Double.NaN; term1 += eta2[i] / val; term2 += Math.log(val); } return (c - n * Math.log(term1) - term2) / 2; } private double d1lnlk(double delta) { double term1 = 0; double term2 = 0; double term3 = 0; int n = N - q; for (int i = 0; i < n; i++) { double val = 1 / (lambda[i] + delta); double val2 = eta2[i] * val; term1 += val2; term2 += val2 * val; term3 += val; } return n * term2 / term1 / 2 - term3 / 2; } private double[][] scanlnlk(double lower, double upper) { double[][] result = new double[nregions][3]; upper = Math.log10(upper); lower = Math.log10(lower); double incr = (upper - lower) / (nregions - 1); for (int i = 0; i < nregions; i++) { double delta = Math.pow(10.0, lower + i * incr); result[i][0] = delta; result[i][1] = lnlk(delta); result[i][2] = d1lnlk(delta); } return result; } private double[][] findSignChanges(double[][] scan) { ArrayList<Double[]> changes = new ArrayList<Double[]>(); int n = scan.length; for (int i = 0; i < n - 1; i++) { if (scan[i][2] > 0 && scan[i+1][2] <= 0 && !Double.isNaN(scan[i][1])) changes.add(new Double[]{scan[i][0], scan[i+1][0]}); } n = changes.size(); double[][] result = new double[n][2]; for (int i = 0; i < n; i++) { result[i][0] = changes.get(i)[0]; result[i][1] = changes.get(i)[1]; } return result; } private double findMaximum(double[] interval) { //uses Newton Raphson to find local maximum //updates delta using delta' = delta - d1/d2 //where d1 is the first derivative of lnlk at delta and //d2 is the second derivative of lnlk at delta //the local maximum is expected to fall between delta and max //if the algorithm finds a new delta outside this interval //then the likelihood is not well behaved in this interval //subdivide the interval and try again double delta = interval[0]; boolean end = false; int n = N - q; int nIterations = 0; while (!end && nIterations < maxiter) { //A = sum[eta2/(lambda + delta)] //B = sum[eta2/(lambda + delta)^2] //C = sum[eta2/(lambda + delta)^3] //D = sum[1/(lambda + delta)] //E = sum[1/(lambda + delta)^2] double A = 0; double B = 0; double C = 0; double D = 0; double E = 0; for (int i = 0; i < n; i++) { double val = lambda[i] + delta; double val2 = val * val; double val3 = val2 * val; A += eta2[i]/val; B += eta2[i]/val2; C += eta2[i]/val3; D += 1/val; E += 1/val2; } double d1 = n*B/A - D; if (Math.abs(d1) < convergence) end = true; else { double d2 = E + n*(B*B - 2*A*C)/A/A; delta = delta - d1/d2; } if (delta < interval[0] || delta > interval[1]) { subintervalCount++; if (subintervalCount > 3) { subintervalCount = 0; return Double.NaN; } delta = findDeltaInInterval(interval); end = true; } nIterations++; } subintervalCount = 0; return delta; } private DoubleMatrix inverseH(double delta) { DoubleMatrix V = eigA.getEigenvectors(); DoubleMatrix D = eigA.getEigenvalueMatrix(); int n = D.numberOfRows(); for (int i = 0; i < n; i++) D.set(i, i, 1 / (D.get(i, i) + delta)); return V.mult(D.tcrossproduct(V)); } private DoubleMatrix calculateBeta() { DoubleMatrix XtH = X.crossproduct(invH); invXHX = XtH.mult(X).inverse(); return invXHX.mult(XtH.mult(y)); } private DoubleMatrix calculateBLUP(){ Xbeta = X.mult(beta); DoubleMatrix YminusXbeta = y.minus(Xbeta); DoubleMatrix KtransZ = K.mult(Z.transpose()); DoubleMatrix KtransZinvH = KtransZ.mult(invH); return KtransZinvH.mult(YminusXbeta); } private DoubleMatrix calculatePred(){ Xbeta = X.mult(beta); DoubleMatrix Zu = Z.mult(blup); return Xbeta.plus(Zu); } private DoubleMatrix calculateRes(){ return y.minus(pred); } private double getGenvar(DoubleMatrix beta) { DoubleMatrix res = y.copy(); res.minusEquals(X.mult(beta)); return res.crossproduct(invH.mult(res)).get(0,0) / (N - q); } public int getDfMarker() { return dfMarker; } public DoubleMatrix getBeta() { return beta; } public int getDfModel() { return dfModel; } public int getDfError() { return dfError; } public double getDelta() { return delta; } public DoubleMatrix getInvH() { return invH; } public double getVarRes() { return varResidual; } public double getVarRan() { return varRandomEffect; } public DoubleMatrix getBlup() { return blup; } public DoubleMatrix getPred() { return pred; } public DoubleMatrix getRes() { return res; } public double getLnLikelihood() { return lnLikelihood; } public double[] getMarkerFp() { if (dfMarker < 1) return new double[]{Double.NaN, Double.NaN, Double.NaN}; int nparm = beta.numberOfRows(); int firstmarker = nparm - dfMarker; DoubleMatrix M = DoubleMatrixFactory.DEFAULT.make(dfMarker, nparm); for (int i = 0; i < dfMarker; i++) M.set(i, i + firstmarker, 1); DoubleMatrix MB = M.mult(beta); DoubleMatrix invMiM = M.mult(invXHX.tcrossproduct(M)); invMiM.invert(); double F = MB.crossproduct(invMiM.mult(MB)).get(0,0); F /= varRandomEffect; F /= dfMarker; double p; try { p = LinearModelUtils.Ftest(F, dfMarker, N - q); } catch (Exception e) {p = Double.NaN;} return new double[]{F,p}; } public void solveWithNewData(DoubleMatrix y) { this.y = y; solve(); } }
src/net/maizegenetics/stats/EMMA/EMMAforDoubleMatrix.java
package net.maizegenetics.stats.EMMA; import java.util.ArrayList; import java.util.Arrays; import org.apache.log4j.Logger; import net.maizegenetics.jGLiM.AbstractLinearModel; import net.maizegenetics.jGLiM.LinearModelUtils; import net.maizegenetics.matrixalgebra.Matrix.DoubleMatrix; import net.maizegenetics.matrixalgebra.Matrix.DoubleMatrixFactory; import net.maizegenetics.matrixalgebra.decomposition.EJMLEigenvalueDecomposition; import net.maizegenetics.matrixalgebra.decomposition.EigenvalueDecomposition; public class EMMAforDoubleMatrix { private static final Logger myLogger = Logger.getLogger(EMMAforDoubleMatrix.class); protected DoubleMatrix y; protected double[] lambda; protected double[] eta2; protected double c; protected int N; protected int q; protected int Nran; protected int dfMarker = 0; protected DoubleMatrix X; protected DoubleMatrix A; protected EigenvalueDecomposition eig; protected EigenvalueDecomposition eigA; protected DoubleMatrix U; protected DoubleMatrix invH; protected DoubleMatrix invXHX; protected DoubleMatrix beta; protected double ssModel; protected double ssError; protected double SST; protected double Rsq; protected int dfModel; protected int dfError; protected double delta; protected double varResidual; protected double varRandomEffect; protected DoubleMatrix blup; protected DoubleMatrix pred; protected DoubleMatrix res; protected double lnLikelihood; protected boolean findDelta = true; protected double lowerlimit = 1e-5; protected double upperlimit = 1e5; protected int nregions = 100; protected double convergence = 1e-10; protected int maxiter = 50; protected int subintervalCount = 0; public EMMAforDoubleMatrix(DoubleMatrix y, DoubleMatrix fixed, DoubleMatrix kin, int nAlleles) { this(y, fixed, kin, nAlleles, Double.NaN); } public EMMAforDoubleMatrix(DoubleMatrix data, DoubleMatrix fixed, DoubleMatrix kin, int nAlleles, double delta) { //throw an error if X is less than full column rank dfModel = fixed.numberOfColumns(); int rank = fixed.columnRank(); if (rank < dfModel) throw new IllegalArgumentException("The fixed effect design matrix has less than full column rank. The analysis will not be run."); if (!Double.isNaN(delta)) { this.delta = delta; findDelta = false; } y = data; if (y.numberOfColumns() > 1 && y.numberOfRows() == 1) this.y = y.transpose(); else this.y = y; N = y.numberOfRows(); X = fixed; q = X.numberOfColumns(); A = kin; Nran = A.numberOfRows(); dfMarker = nAlleles - 1; init(); } protected void init() { int nreml = N - q; c = nreml * Math.log(nreml / 2 / Math.PI) - nreml; lambda = new double[nreml]; //find the eigenvalues of A eigA = A.getEigenvalueDecomposition(); double[] eigenvalA = eigA.getEigenvalues(); int n = eigenvalA.length; double min = eigenvalA[0]; for (int i = 1; i < n; i++) min = Math.min(min, eigenvalA[i]); double bend = 0.0; if (min < 0.01) bend = -1 * min + 0.5; //S = I - X inv(X'X) X' //X is assumed to be of full column rank, i.e. X'X is non-singular DoubleMatrix[] XtXGM = X.getXtXGM(); DoubleMatrix XtX = XtXGM[0]; DoubleMatrix S = XtXGM[2]; DoubleMatrix G = XtXGM[1]; //determine the s //add bend to the diagonal of A //this is necessary to get correct decomposition of SAS DoubleMatrix A1 = A.copy(); n = A1.numberOfRows(); for (int i = 0; i < n; i++) A1.set(i, i, A1.get(i, i) + bend); DoubleMatrix SAS = S.mult(A1.mult(S)); //decompose SAS eig = SAS.getEigenvalueDecomposition(); //which are the zero eigenvalues? double[] eigenval = eig.getEigenvalues(); int[] ndx = getSortedIndexofAbsoluteValues(eigenval); int[] eigndx = new int[nreml]; for (int i = 0; i < nreml; i++) eigndx[i] = ndx[i]; //sort V to get U DoubleMatrix V = eig.getEigenvectors(); U = V.getSelection(null, ndx); //derive lambda for (int i = 0; i < nreml; i++) lambda[i] = eigenval[eigndx[i]] - bend; } private int[] getSortedIndexofAbsoluteValues(double[] values) { int n = values.length; int[] index = new int[n]; class Pair implements Comparable<Pair> { int order; double absvalue; Pair(int order, double value){ this.order = order; this.absvalue = Math.abs(value); } @Override public int compareTo(Pair other) { if (absvalue < other.absvalue) return 1; if (absvalue > other.absvalue) return -1; return 0; } } Pair[] valuePairs = new Pair[n]; for (int i = 0; i < n; i++) { valuePairs[i] = new Pair(i, values[i]); } Arrays.sort(valuePairs); for (int i = 0; i < n; i++) index[i] = valuePairs[i].order; return index; } public void solve() { //calculate eta squared DoubleMatrix eta = U.crossproduct(y); int nrows = eta.numberOfRows(); eta2 = new double[nrows]; for (int i = 0; i < nrows; i++) eta2[i] = eta.get(i, 0) * eta.get(i, 0); if (findDelta) { double[] interval = new double[]{lowerlimit, upperlimit}; delta = findDeltaInInterval(interval); } lnLikelihood = lnlk(delta); invH = inverseH(delta); beta = calculateBeta(); double genvar = getGenvar(beta); dfModel = q - 1; dfError = N - q; varResidual = genvar * delta; varRandomEffect = genvar; calculatePredRes(); } private double findDeltaInInterval(double[] interval) { double[][] d = scanlnlk(interval[0], interval[1]); double[][] sgnchange = findSignChanges(d); int nchanges = sgnchange.length; double[] bestd = new double[]{Double.NaN, Double.NaN, Double.NaN}; int n = d.length; //find the element of d with maximum ln Likelihood (bestd) for (int i = 0; i < n; i++) { if (Double.isNaN(bestd[1])) bestd = d[i]; else if (!Double.isNaN(d[i][1]) && d[i][1] > bestd[1]) bestd = d[i]; } double bestdelta = bestd[0]; double lkDelta = bestd[1]; for (int i = 0; i < nchanges; i++) { double newdelta = findMaximum(sgnchange[i]); if (!Double.isNaN(newdelta)) { double newlk = lnlk(newdelta); if (!Double.isNaN(newlk) && newlk > lkDelta) { bestdelta = newdelta; lkDelta = newlk; } } } return bestdelta; } private double lnlk(double delta) { double term1 = 0; double term2 = 0; int n = N - q; for (int i = 0; i < n; i++) { double val = (lambda[i] + delta); if (val < 0) return Double.NaN; term1 += eta2[i] / val; term2 += Math.log(val); } return (c - n * Math.log(term1) - term2) / 2; } private double d1lnlk(double delta) { double term1 = 0; double term2 = 0; double term3 = 0; int n = N - q; for (int i = 0; i < n; i++) { double val = 1 / (lambda[i] + delta); double val2 = eta2[i] * val; term1 += val2; term2 += val2 * val; term3 += val; } return n * term2 / term1 / 2 - term3 / 2; } private double[][] scanlnlk(double lower, double upper) { double[][] result = new double[nregions][3]; upper = Math.log10(upper); lower = Math.log10(lower); double incr = (upper - lower) / (nregions - 1); for (int i = 0; i < nregions; i++) { double delta = Math.pow(10.0, lower + i * incr); result[i][0] = delta; result[i][1] = lnlk(delta); result[i][2] = d1lnlk(delta); } return result; } private double[][] findSignChanges(double[][] scan) { ArrayList<Double[]> changes = new ArrayList<Double[]>(); int n = scan.length; for (int i = 0; i < n - 1; i++) { if (scan[i][2] > 0 && scan[i+1][2] <= 0 && !Double.isNaN(scan[i][1])) changes.add(new Double[]{scan[i][0], scan[i+1][0]}); } n = changes.size(); double[][] result = new double[n][2]; for (int i = 0; i < n; i++) { result[i][0] = changes.get(i)[0]; result[i][1] = changes.get(i)[1]; } return result; } private double findMaximum(double[] interval) { //uses Newton Raphson to find local maximum //updates delta using delta' = delta - d1/d2 //where d1 is the first derivative of lnlk at delta and //d2 is the second derivative of lnlk at delta //the local maximum is expected to fall between delta and max //if the algorithm finds a new delta outside this interval //then the likelihood is not well behaved in this interval //subdivide the interval and try again double delta = interval[0]; boolean end = false; int n = N - q; int nIterations = 0; while (!end && nIterations < maxiter) { //A = sum[eta2/(lambda + delta)] //B = sum[eta2/(lambda + delta)^2] //C = sum[eta2/(lambda + delta)^3] //D = sum[1/(lambda + delta)] //E = sum[1/(lambda + delta)^2] double A = 0; double B = 0; double C = 0; double D = 0; double E = 0; for (int i = 0; i < n; i++) { double val = lambda[i] + delta; double val2 = val * val; double val3 = val2 * val; A += eta2[i]/val; B += eta2[i]/val2; C += eta2[i]/val3; D += 1/val; E += 1/val2; } double d1 = n*B/A - D; if (Math.abs(d1) < convergence) end = true; else { double d2 = E + n*(B*B - 2*A*C)/A/A; delta = delta - d1/d2; } if (delta < interval[0] || delta > interval[1]) { subintervalCount++; if (subintervalCount > 3) { subintervalCount = 0; return Double.NaN; } delta = findDeltaInInterval(interval); end = true; } nIterations++; } subintervalCount = 0; return delta; } private DoubleMatrix inverseH(double delta) { DoubleMatrix V = eigA.getEigenvectors(); DoubleMatrix D = eigA.getEigenvalueMatrix(); int n = D.numberOfRows(); for (int i = 0; i < n; i++) D.set(i, i, 1 / (D.get(i, i) + delta)); return V.mult(D.tcrossproduct(V)); } private DoubleMatrix calculateBeta() { DoubleMatrix XtH = X.crossproduct(invH); invXHX = XtH.mult(X).inverse(); return invXHX.mult(XtH.mult(y)); } private double getGenvar(DoubleMatrix beta) { DoubleMatrix res = y.copy(); res.minusEquals(X.mult(beta)); return res.crossproduct(invH.mult(res)).get(0,0) / (N - q); } public int getDfMarker() { return dfMarker; } public DoubleMatrix getBeta() { return beta; } public int getDfModel() { return dfModel; } public int getDfError() { return dfError; } public double getDelta() { return delta; } public DoubleMatrix getInvH() { return invH; } public double getVarRes() { return varResidual; } public double getVarRan() { return varRandomEffect; } public DoubleMatrix getBlup() { return blup; } public DoubleMatrix getPred() { return pred; } public DoubleMatrix getRes() { return res; } public double getLnLikelihood() { return lnLikelihood; } public void calculatePredRes() { pred = X.mult(beta); res = y.minus(pred); } public double[] getMarkerFp() { if (dfMarker < 1) return new double[]{Double.NaN, Double.NaN, Double.NaN}; int nparm = beta.numberOfRows(); int firstmarker = nparm - dfMarker; DoubleMatrix M = DoubleMatrixFactory.DEFAULT.make(dfMarker, nparm); for (int i = 0; i < dfMarker; i++) M.set(i, i + firstmarker, 1); DoubleMatrix MB = M.mult(beta); DoubleMatrix invMiM = M.mult(invXHX.tcrossproduct(M)); invMiM.invert(); double F = MB.crossproduct(invMiM.mult(MB)).get(0,0); F /= varRandomEffect; F /= dfMarker; double p; try { p = LinearModelUtils.Ftest(F, dfMarker, N - q); } catch (Exception e) {p = Double.NaN;} return new double[]{F,p}; } public void solveWithNewData(DoubleMatrix y) { this.y = y; solve(); } }
adds code to calculate blups, predicted values, and residuals
src/net/maizegenetics/stats/EMMA/EMMAforDoubleMatrix.java
adds code to calculate blups, predicted values, and residuals
<ide><path>rc/net/maizegenetics/stats/EMMA/EMMAforDoubleMatrix.java <ide> protected int Nran; <ide> protected int dfMarker = 0; <ide> <add>// protected boolean noZ; <add> <ide> protected DoubleMatrix X; <ide> protected DoubleMatrix A; <add> protected DoubleMatrix Z = null; <add>// protected DoubleMatrix transZ; <add> protected DoubleMatrix K; <ide> protected EigenvalueDecomposition eig; <ide> protected EigenvalueDecomposition eigA; <ide> protected DoubleMatrix U; <ide> protected DoubleMatrix invXHX; <ide> <ide> protected DoubleMatrix beta; <add> protected DoubleMatrix Xbeta; <ide> protected double ssModel; <ide> protected double ssError; <ide> protected double SST; <ide> this(y, fixed, kin, nAlleles, Double.NaN); <ide> } <ide> <add> /** <add> * This constructor assumes that Z is the identity matrix for calculating blups, predicted values and residuals. If that is not true use <add> * the contstructor that explicity takes Z. This constructor treats A as ZKZ' so it can be used if blups and residuals are not needed. <add> * @param data <add> * @param fixed <add> * @param kin <add> * @param nAlleles <add> * @param delta <add> */ <ide> public EMMAforDoubleMatrix(DoubleMatrix data, DoubleMatrix fixed, DoubleMatrix kin, int nAlleles, double delta) { <ide> //throw an error if X is less than full column rank <ide> dfModel = fixed.numberOfColumns(); <ide> <ide> y = data; <ide> if (y.numberOfColumns() > 1 && y.numberOfRows() == 1) this.y = y.transpose(); <del> else this.y = y; <ide> <ide> N = y.numberOfRows(); <ide> X = fixed; <del> <add> <ide> q = X.numberOfColumns(); <ide> A = kin; <add> Z = DoubleMatrixFactory.DEFAULT.identity(A.numberOfRows()); <add> <add> Nran = A.numberOfRows(); <add> dfMarker = nAlleles - 1; <add> init(); <add> } <add> <add> /** <add> * This constructor should be used when Z is not the identity matrix. Z is needed to calculate blups and residuals. <add> * @param data <add> * @param fixed <add> * @param kin <add> * @param inZ <add> * @param nAlleles <add> * @param delta <add> */ <add> public EMMAforDoubleMatrix(DoubleMatrix data, DoubleMatrix fixed, DoubleMatrix kin, DoubleMatrix inZ, int nAlleles, double delta) { <add> //I created this constructor becuase it seems that the previous constructor assumes that Z is the identity matrix <add> dfModel = fixed.numberOfColumns(); <add> <add> int rank = fixed.columnRank(); <add> if (rank < dfModel) throw new IllegalArgumentException("The fixed effect design matrix has less than full column rank. The analysis will not be run."); <add> if (!Double.isNaN(delta)) { <add> this.delta = delta; <add> findDelta = false; <add> } <add> <add> y = data; <add> if (y.numberOfColumns() > 1 && y.numberOfRows() == 1) this.y = y.transpose(); <add> <add> N = y.numberOfRows(); <add> X = fixed; <add> <add> q = X.numberOfColumns(); <add> Z = inZ; <add> K = kin; <add> <add> A = Z.mult(K).tcrossproduct(Z); <add> <ide> Nran = A.numberOfRows(); <ide> dfMarker = nAlleles - 1; <ide> init(); <ide> eigA = A.getEigenvalueDecomposition(); <ide> double[] eigenvalA = eigA.getEigenvalues(); <ide> int n = eigenvalA.length; <add> <ide> double min = eigenvalA[0]; <ide> for (int i = 1; i < n; i++) min = Math.min(min, eigenvalA[i]); <ide> double bend = 0.0; <ide> lnLikelihood = lnlk(delta); <ide> invH = inverseH(delta); <ide> beta = calculateBeta(); <add> blup = calculateBLUP(); <add> pred = calculatePred(); <add> res = calculateRes(); <ide> double genvar = getGenvar(beta); <ide> <ide> dfModel = q - 1; <ide> dfError = N - q; <ide> varResidual = genvar * delta; <ide> varRandomEffect = genvar; <del> calculatePredRes(); <ide> } <ide> <ide> private double findDeltaInInterval(double[] interval) { <ide> return invXHX.mult(XtH.mult(y)); <ide> } <ide> <add> private DoubleMatrix calculateBLUP(){ <add> Xbeta = X.mult(beta); <add> DoubleMatrix YminusXbeta = y.minus(Xbeta); <add> DoubleMatrix KtransZ = K.mult(Z.transpose()); <add> DoubleMatrix KtransZinvH = KtransZ.mult(invH); <add> return KtransZinvH.mult(YminusXbeta); <add> } <add> <add> private DoubleMatrix calculatePred(){ <add> Xbeta = X.mult(beta); <add> DoubleMatrix Zu = Z.mult(blup); <add> return Xbeta.plus(Zu); <add> } <add> <add> private DoubleMatrix calculateRes(){ <add> return y.minus(pred); <add> } <add> <add> <add> <add> <ide> private double getGenvar(DoubleMatrix beta) { <ide> DoubleMatrix res = y.copy(); <ide> res.minusEquals(X.mult(beta)); <ide> return lnLikelihood; <ide> } <ide> <del> public void calculatePredRes() { <del> pred = X.mult(beta); <del> res = y.minus(pred); <del> } <del> <add> <ide> public double[] getMarkerFp() { <ide> if (dfMarker < 1) return new double[]{Double.NaN, Double.NaN, Double.NaN}; <ide> int nparm = beta.numberOfRows();
Java
bsd-3-clause
8cfb08609ae650f1cd7d04b3d393125a41270236
0
exponent/react-native,janicduplessis/react-native,javache/react-native,hoangpham95/react-native,hammerandchisel/react-native,exponentjs/react-native,hammerandchisel/react-native,pandiaraj44/react-native,javache/react-native,hoangpham95/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponentjs/react-native,pandiaraj44/react-native,janicduplessis/react-native,exponent/react-native,hoangpham95/react-native,myntra/react-native,exponentjs/react-native,myntra/react-native,facebook/react-native,arthuralee/react-native,facebook/react-native,facebook/react-native,hammerandchisel/react-native,exponent/react-native,hammerandchisel/react-native,myntra/react-native,facebook/react-native,arthuralee/react-native,facebook/react-native,exponent/react-native,pandiaraj44/react-native,arthuralee/react-native,myntra/react-native,javache/react-native,javache/react-native,hoangpham95/react-native,javache/react-native,janicduplessis/react-native,exponent/react-native,hoangpham95/react-native,janicduplessis/react-native,pandiaraj44/react-native,janicduplessis/react-native,pandiaraj44/react-native,exponent/react-native,facebook/react-native,janicduplessis/react-native,exponentjs/react-native,hammerandchisel/react-native,exponentjs/react-native,pandiaraj44/react-native,exponentjs/react-native,janicduplessis/react-native,hammerandchisel/react-native,arthuralee/react-native,myntra/react-native,exponent/react-native,facebook/react-native,janicduplessis/react-native,hoangpham95/react-native,myntra/react-native,pandiaraj44/react-native,arthuralee/react-native,hoangpham95/react-native,facebook/react-native,pandiaraj44/react-native,myntra/react-native,javache/react-native,myntra/react-native,javache/react-native,myntra/react-native,javache/react-native,facebook/react-native,exponentjs/react-native,exponentjs/react-native,hammerandchisel/react-native,exponent/react-native,javache/react-native
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.turbomodule.core; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JSIModule; import com.facebook.react.bridge.JavaScriptContextHolder; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.queue.MessageQueueThread; import com.facebook.react.turbomodule.core.interfaces.JSCallInvokerHolder; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import com.facebook.react.turbomodule.core.interfaces.TurboModuleRegistry; import com.facebook.soloader.SoLoader; import java.util.*; import javax.annotation.Nullable; /** * This is the main class and entry point for TurboModules. * Note that this is a hybrid class, and has a C++ counterpart * This class installs the JSI bindings. It also implements the method to get a Java module, that the C++ counterpart calls. */ public class TurboModuleManager implements JSIModule, TurboModuleRegistry { static { SoLoader.loadLibrary("turbomodulejsijni"); } private final TurboModuleManagerDelegate mTurbomoduleManagerDelegate; private final Map<String, TurboModule> mTurboModules = new HashMap<>(); @DoNotStrip @SuppressWarnings("unused") private final HybridData mHybridData; public TurboModuleManager(JavaScriptContextHolder jsContext, TurboModuleManagerDelegate tmmDelegate, JSCallInvokerHolder instanceHolder) { mHybridData = initHybrid(jsContext.get(), (JSCallInvokerHolderImpl) instanceHolder, tmmDelegate); mTurbomoduleManagerDelegate = tmmDelegate; } @DoNotStrip @Nullable protected TurboModule getJavaModule(String name) { if (!mTurboModules.containsKey(name)) { final TurboModule turboModule = mTurbomoduleManagerDelegate.getModule(name); if (turboModule != null) { /** * TurboModuleManager is initialized after ReactApplicationContext has been setup. * Therefore, it's safe to call initialize on the TurboModule. */ ((NativeModule)turboModule).initialize(); mTurboModules.put(name, turboModule); } } return mTurboModules.get(name); } @Nullable public TurboModule getModule(String name) { return getJavaModule(name); } public Collection<TurboModule> getModules() { return mTurboModules.values(); } public boolean hasModule(String name) { return mTurboModules.containsKey(name); } private native HybridData initHybrid(long jsContext, JSCallInvokerHolderImpl jsQueue, TurboModuleManagerDelegate tmmDelegate); private native void installJSIBindings(); public void installBindings() { installJSIBindings(); } @Override public void initialize() {} @Override public void onCatalystInstanceDestroy() {} }
ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.turbomodule.core; import com.facebook.jni.HybridData; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.JSIModule; import com.facebook.react.bridge.JavaScriptContextHolder; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.queue.MessageQueueThread; import com.facebook.react.turbomodule.core.interfaces.JSCallInvokerHolder; import com.facebook.react.turbomodule.core.interfaces.TurboModule; import com.facebook.react.turbomodule.core.interfaces.TurboModuleRegistry; import com.facebook.soloader.SoLoader; import java.util.*; import javax.annotation.Nullable; /** * This is the main class and entry point for TurboModules. * Note that this is a hybrid class, and has a C++ counterpart * This class installs the JSI bindings. It also implements the method to get a Java module, that the C++ counterpart calls. */ public class TurboModuleManager implements JSIModule, TurboModuleRegistry { static { SoLoader.loadLibrary("turbomodulejsijni"); } private final ReactApplicationContext mReactApplicationContext; private final TurboModuleManagerDelegate mTurbomoduleManagerDelegate; private final Map<String, TurboModule> mTurboModules = new HashMap<>(); @DoNotStrip @SuppressWarnings("unused") private final HybridData mHybridData; public TurboModuleManager( ReactApplicationContext reactApplicationContext, JavaScriptContextHolder jsContext, TurboModuleManagerDelegate tmmDelegate, JSCallInvokerHolder instanceHolder) { mReactApplicationContext = reactApplicationContext; mHybridData = initHybrid(jsContext.get(), (JSCallInvokerHolderImpl) instanceHolder, tmmDelegate); mTurbomoduleManagerDelegate = tmmDelegate; } @DoNotStrip @Nullable protected TurboModule getJavaModule(String name) { if (!mTurboModules.containsKey(name)) { final TurboModule turboModule = mTurbomoduleManagerDelegate.getModule(name); if (turboModule != null) { /** * TurboModuleManager is initialized after ReactApplicationContext has been setup. * Therefore, it's safe to call initialize on the TurboModule. */ ((NativeModule)turboModule).initialize(); mTurboModules.put(name, turboModule); } } return mTurboModules.get(name); } @Nullable public TurboModule getModule(String name) { return getJavaModule(name); } public Collection<TurboModule> getModules() { return mTurboModules.values(); } public boolean hasModule(String name) { return mTurboModules.containsKey(name); } private native HybridData initHybrid(long jsContext, JSCallInvokerHolderImpl jsQueue, TurboModuleManagerDelegate tmmDelegate); private native void installJSIBindings(); public void installBindings() { installJSIBindings(); } @Override public void initialize() {} @Override public void onCatalystInstanceDestroy() {} }
Remove TurboModuleManager dependency on ReactApplicationContext Summary: TurboModuleManager doesn't need access to ReactApplicationContext. Reviewed By: ejanzer Differential Revision: D16076581 fbshipit-source-id: 7b825c5a75d352aa6e83ed76c46f1cd70ba92ab2
ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java
Remove TurboModuleManager dependency on ReactApplicationContext
<ide><path>eactAndroid/src/main/java/com/facebook/react/turbomodule/core/TurboModuleManager.java <ide> SoLoader.loadLibrary("turbomodulejsijni"); <ide> } <ide> <del> private final ReactApplicationContext mReactApplicationContext; <ide> private final TurboModuleManagerDelegate mTurbomoduleManagerDelegate; <ide> <ide> private final Map<String, TurboModule> mTurboModules = new HashMap<>(); <ide> @SuppressWarnings("unused") <ide> private final HybridData mHybridData; <ide> <del> public TurboModuleManager( <del> ReactApplicationContext reactApplicationContext, JavaScriptContextHolder jsContext, TurboModuleManagerDelegate tmmDelegate, JSCallInvokerHolder instanceHolder) { <del> mReactApplicationContext = reactApplicationContext; <add> public TurboModuleManager(JavaScriptContextHolder jsContext, TurboModuleManagerDelegate tmmDelegate, JSCallInvokerHolder instanceHolder) { <ide> mHybridData = initHybrid(jsContext.get(), (JSCallInvokerHolderImpl) instanceHolder, tmmDelegate); <ide> mTurbomoduleManagerDelegate = tmmDelegate; <ide> }
Java
apache-2.0
0d55dd8c245e0f08f37b3cd8dd1884375d5de140
0
wcm-io-qa/wcm-io-qa-galenium,wcm-io-qa/wcm-io-qa-galenium,wcm-io-qa/wcm-io-qa-galenium
/* * #%L * wcm.io * %% * Copyright (C) 2018 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.qa.galenium.mediaquery; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import io.wcm.qa.galenium.device.TestDevice; import io.wcm.qa.galenium.exceptions.GaleniumException; import io.wcm.qa.galenium.reporting.GaleniumReportUtil; import io.wcm.qa.galenium.util.ConfigurationUtil; import io.wcm.qa.galenium.util.GaleniumConfiguration; import io.wcm.qa.galenium.util.GaleniumContext; public final class MediaQueryUtil { private static final int CONFIGURED_MAX_WIDTH = GaleniumConfiguration.getMediaQueryMaximalWidth(); private static final int CONFIGURED_MIN_WIDTH = GaleniumConfiguration.getMediaQueryMinimalWidth(); private static final MediaQuery DEFAULT_MEDIA_QUERY = getNewMediaQuery("DEFAULT_MQ", CONFIGURED_MIN_WIDTH, CONFIGURED_MAX_WIDTH); private MediaQueryUtil() { // do not instantiate } public static MediaQuery getCurrentMediaQuery() { WebDriver driver = GaleniumContext.getDriver(); if (driver == null) { return DEFAULT_MEDIA_QUERY; } Collection<MediaQuery> mediaQueries = getMediaQueries(); for (MediaQuery mediaQuery : mediaQueries) { if (matchesCurrentTestDevice(mediaQuery)) { return mediaQuery; } } return DEFAULT_MEDIA_QUERY; } public static Collection<MediaQuery> getMediaQueries() { String propertiesFilePath = GaleniumConfiguration.getMediaQueryPropertiesPath(); if (StringUtils.isBlank(propertiesFilePath)) { throw new GaleniumException("path to media query properties is empty"); } return getMediaQueries(propertiesFilePath); } public static Collection<MediaQuery> getMediaQueries(File mediaQueryPropertyFile) { if (mediaQueryPropertyFile == null) { throw new GaleniumException("media query properties file is null."); } if (!mediaQueryPropertyFile.isFile()) { throw new GaleniumException("media query properties file is not a file."); } return getMediaQueries(mediaQueryPropertyFile.getPath()); } public static Collection<MediaQuery> getMediaQueries(Properties mediaQueryProperties) { Collection<MediaQuery> mediaQueries = new ArrayList<MediaQuery>(); SortedMap<Integer, String> sortedMediaQueryMap = getSortedMediaQueryMap(mediaQueryProperties); Set<Entry<Integer, String>> entrySet = sortedMediaQueryMap.entrySet(); int lowerBound = CONFIGURED_MIN_WIDTH; for (Entry<Integer, String> entry : entrySet) { String mediaQueryName = entry.getValue(); int upperBound = entry.getKey(); mediaQueries.add(getNewMediaQuery(mediaQueryName, lowerBound, upperBound)); lowerBound = upperBound + 1; } if (getLogger().isDebugEnabled()) { getLogger().debug("generated " + mediaQueries.size() + " media queries"); for (MediaQuery mediaQuery : mediaQueries) { getLogger().debug(" " + mediaQuery); } } return mediaQueries; } public static Collection<MediaQuery> getMediaQueries(String propertyFilePath) { Properties mediaQueryProperties = ConfigurationUtil.loadProperties(propertyFilePath); return getMediaQueries(mediaQueryProperties); } public static MediaQueryInstance getNewMediaQuery(String mediaQueryName, int lowerBound, int upperBound) { if (lowerBound < CONFIGURED_MIN_WIDTH) { throw new GaleniumException("MediaQuery: illegally low lower bound for '" + mediaQueryName + "': " + lowerBound + " < " + CONFIGURED_MIN_WIDTH); } if (upperBound < CONFIGURED_MIN_WIDTH) { throw new GaleniumException("MediaQuery: illegally low upper bound for '" + mediaQueryName + "': " + upperBound + " < " + CONFIGURED_MIN_WIDTH); } if (upperBound > CONFIGURED_MAX_WIDTH) { throw new GaleniumException("MediaQuery: illegally high upper bound for '" + mediaQueryName + "': " + upperBound + " > " + CONFIGURED_MAX_WIDTH); } if (lowerBound > upperBound) { throw new GaleniumException("illegal media query lower and upper bound combination for '" + mediaQueryName + "': " + lowerBound + " > " + upperBound); } return new MediaQueryInstance(mediaQueryName, lowerBound, upperBound); } private static Integer getIntegerValue(Entry<Object, Object> entry) { Object value = entry.getValue(); if (value == null) { throw new GaleniumException("value null for '" + entry.getKey() + "'"); } try { return Integer.parseInt(value.toString()); } catch (NumberFormatException ex) { throw new GaleniumException("could not parse to integer: '" + value, ex); } } private static Logger getLogger() { return GaleniumReportUtil.getLogger(); } private static SortedMap<Integer, String> getSortedMediaQueryMap(Properties mediaQueryProperties) { SortedMap<Integer, String> mediaQueryMap = new TreeMap<Integer, String>(); Set<Entry<Object, Object>> mqEntries = mediaQueryProperties.entrySet(); for (Entry<Object, Object> entry : mqEntries) { Integer intValue = getIntegerValue(entry); String mediaQueryName = entry.getKey().toString(); mediaQueryMap.put(intValue, mediaQueryName); } return mediaQueryMap; } private static boolean matchesCurrentTestDevice(MediaQuery mediaQuery) { TestDevice testDevice = GaleniumContext.getTestDevice(); if (testDevice == null) { return false; } Dimension screenSize = testDevice.getScreenSize(); if (screenSize.getWidth() < mediaQuery.getLowerBound()) { return false; } if (screenSize.getWidth() > mediaQuery.getUpperBound()) { return false; } return true; } private static final class MediaQueryInstance implements MediaQuery { private int high; private int low; private String name; public MediaQueryInstance(String mediaQueryName, int lowerBound, int upperBound) { name = mediaQueryName; low = lowerBound; high = upperBound; } @Override public int getLowerBound() { return low; } @Override public String getName() { return name; } @Override public int getUpperBound() { return high; } @Override public String toString() { return name + "(lower: " + low + ", upper: " + high + ")"; } } }
convenience/src/main/java/io/wcm/qa/galenium/mediaquery/MediaQueryUtil.java
/* * #%L * wcm.io * %% * Copyright (C) 2018 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.qa.galenium.mediaquery; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import io.wcm.qa.galenium.device.TestDevice; import io.wcm.qa.galenium.exceptions.GaleniumException; import io.wcm.qa.galenium.reporting.GaleniumReportUtil; import io.wcm.qa.galenium.util.ConfigurationUtil; import io.wcm.qa.galenium.util.GaleniumConfiguration; import io.wcm.qa.galenium.util.GaleniumContext; public final class MediaQueryUtil { private static final MediaQuery DEFAULT_MEDIA_QUERY = getNewMediaQuery("DEFAULT_MQ", MIN_WIDTH, MAX_WIDTH); private static final int MAX_WIDTH = GaleniumConfiguration.getMediaQueryMaximalWidth(); private static final int MIN_WIDTH = GaleniumConfiguration.getMediaQueryMinimalWidth(); private MediaQueryUtil() { // do not instantiate } public static MediaQuery getCurrentMediaQuery() { WebDriver driver = GaleniumContext.getDriver(); if (driver == null) { return DEFAULT_MEDIA_QUERY; } Collection<MediaQuery> mediaQueries = getMediaQueries(); for (MediaQuery mediaQuery : mediaQueries) { if (matchesCurrentTestDevice(mediaQuery)) { return mediaQuery; } } return DEFAULT_MEDIA_QUERY; } public static Collection<MediaQuery> getMediaQueries() { String propertiesFilePath = GaleniumConfiguration.getMediaQueryPropertiesPath(); if (StringUtils.isBlank(propertiesFilePath)) { throw new GaleniumException("path to media query properties is empty"); } return getMediaQueries(propertiesFilePath); } public static Collection<MediaQuery> getMediaQueries(File mediaQueryPropertyFile) { if (mediaQueryPropertyFile == null) { throw new GaleniumException("media query properties file is null."); } if (!mediaQueryPropertyFile.isFile()) { throw new GaleniumException("media query properties file is not a file."); } return getMediaQueries(mediaQueryPropertyFile.getPath()); } public static Collection<MediaQuery> getMediaQueries(Properties mediaQueryProperties) { Collection<MediaQuery> mediaQueries = new ArrayList<MediaQuery>(); SortedMap<Integer, String> sortedMediaQueryMap = getSortedMediaQueryMap(mediaQueryProperties); Set<Entry<Integer, String>> entrySet = sortedMediaQueryMap.entrySet(); int lowerBound = MIN_WIDTH; for (Entry<Integer, String> entry : entrySet) { String mediaQueryName = entry.getValue(); int upperBound = entry.getKey(); mediaQueries.add(getNewMediaQuery(mediaQueryName, lowerBound, upperBound)); lowerBound = upperBound + 1; } if (getLogger().isDebugEnabled()) { getLogger().debug("generated " + mediaQueries.size() + " media queries"); for (MediaQuery mediaQuery : mediaQueries) { getLogger().debug(" " + mediaQuery); } } return mediaQueries; } public static Collection<MediaQuery> getMediaQueries(String propertyFilePath) { Properties mediaQueryProperties = ConfigurationUtil.loadProperties(propertyFilePath); return getMediaQueries(mediaQueryProperties); } public static MediaQueryInstance getNewMediaQuery(String mediaQueryName, int lowerBound, int upperBound) { if (lowerBound < MIN_WIDTH) { throw new GaleniumException("MediaQuery: illegally low lower bound for '" + mediaQueryName + "': " + lowerBound + " < " + MIN_WIDTH); } if (upperBound < MIN_WIDTH) { throw new GaleniumException("MediaQuery: illegally low upper bound for '" + mediaQueryName + "': " + upperBound + " < " + MIN_WIDTH); } if (upperBound > MAX_WIDTH) { throw new GaleniumException("MediaQuery: illegally high upper bound for '" + mediaQueryName + "': " + upperBound + " > " + MAX_WIDTH); } if (lowerBound > upperBound) { throw new GaleniumException("illegal media query lower and upper bound combination for '" + mediaQueryName + "': " + lowerBound + " > " + upperBound); } return new MediaQueryInstance(mediaQueryName, lowerBound, upperBound); } private static Integer getIntegerValue(Entry<Object, Object> entry) { Object value = entry.getValue(); if (value == null) { throw new GaleniumException("value null for '" + entry.getKey() + "'"); } try { return Integer.parseInt(value.toString()); } catch (NumberFormatException ex) { throw new GaleniumException("could not parse to integer: '" + value, ex); } } private static Logger getLogger() { return GaleniumReportUtil.getLogger(); } private static SortedMap<Integer, String> getSortedMediaQueryMap(Properties mediaQueryProperties) { SortedMap<Integer, String> mediaQueryMap = new TreeMap<Integer, String>(); Set<Entry<Object, Object>> mqEntries = mediaQueryProperties.entrySet(); for (Entry<Object, Object> entry : mqEntries) { Integer intValue = getIntegerValue(entry); String mediaQueryName = entry.getKey().toString(); mediaQueryMap.put(intValue, mediaQueryName); } return mediaQueryMap; } private static boolean matchesCurrentTestDevice(MediaQuery mediaQuery) { TestDevice testDevice = GaleniumContext.getTestDevice(); if (testDevice == null) { return false; } Dimension screenSize = testDevice.getScreenSize(); if (screenSize.getWidth() < mediaQuery.getLowerBound()) { return false; } if (screenSize.getWidth() > mediaQuery.getUpperBound()) { return false; } return true; } private static final class MediaQueryInstance implements MediaQuery { private int high; private int low; private String name; public MediaQueryInstance(String mediaQueryName, int lowerBound, int upperBound) { name = mediaQueryName; low = lowerBound; high = upperBound; } @Override public int getLowerBound() { return low; } @Override public String getName() { return name; } @Override public int getUpperBound() { return high; } @Override public String toString() { return name + "(lower: " + low + ", upper: " + high + ")"; } } }
fix compile error, better naming
convenience/src/main/java/io/wcm/qa/galenium/mediaquery/MediaQueryUtil.java
fix compile error, better naming
<ide><path>onvenience/src/main/java/io/wcm/qa/galenium/mediaquery/MediaQueryUtil.java <ide> <ide> public final class MediaQueryUtil { <ide> <del> private static final MediaQuery DEFAULT_MEDIA_QUERY = getNewMediaQuery("DEFAULT_MQ", MIN_WIDTH, MAX_WIDTH); <del> private static final int MAX_WIDTH = GaleniumConfiguration.getMediaQueryMaximalWidth(); <del> private static final int MIN_WIDTH = GaleniumConfiguration.getMediaQueryMinimalWidth(); <add> private static final int CONFIGURED_MAX_WIDTH = GaleniumConfiguration.getMediaQueryMaximalWidth(); <add> private static final int CONFIGURED_MIN_WIDTH = GaleniumConfiguration.getMediaQueryMinimalWidth(); <add> private static final MediaQuery DEFAULT_MEDIA_QUERY = getNewMediaQuery("DEFAULT_MQ", CONFIGURED_MIN_WIDTH, CONFIGURED_MAX_WIDTH); <ide> <ide> private MediaQueryUtil() { <ide> // do not instantiate <ide> Collection<MediaQuery> mediaQueries = new ArrayList<MediaQuery>(); <ide> SortedMap<Integer, String> sortedMediaQueryMap = getSortedMediaQueryMap(mediaQueryProperties); <ide> Set<Entry<Integer, String>> entrySet = sortedMediaQueryMap.entrySet(); <del> int lowerBound = MIN_WIDTH; <add> int lowerBound = CONFIGURED_MIN_WIDTH; <ide> for (Entry<Integer, String> entry : entrySet) { <ide> String mediaQueryName = entry.getValue(); <ide> int upperBound = entry.getKey(); <ide> } <ide> <ide> public static MediaQueryInstance getNewMediaQuery(String mediaQueryName, int lowerBound, int upperBound) { <del> if (lowerBound < MIN_WIDTH) { <del> throw new GaleniumException("MediaQuery: illegally low lower bound for '" + mediaQueryName + "': " + lowerBound + " < " + MIN_WIDTH); <del> } <del> if (upperBound < MIN_WIDTH) { <del> throw new GaleniumException("MediaQuery: illegally low upper bound for '" + mediaQueryName + "': " + upperBound + " < " + MIN_WIDTH); <del> } <del> if (upperBound > MAX_WIDTH) { <del> throw new GaleniumException("MediaQuery: illegally high upper bound for '" + mediaQueryName + "': " + upperBound + " > " + MAX_WIDTH); <add> if (lowerBound < CONFIGURED_MIN_WIDTH) { <add> throw new GaleniumException("MediaQuery: illegally low lower bound for '" + mediaQueryName + "': " + lowerBound + " < " + CONFIGURED_MIN_WIDTH); <add> } <add> if (upperBound < CONFIGURED_MIN_WIDTH) { <add> throw new GaleniumException("MediaQuery: illegally low upper bound for '" + mediaQueryName + "': " + upperBound + " < " + CONFIGURED_MIN_WIDTH); <add> } <add> if (upperBound > CONFIGURED_MAX_WIDTH) { <add> throw new GaleniumException("MediaQuery: illegally high upper bound for '" + mediaQueryName + "': " + upperBound + " > " + CONFIGURED_MAX_WIDTH); <ide> } <ide> if (lowerBound > upperBound) { <ide> throw new GaleniumException("illegal media query lower and upper bound combination for '" + mediaQueryName + "': " + lowerBound + " > " + upperBound);
Java
apache-2.0
2c7a80af4b48d3143670aebaaf8c951664d7de6f
0
mureinik/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang,mureinik/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang,mureinik/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * Defines an object that allows mutable access to a value. * <p> * <code>Mutable</code> is used as a generic interface to the implementations * in this package. * <p> * A typical use case would be to enable a primitive or string to be passed * to a method and allow that method to effectively change the value of the * primitive/string. Another use case is to store a frequently changing * primitive in a collection (for example a total in a map) without needing * to create new Integer/Long wrapper objects. * * @author Matthew Hawthorne * @since 2.1 * @version $Id: Mutable.java,v 1.2 2004/07/05 22:12:22 scolebourne Exp $ */ public interface Mutable { /** * Gets the value of this mutable. * * @return the stored value */ Object getValue(); /** * Sets the value of this mutable. * * @param value the value to store * @throws NullPointerException if the object is null and null is invalid * @throws ClassCastException if the type is invalid */ void setValue(Object value); }
src/java/org/apache/commons/lang/mutable/Mutable.java
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * A mutable object. * * @author Matthew Hawthorne * @since 2.1 * @version $Id: Mutable.java,v 1.1 2004/06/11 02:26:32 matth Exp $ */ public interface Mutable { /** * Sets the value of this object. * * @param value the value of this object. */ public void setValue(Object value); /** * Gets the value of this object. * * @return a value. */ public Object getValue(); }
Improve javadocs git-svn-id: d201ecbade8cc7da50e7bffa1d709f7a0d92be7d@137869 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/lang/mutable/Mutable.java
Improve javadocs
<ide><path>rc/java/org/apache/commons/lang/mutable/Mutable.java <ide> package org.apache.commons.lang.mutable; <ide> <ide> /** <del> * A mutable object. <add> * Defines an object that allows mutable access to a value. <add> * <p> <add> * <code>Mutable</code> is used as a generic interface to the implementations <add> * in this package. <add> * <p> <add> * A typical use case would be to enable a primitive or string to be passed <add> * to a method and allow that method to effectively change the value of the <add> * primitive/string. Another use case is to store a frequently changing <add> * primitive in a collection (for example a total in a map) without needing <add> * to create new Integer/Long wrapper objects. <ide> * <ide> * @author Matthew Hawthorne <ide> * @since 2.1 <del> * @version $Id: Mutable.java,v 1.1 2004/06/11 02:26:32 matth Exp $ <add> * @version $Id: Mutable.java,v 1.2 2004/07/05 22:12:22 scolebourne Exp $ <ide> */ <ide> public interface Mutable { <ide> <ide> /** <del> * Sets the value of this object. <add> * Gets the value of this mutable. <ide> * <del> * @param value the value of this object. <add> * @return the stored value <ide> */ <del> public void setValue(Object value); <add> Object getValue(); <ide> <ide> /** <del> * Gets the value of this object. <add> * Sets the value of this mutable. <ide> * <del> * @return a value. <add> * @param value the value to store <add> * @throws NullPointerException if the object is null and null is invalid <add> * @throws ClassCastException if the type is invalid <ide> */ <del> public Object getValue(); <add> void setValue(Object value); <ide> <ide> }
Java
mit
26e2e1d003cc5f3f8cf813169dc85cb2ad1b064a
0
DemigodsRPG/Demigods3
package com.censoredsoftware.Demigods.Engine; import java.util.ArrayDeque; import java.util.Deque; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.conversations.ConversationFactory; import org.bukkit.plugin.Plugin; import com.censoredsoftware.Demigods.DemigodsPlugin; import com.censoredsoftware.Demigods.Engine.Command.DevelopmentCommands; import com.censoredsoftware.Demigods.Engine.Command.GeneralCommands; import com.censoredsoftware.Demigods.Engine.Command.MainCommand; import com.censoredsoftware.Demigods.Engine.Conversation.Conversation; import com.censoredsoftware.Demigods.Engine.Exceptions.DemigodsStartupException; import com.censoredsoftware.Demigods.Engine.Listener.StructureListener; import com.censoredsoftware.Demigods.Engine.Module.ConfigModule; import com.censoredsoftware.Demigods.Engine.Module.MessageModule; import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability; import com.censoredsoftware.Demigods.Engine.Object.Conversation.ConversationInfo; import com.censoredsoftware.Demigods.Engine.Object.Deity.Deity; import com.censoredsoftware.Demigods.Engine.Object.General.DemigodsCommand; import com.censoredsoftware.Demigods.Engine.Object.Language.Translation; import com.censoredsoftware.Demigods.Engine.Object.Structure.Structure; import com.censoredsoftware.Demigods.Engine.Object.Task.Task; import com.censoredsoftware.Demigods.Engine.Object.Task.TaskSet; import com.censoredsoftware.Demigods.Engine.Utility.DataUtility; import com.censoredsoftware.Demigods.Engine.Utility.SchedulerUtility; import com.censoredsoftware.Demigods.Engine.Utility.TextUtility; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class Demigods { // Public Static Access public static DemigodsPlugin plugin; public static ConversationFactory conversation; // Public Modules public static ConfigModule config; public static MessageModule message; // Public Dependency Plugins public static WorldGuardPlugin worldguard; // The Game Data protected static Deque<Deity> deities; protected static Deque<TaskSet> quests; protected static Deque<Structure> structures; protected static Deque<ConversationInfo> conversasions; // The Engine Default Text public static Translation text; public interface ListedDeity { public Deity getDeity(); } public interface ListedTaskSet { public TaskSet getTaskSet(); } public interface ListedStructure { public Structure getStructure(); } public interface ListedConversation { public ConversationInfo getConversation(); } public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation[] conversations) throws DemigodsStartupException { // Allow static access. plugin = instance; conversation = new ConversationFactory(instance); // Setup public modules. config = new ConfigModule(instance, true); message = new MessageModule(instance, config.getSettingBoolean("misc.tag_messages")); // Define the game data. Demigods.deities = new ArrayDeque<Deity>() { { for(ListedDeity deity : deities) add(deity.getDeity()); } }; Demigods.quests = new ArrayDeque<TaskSet>() { { for(ListedTaskSet taskSet : taskSets) add(taskSet.getTaskSet()); } }; Demigods.structures = new ArrayDeque<Structure>() { { for(ListedStructure structure : structures) add(structure.getStructure()); } }; Demigods.conversasions = new ArrayDeque<ConversationInfo>() { { for(Conversation conversation : Conversation.values()) add(conversation.getConversation()); if(conversations != null) for(ListedConversation conversation : conversations) add(conversation.getConversation()); } }; Demigods.text = getTranslation(); // Initialize soft data. new DataUtility(); if(!DataUtility.isConnected()) { message.severe("Demigods was unable to connect to a Redis server."); message.severe("A Redis server is required for Demigods to run."); message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")"); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } // Initialize metrics. try { // (new Metrics(instance)).start(); } catch(Exception ignored) {} // Finish loading the plugin based on the game data. loadDepends(instance); loadListeners(instance); loadCommands(); // Finally, regenerate structures Structure.regenerateStructures(); // Start game threads. SchedulerUtility.startThreads(instance); if(runningSpigot()) message.info(("Spigot found, will use extra API features.")); } /** * Get the translation involved. * * @return The translation. */ public Translation getTranslation() { // Default to EnglishCharNames return new TextUtility.English(); } protected static void loadListeners(DemigodsPlugin instance) { // Engine // instance.getServer().getPluginManager().registerEvents(new BattleListener(), instance); // instance.getServer().getPluginManager().registerEvents(new CommandListener(), instance); // instance.getServer().getPluginManager().registerEvents(new EntityListener(), instance); // instance.getServer().getPluginManager().registerEvents(new GriefListener(), instance); // instance.getServer().getPluginManager().registerEvents(new InventoryListener(), instance); // instance.getServer().getPluginManager().registerEvents(new PlayerListener(), instance); instance.getServer().getPluginManager().registerEvents(new StructureListener(), instance); // instance.getServer().getPluginManager().registerEvents(new TributeListener(), instance); // Deities for(Deity deity : getLoadedDeities()) { if(deity.getAbilities() == null) continue; for(Ability ability : deity.getAbilities()) { // if(ability.getListener() != null) instance.getServer().getPluginManager().registerEvents(ability.getListener(), instance); } } // Tasks for(TaskSet quest : getLoadedQuests()) { if(quest.getTasks() == null) continue; for(Task task : quest.getTasks()) { // if(task.getListener() != null) instance.getServer().getPluginManager().registerEvents(task.getListener(), instance); } } // Structures for(Structure structure : getLoadedStructures()) { if(structure.getUniqueListener() == null) continue; // instance.getServer().getPluginManager().registerEvents(structure.getUniqueListener(), instance); } // Conversations for(ConversationInfo conversation : getLoadedConversations()) { if(conversation.getUniqueListener() == null) continue; // instance.getServer().getPluginManager().registerEvents(conversation.getUniqueListener(), instance); } } protected static void loadCommands() { DemigodsCommand.registerCommand(new MainCommand()); DemigodsCommand.registerCommand(new GeneralCommands()); DemigodsCommand.registerCommand(new DevelopmentCommands()); } protected static void loadDepends(DemigodsPlugin instance) { // WorldGuard Plugin depend = instance.getServer().getPluginManager().getPlugin("WorldGuard"); if(depend instanceof WorldGuardPlugin) worldguard = (WorldGuardPlugin) depend; } public static Deque<Deity> getLoadedDeities() { return Demigods.deities; } public static Deque<TaskSet> getLoadedQuests() { return Demigods.quests; } public static Deque<Structure> getLoadedStructures() { return Demigods.structures; } public static Deque<ConversationInfo> getLoadedConversations() { return Demigods.conversasions; } public static boolean runningSpigot() { try { Bukkit.getServer().getWorlds().get(0).spigot(); return true; } catch(NoSuchMethodError ignored) {} return false; } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
src/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java
package com.censoredsoftware.Demigods.Engine; import java.util.ArrayDeque; import java.util.Deque; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.conversations.ConversationFactory; import org.bukkit.plugin.Plugin; import com.censoredsoftware.Demigods.DemigodsPlugin; import com.censoredsoftware.Demigods.Engine.Command.DevelopmentCommands; import com.censoredsoftware.Demigods.Engine.Command.GeneralCommands; import com.censoredsoftware.Demigods.Engine.Command.MainCommand; import com.censoredsoftware.Demigods.Engine.Conversation.Conversation; import com.censoredsoftware.Demigods.Engine.Exceptions.DemigodsStartupException; import com.censoredsoftware.Demigods.Engine.Listener.GriefListener; import com.censoredsoftware.Demigods.Engine.Listener.StructureListener; import com.censoredsoftware.Demigods.Engine.Module.ConfigModule; import com.censoredsoftware.Demigods.Engine.Module.MessageModule; import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability; import com.censoredsoftware.Demigods.Engine.Object.Conversation.ConversationInfo; import com.censoredsoftware.Demigods.Engine.Object.Deity.Deity; import com.censoredsoftware.Demigods.Engine.Object.General.DemigodsCommand; import com.censoredsoftware.Demigods.Engine.Object.Language.Translation; import com.censoredsoftware.Demigods.Engine.Object.Structure.Structure; import com.censoredsoftware.Demigods.Engine.Object.Task.Task; import com.censoredsoftware.Demigods.Engine.Object.Task.TaskSet; import com.censoredsoftware.Demigods.Engine.Utility.DataUtility; import com.censoredsoftware.Demigods.Engine.Utility.SchedulerUtility; import com.censoredsoftware.Demigods.Engine.Utility.TextUtility; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class Demigods { // Public Static Access public static DemigodsPlugin plugin; public static ConversationFactory conversation; // Public Modules public static ConfigModule config; public static MessageModule message; // Public Dependency Plugins public static WorldGuardPlugin worldguard; // The Game Data protected static Deque<Deity> deities; protected static Deque<TaskSet> quests; protected static Deque<Structure> structures; protected static Deque<ConversationInfo> conversasions; // The Engine Default Text public static Translation text; public interface ListedDeity { public Deity getDeity(); } public interface ListedTaskSet { public TaskSet getTaskSet(); } public interface ListedStructure { public Structure getStructure(); } public interface ListedConversation { public ConversationInfo getConversation(); } public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation[] conversations) throws DemigodsStartupException { // Allow static access. plugin = instance; conversation = new ConversationFactory(instance); // Setup public modules. config = new ConfigModule(instance, true); message = new MessageModule(instance, config.getSettingBoolean("misc.tag_messages")); // Define the game data. Demigods.deities = new ArrayDeque<Deity>() { { for(ListedDeity deity : deities) add(deity.getDeity()); } }; Demigods.quests = new ArrayDeque<TaskSet>() { { for(ListedTaskSet taskSet : taskSets) add(taskSet.getTaskSet()); } }; Demigods.structures = new ArrayDeque<Structure>() { { for(ListedStructure structure : structures) add(structure.getStructure()); } }; Demigods.conversasions = new ArrayDeque<ConversationInfo>() { { for(Conversation conversation : Conversation.values()) add(conversation.getConversation()); if(conversations != null) for(ListedConversation conversation : conversations) add(conversation.getConversation()); } }; Demigods.text = getTranslation(); // Initialize soft data. new DataUtility(); if(!DataUtility.isConnected()) { message.severe("Demigods was unable to connect to a Redis server."); message.severe("A Redis server is required for Demigods to run."); message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")"); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } // Initialize metrics. try { // (new Metrics(instance)).start(); } catch(Exception ignored) {} // Finish loading the plugin based on the game data. loadDepends(instance); loadListeners(instance); loadCommands(); // Finally, regenerate structures Structure.regenerateStructures(); // Start game threads. SchedulerUtility.startThreads(instance); if(runningSpigot()) message.info(("Spigot found, will use extra API features.")); } /** * Get the translation involved. * * @return The translation. */ public Translation getTranslation() { // Default to EnglishCharNames return new TextUtility.English(); } protected static void loadListeners(DemigodsPlugin instance) { // Engine // instance.getServer().getPluginManager().registerEvents(new BattleListener(), instance); // instance.getServer().getPluginManager().registerEvents(new CommandListener(), instance); // instance.getServer().getPluginManager().registerEvents(new EntityListener(), instance); instance.getServer().getPluginManager().registerEvents(new GriefListener(), instance); // instance.getServer().getPluginManager().registerEvents(new InventoryListener(), instance); // instance.getServer().getPluginManager().registerEvents(new PlayerListener(), instance); instance.getServer().getPluginManager().registerEvents(new StructureListener(), instance); // instance.getServer().getPluginManager().registerEvents(new TributeListener(), instance); // Deities for(Deity deity : getLoadedDeities()) { if(deity.getAbilities() == null) continue; for(Ability ability : deity.getAbilities()) { // if(ability.getListener() != null) instance.getServer().getPluginManager().registerEvents(ability.getListener(), instance); } } // Tasks for(TaskSet quest : getLoadedQuests()) { if(quest.getTasks() == null) continue; for(Task task : quest.getTasks()) { // if(task.getListener() != null) instance.getServer().getPluginManager().registerEvents(task.getListener(), instance); } } // Structures for(Structure structure : getLoadedStructures()) { if(structure.getUniqueListener() == null) continue; // instance.getServer().getPluginManager().registerEvents(structure.getUniqueListener(), instance); } // Conversations for(ConversationInfo conversation : getLoadedConversations()) { if(conversation.getUniqueListener() == null) continue; // instance.getServer().getPluginManager().registerEvents(conversation.getUniqueListener(), instance); } } protected static void loadCommands() { DemigodsCommand.registerCommand(new MainCommand()); DemigodsCommand.registerCommand(new GeneralCommands()); DemigodsCommand.registerCommand(new DevelopmentCommands()); } protected static void loadDepends(DemigodsPlugin instance) { // WorldGuard Plugin depend = instance.getServer().getPluginManager().getPlugin("WorldGuard"); if(depend instanceof WorldGuardPlugin) worldguard = (WorldGuardPlugin) depend; } public static Deque<Deity> getLoadedDeities() { return Demigods.deities; } public static Deque<TaskSet> getLoadedQuests() { return Demigods.quests; } public static Deque<Structure> getLoadedStructures() { return Demigods.structures; } public static Deque<ConversationInfo> getLoadedConversations() { return Demigods.conversasions; } public static boolean runningSpigot() { try { Bukkit.getServer().getWorlds().get(0).spigot(); return true; } catch(NoSuchMethodError ignored) {} return false; } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
Pinpoint lag.
src/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java
Pinpoint lag.
<ide><path>rc/main/java/com/censoredsoftware/Demigods/Engine/Demigods.java <ide> import com.censoredsoftware.Demigods.Engine.Command.MainCommand; <ide> import com.censoredsoftware.Demigods.Engine.Conversation.Conversation; <ide> import com.censoredsoftware.Demigods.Engine.Exceptions.DemigodsStartupException; <del>import com.censoredsoftware.Demigods.Engine.Listener.GriefListener; <ide> import com.censoredsoftware.Demigods.Engine.Listener.StructureListener; <ide> import com.censoredsoftware.Demigods.Engine.Module.ConfigModule; <ide> import com.censoredsoftware.Demigods.Engine.Module.MessageModule; <ide> // instance.getServer().getPluginManager().registerEvents(new BattleListener(), instance); <ide> // instance.getServer().getPluginManager().registerEvents(new CommandListener(), instance); <ide> // instance.getServer().getPluginManager().registerEvents(new EntityListener(), instance); <del> instance.getServer().getPluginManager().registerEvents(new GriefListener(), instance); <add> // instance.getServer().getPluginManager().registerEvents(new GriefListener(), instance); <ide> // instance.getServer().getPluginManager().registerEvents(new InventoryListener(), instance); <ide> // instance.getServer().getPluginManager().registerEvents(new PlayerListener(), instance); <ide> instance.getServer().getPluginManager().registerEvents(new StructureListener(), instance);
Java
apache-2.0
90bb62013e05f0b062d90788fe8ac05c021aa589
0
palessandro/activejdbc,javalite/activejdbc,palessandro/activejdbc,javalite/activejdbc,javalite/activejdbc,javalite/activejdbc,palessandro/activejdbc
/* Copyright 2009-2015 Igor Polevoy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javalite.activejdbc; import org.javalite.activejdbc.annotations.CompositePK; import org.javalite.activejdbc.associations.*; import org.javalite.activejdbc.cache.QueryCache; import org.javalite.activejdbc.conversion.BlankToNullConverter; import org.javalite.activejdbc.conversion.Converter; import org.javalite.activejdbc.conversion.ZeroToNullConverter; import org.javalite.activejdbc.dialects.Dialect; import org.javalite.activejdbc.validation.NumericValidationBuilder; import org.javalite.activejdbc.validation.ValidationBuilder; import org.javalite.activejdbc.validation.ValidationException; import org.javalite.activejdbc.validation.Validator; import org.javalite.common.Convert; import org.javalite.common.Escape; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.*; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.util.*; import static org.javalite.common.Inflector.*; import static org.javalite.common.Util.blank; import static org.javalite.common.Util.empty; import static org.javalite.common.Util.join; /** * This class is a super class of all "models" and provides most functionality * necessary for implementation of Active Record pattern. * * @author Igor Polevoy * @author Eric Nielsen */ public abstract class Model extends CallbackSupport implements Externalizable { private final static Logger logger = LoggerFactory.getLogger(Model.class); private Map<String, Object> attributes = new CaseInsensitiveMap<Object>(); private final Set<String> dirtyAttributeNames = new CaseInsensitiveSet(); private boolean frozen = false; private MetaModel metaModelLocal; private ModelRegistry modelRegistryLocal; private final Map<Class, Model> cachedParents = new HashMap<Class, Model>(); private final Map<Class, List<Model>> cachedChildren = new HashMap<Class, List<Model>>(); private boolean manageTime = true; private boolean compositeKeyPersisted = false; private Errors errors = new Errors(); protected Model() { } private void fireAfterLoad() { afterLoad(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterLoad(this); } } private void fireBeforeSave() { beforeSave(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeSave(this); } } private void fireAfterSave() { afterSave(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterSave(this); } } private void fireBeforeCreate() { beforeCreate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeCreate(this); } } private void fireAfterCreate() { afterCreate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterCreate(this); } } private void fireBeforeUpdate() { beforeUpdate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeUpdate(this); } } private void fireAfterUpdate() { afterUpdate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterUpdate(this); } } private void fireBeforeDelete() { beforeDelete(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeDelete(this); } } private void fireAfterDelete() { afterDelete(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterDelete(this); } } private void fireBeforeValidation() { beforeValidation(); for(CallbackListener callback: modelRegistryLocal().callbacks()) callback.beforeValidation(this); } private void fireAfterValidation() { afterValidation(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterValidation(this); } } public static MetaModel getMetaModel() { return ModelDelegate.metaModelOf(modelClass()); } protected Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } protected Set<String> dirtyAttributeNames() { return Collections.unmodifiableSet(dirtyAttributeNames); } /** * Overrides attribute values from input map. The input map may have attributes whose name do not match the * attribute names (columns) of this model. Such attributes will be ignored. Those values whose names are * not present in the argument map, will stay untouched. The input map may have only partial list of attributes. * * @param input map with attributes to overwrite this models'. Keys are names of attributes of this model, values * are new values for it. */ public <T extends Model> T fromMap(Map input) { hydrate(input, false); dirtyAttributeNames.addAll(input.keySet()); return (T) this; } /** * Hydrates a this instance of model from a map. Only picks values from a map that match * this instance's attribute names, while ignoring the others. * * @param attributesMap map containing values for this instance. */ protected void hydrate(Map<String, Object> attributesMap, boolean fireAfterLoad) { Set<String> attributeNames = getMetaModelLocal().getAttributeNames(); for (Map.Entry<String, Object> entry : attributesMap.entrySet()) { if (attributeNames.contains(entry.getKey())) { if (entry.getValue() instanceof Clob && getMetaModelLocal().cached()) { this.attributes.put(entry.getKey(), Convert.toString(entry.getValue())); } else { this.attributes.put(entry.getKey(), getMetaModelLocal().getDialect().overrideDriverTypeConversion( getMetaModelLocal(), entry.getKey(), entry.getValue())); } } } if (getCompositeKeys() != null){ compositeKeyPersisted = true; } if(fireAfterLoad){ fireAfterLoad(); } } /** * Convenience method, sets ID value on this model, equivalent to <code>set(getIdName(), id)</code>. * * @param id value of ID * @return reference to self for chaining. */ public <T extends Model> T setId(Object id) { return set(getIdName(), id); } /** * Sets attribute value as <code>java.sql.Date</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Date</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toSqlDate(Object)}. * * @param attributeName name of attribute. * @param value value to convert. * @return reference to this model. */ public <T extends Model> T setDate(String attributeName, Object value) { Converter<Object, java.sql.Date> converter = modelRegistryLocal().converterForValue( attributeName, value, java.sql.Date.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toSqlDate(value)); } /** * Gets attribute value as <code>java.sql.Date</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Date</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toSqlDate(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>java.sql.Date</code> */ public java.sql.Date getDate(String attributeName) { Object value = getRaw(attributeName); Converter<Object, java.sql.Date> converter = modelRegistryLocal().converterForValue( attributeName, value, java.sql.Date.class); return converter != null ? converter.convert(value) : Convert.toSqlDate(value); } /** * Performs a primitive conversion of <code>java.util.Date</code> to <code>java.sql.Timestamp</code> * based on the time value. * * @param name name of field. * @param date date value. * @deprecated use {@link #setTimestamp(String, Object)} instead. */ @Deprecated public void setTS(String name, java.util.Date date) { if(date == null) { set(name, null); } else { set(name, new java.sql.Timestamp(date.getTime())); } } /** * Sets values for this model instance. The sequence of values must correspond to sequence of names. * * @param attributeNames names of attributes. * @param values values for this instance. */ public void set(String[] attributeNames, Object[] values) { if (attributeNames == null || values == null || attributeNames.length != values.length) { throw new IllegalArgumentException("must pass non-null arrays of equal length"); } for (int i = 0; i < attributeNames.length; i++) { set(attributeNames[i], values[i]); } } /** * Sets a value of an attribute. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Object</code>, given the value is an instance of <code>S</code>, then it will be used and the * converted value will be set. * * @param attributeName name of attribute to set. Names not related to this model will be rejected (those not matching table columns). * @param value value of attribute. Feel free to set any type, as long as it can be accepted by your driver. * @return reference to self, so you can string these methods one after another. */ public <T extends Model> T set(String attributeName, Object value) { Converter<Object, Object> converter = modelRegistryLocal().converterForValue(attributeName, value, Object.class); return setRaw(attributeName, converter != null ? converter.convert(value) : value); } /** * Sets raw value of an attribute, without applying conversions. */ private <T extends Model> T setRaw(String attributeName, Object value) { if (manageTime && attributeName.equalsIgnoreCase("created_at")) { throw new IllegalArgumentException("cannot set 'created_at'"); } getMetaModelLocal().checkAttributeOrAssociation(attributeName); attributes.put(attributeName, value); dirtyAttributeNames.add(attributeName); return (T) this; } /** * Will return true if any attribute of this instance was changed after latest load/save. * (Instance state differs from state in DB) * @return true if this instance was modified. */ public boolean isModified() { return !dirtyAttributeNames.isEmpty(); } /** * Will return true if this instance is frozen, false otherwise. * A frozen instance cannot use used, as it has no relation to a record in table. * * @return true if this instance is frozen, false otherwise. */ public boolean isFrozen(){ return frozen; } /** * Synonym for {@link #isModified()}. * * @return true if this instance was modified. */ public boolean modified() { return isModified(); } /** * Returns names of all attributes from this model. * @return names of all attributes from this model. * @deprecated use {@link #attributeNames()} instead */ @Deprecated public static List<String> attributes(){ return ModelDelegate.attributes(modelClass()); } /** * Returns names of all attributes from this model. * @return names of all attributes from this model. */ public static Set<String> attributeNames() { return ModelDelegate.attributeNames(modelClass()); } /** * Returns all associations of this model. * @return all associations of this model. */ public static List<Association> associations() { return ModelDelegate.associations(modelClass()); } /** * returns true if this is a new instance, not saved yet to DB, false otherwise. * * @return true if this is a new instance, not saved yet to DB, false otherwise */ public boolean isNew(){ return getId() == null && !compositeKeyPersisted; } /** * Synonym for {@link #isFrozen()}. if(m.frozen()) seems to read better than classical Java convention. * * @return true if this instance is frozen, false otherwise. */ public boolean frozen(){ return isFrozen(); } /** * Deletes a single table record represented by this instance. This method assumes that a corresponding table * has only one record whose PK is the ID of this instance. * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. * * @return true if a record was deleted, false if not. */ public boolean delete() { fireBeforeDelete(); int result; if (getCompositeKeys() != null) { String[] compositeKeys = getCompositeKeys(); StringBuilder query = new StringBuilder(); Object[] values = new Object[compositeKeys.length]; for (int i = 0; i < compositeKeys.length; i++) { query.append(i == 0 ? "DELETE FROM " + getMetaModelLocal().getTableName() + " WHERE " : " AND ").append(compositeKeys[i]).append(" = ?"); values[i] = get(compositeKeys[i]); } result = new DB(getMetaModelLocal().getDbName()).exec(query.toString(), values); } else { result = new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + getMetaModelLocal().getTableName() + " WHERE " + getIdName() + "= ?", getId()); } if (1 == result) { frozen = true; if (getMetaModelLocal().cached()) { QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); } ModelDelegate.purgeEdges(getMetaModelLocal()); fireAfterDelete(); return true; } fireAfterDelete(); return false; } /** * Convenience method, will call {@link #delete()} or {@link #deleteCascade()}. * * @param cascade true to call {@link #deleteCascade()}, false to call {@link #delete()}. */ public void delete(boolean cascade){ if(cascade){ deleteCascade(); }else{ delete(); } } /** * Deletes this record from associated table, as well as children. * * Deletes current model and all of its child and many to many associations. This is not a high performance method, as it will * load every row into a model instance before deleting, effectively calling (N + 1) per table queries to the DB, one to select all * the associated records (per table), and one delete statement per record. Use it for small data sets. * * <p/> * In cases of simple one to many and polymorphic associations, things are as expected, a parent is deleted an all children are * deleted as well, but in more complicated cases, this method will walk entire three of associated tables, sometimes * coming back to the same one where it all started. * It will follow associations of children and their associations too; consider this a true cascade delete with all implications * (circular dependencies, referential integrity constraints, potential performance bottlenecks, etc.) * <p/> * * Imagine a situation where you have DOCTORS and PATIENTS in many to many relationship (with DOCTORS_PATIENTS table * as a join table), and in addition PATIENTS and PRESCRIPTIONS in one to many relationship, where a patient might * have many prescriptions: * <pre> DOCTORS +----+------------+-----------+-----------------+ | id | first_name | last_name | discipline | +----+------------+-----------+-----------------+ | 1 | John | Kentor | otolaryngology | | 2 | Hellen | Hunt | dentistry | | 3 | John | Druker | oncology | +----+------------+-----------+-----------------+ PATIENTS +----+------------+-----------+ | id | first_name | last_name | +----+------------+-----------+ | 1 | Jim | Cary | | 2 | John | Carpenter | | 3 | John | Doe | +----+------------+-----------+ DOCTORS_PATIENTS +----+-----------+------------+ | id | doctor_id | patient_id | +----+-----------+------------+ | 1 | 1 | 2 | | 2 | 1 | 1 | | 3 | 2 | 1 | | 4 | 3 | 3 | +----+-----------+------------+ PRESCRIPTIONS +----+------------------------+------------+ | id | name | patient_id | +----+------------------------+------------+ | 1 | Viagra | 1 | | 2 | Prozac | 1 | | 3 | Valium | 2 | | 4 | Marijuana (medicinal) | 2 | | 5 | CML treatment | 3 | +----+------------------------+------------+ * </pre> * * Lets start with a simple example, Doctor John Druker. This doctor has one patient John Doe, and the patient has one prescription. * So, when an instance of this doctor model is issued statement: * <pre> * drDruker.deleteCascade(); * </pre> * , the result is as expected: the DOCTORS:ID=3 is deleted, DOCTORS_PATIENTS:ID=4 is deleted, PATIENTS:ID=3 is deleted * and PRESCRIPTIONS:ID=5 is deleted. * * <p/> * However, when doctor Kentor(#1) is deleted, the following records are also deleted: * <ul> * <li>DOCTORS_PATIENTS:ID=1, 2 - these are links to patients</li> * <li>PATIENTS:ID=1,2 these are patients themselves</li> * <li>PRESCRIPTIONS:ID=1,2,3,4 - these are prescriptions of patients 1 and 2</li> * </ul> * But, in addition, since this is a many to many relationship, deleting patients 1 and 2 results in also deleting * doctor Hellen Hunt(#2), since she is a doctor of patient Jim Cary(#1), deleting all corresponding join links from * table DOCTORS_PATIENTS. So, deleting doctor Kentor, deleted most all records from related tables, leaving only these * records in place: * <ul> * <li>DOCTORS:ID=3</li> * <li>DOCTORS_PATIENTS:ID=4</li> * <li>PATIENTS:ID=3</li> * <li>PRESCRIPTIONS:ID=5</li> * </ul> * Had doctor Hellen Hunt(#2) had more patients, it would delete them too, and so on. This goes a long way to say that it * could be easy to be tangled up in web of associations, so be careful out there. * * <p/> * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. */ public void deleteCascade(){ deleteCascadeExcept(); } /** * This method does everything {@link #deleteCascade()} does, but in addition allows to exclude some associations * from this action. This is necessary because {@link #deleteCascade()} method can be far too eager to delete * records in a database, and this is a good way to tell the model to exclude some associations from deletes. * * <p>Example:</p> * <code> * Patient.findById(3).deleteCascadeExcept(Patient.getMetaModel().getAssociationForTarget("prescriptions")); * </code> * * @see {@link #deleteCascade()} - see for more information. * @param excludedAssociations associations */ public void deleteCascadeExcept(Association ... excludedAssociations){ List<Association> excludedAssociationsList = Arrays.asList(excludedAssociations); deleteMany2ManyDeep(getMetaModelLocal().getManyToManyAssociations(excludedAssociationsList)); deleteChildrenDeep(getMetaModelLocal().getOneToManyAssociations(excludedAssociationsList)); deleteChildrenDeep(getMetaModelLocal().getPolymorphicAssociations(excludedAssociationsList)); delete(); } private void deleteMany2ManyDeep(List<Many2ManyAssociation> many2ManyAssociations){ List<Model> allMany2ManyChildren = new ArrayList<Model>(); for (Association association : many2ManyAssociations) { String targetTableName = association.getTarget(); Class c = Registry.instance().getModelClass(targetTableName, false); if(c == null){// this model is probably not defined as a class, but the table exists! logger.error("ActiveJDBC WARNING: failed to find a model class for: {}, maybe model is not defined for this table?" + " There might be a risk of running into integrity constrain violation if this model is not defined.", targetTableName); } else{ allMany2ManyChildren.addAll(getAll(c)); } } deleteJoinsForManyToMany(); for (Model model : allMany2ManyChildren) { model.deleteCascade(); } } /** * Deletes this record from associated table, as well as its immediate children. This is a high performance method * because it does not walk through a chain of child dependencies like {@link #deleteCascade()} does, but rather issues * one DELETE statement per child dependency table. Also, its semantics are a bit different between than {@link #deleteCascade()}. * It only deletes current record and immediate children, but not their children (no grand kinds are dead as a result :)). * <h4>One to many and polymorphic associations</h4> * The current record is deleted, as well as immediate children. * <h4>Many to many associations</h4> * The current record is deleted, as well as links in a join table. Nothing else is deleted. * <p/> * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. */ public void deleteCascadeShallow(){ deleteJoinsForManyToMany(); deleteOne2ManyChildrenShallow(); deletePolymorphicChildrenShallow(); delete(); } private void deleteJoinsForManyToMany() { List<? extends Association> associations = getMetaModelLocal().getManyToManyAssociations(Collections.<Association>emptyList()); for (Association association : associations) { String join = ((Many2ManyAssociation)association).getJoin(); String sourceFK = ((Many2ManyAssociation)association).getSourceFkName(); new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + join + " WHERE " + sourceFK + " = ?", getId()); } } private void deleteOne2ManyChildrenShallow() { List<OneToManyAssociation> childAssociations = getMetaModelLocal().getOneToManyAssociations(Collections.<Association>emptyList()); for (OneToManyAssociation association : childAssociations) { String target = association.getTarget(); new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + target + " WHERE " + association.getFkName() + " = ?", getId()); } } private void deletePolymorphicChildrenShallow() { List<OneToManyPolymorphicAssociation> polymorphics = getMetaModelLocal().getPolymorphicAssociations(new ArrayList<Association>()); for (OneToManyPolymorphicAssociation association : polymorphics) { String target = association.getTarget(); String parentType = association.getTypeLabel(); new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + target + " WHERE parent_id = ? AND parent_type = ?", getId(), parentType); } } private void deleteChildrenDeep(List<? extends Association> childAssociations){ for (Association association : childAssociations) { String targetTableName = association.getTarget(); Class c = Registry.instance().getModelClass(targetTableName, false); if(c == null){// this model is probably not defined as a class, but the table exists! logger.error("ActiveJDBC WARNING: failed to find a model class for: {}, maybe model is not defined for this table?" + " There might be a risk of running into integrity constrain violation if this model is not defined.", targetTableName); } else{ List<Model> dependencies = getAll(c); for (Model model : dependencies) { model.deleteCascade(); } } } } /** * Deletes some records from associated table. This method does not follow any associations. * If this model has one to many associations, you might end up with either orphan records in child * tables, or run into integrity constraint violations. However, this method if very efficient as it deletes all records * in one shot, without pre-loading them. * This method also has a side-effect: it will not mark loaded instances corresponding to deleted records as "frozen". * This means that such an instance would allow calling save() and saveIt() methods resulting DB errors, as you * would be attempting to update phantom records. * * * @param query narrows which records to delete. Example: <pre>"last_name like '%sen%'"</pre>. * @param params (optional) - list of parameters if a query is parametrized. * @return number of deleted records. */ public static int delete(String query, Object... params) { return ModelDelegate.delete(modelClass(), query, params); } /** * Returns true if record corresponding to the id passed exists in the DB. * * @param id id in question. * @return true if corresponding record exists in DB, false if it does not. */ public static boolean exists(Object id) { return ModelDelegate.exists(modelClass(), id); } /** * Returns true if record corresponding to the id of this instance exists in the DB. * * @return true if corresponding record exists in DB, false if it does not. */ public boolean exists(){ MetaModel metaModel = getMetaModelLocal(); return null != new DB(metaModel.getDbName()).firstCell(metaModel.getDialect().selectExists(metaModel), getId()); } /** * Deletes all records from associated table. This methods does not take associations into account. * * @return number of records deleted. */ public static int deleteAll() { return ModelDelegate.deleteAll(modelClass()); } /** * Updates records associated with this model. * * This example : * <pre> * Employee.update("bonus = ?", "years_at_company > ?", "5", "10"); * </pre * In this example, employees who worked for more than 10 years, get a bonus of 5% (not so generous :)). * * * @param updates - what needs to be updated. * @param conditions specifies which records to update. If this argument is <code>null</code>, all records in table will be updated. * In such cases, use a more explicit {@link #updateAll(String, Object...)} method. * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, * updates first, then conditions. * @return number of updated records. */ public static int update(String updates, String conditions, Object ... params) { return ModelDelegate.update(modelClass(), updates, conditions, params); } /** * Updates all records associated with this model. * * This example : * <pre> * Employee.updateAll("bonus = ?", "10"); * </pre> * In this example, all employees get a bonus of 10%. * * * @param updates - what needs to be updated. * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, * updates first, then conditions. * @return number of updated records. */ public static int updateAll(String updates, Object ... params) { return ModelDelegate.updateAll(modelClass(), updates, params); } /** * Returns all values of the model with all attribute names converted to lower case, * regardless how these names came from DB. This method is a convenience * method for displaying values on web pages. * * <p/> * If {@link LazyList#include(Class[])} method was used, and this * model belongs to a parent (as in many to one relationship), then the parent * will be eagerly loaded and also converted to a map. Parents' maps are keyed in the * returned map by underscored name of a parent model class name. * <p/> * For example, if this model were <code>Address</code> * and a parent is <code>User</code> (and user has many addresses), then the resulting map would * have all the attributes of the current table and another map representing a parent user with a * key "user" in current map. * * @return all values of the model with all attribute names converted to lower case. */ public Map<String, Object> toMap(){ Map<String, Object> retVal = new TreeMap<String, Object>(); for (Map.Entry<String, Object> entry : attributes.entrySet()) { Object v = entry.getValue(); if (v == null) { continue; } if (v instanceof Clob) { retVal.put(entry.getKey().toLowerCase(), Convert.toString(v)); } else { retVal.put(entry.getKey().toLowerCase(), v); } } for(Class parentClass: cachedParents.keySet()){ retVal.put(underscore(parentClass.getSimpleName()), cachedParents.get(parentClass).toMap()); } for(Class childClass: cachedChildren.keySet()){ List<Model> children = cachedChildren.get(childClass); List<Map> childMaps = new ArrayList<Map>(children.size()); for(Model child:children){ childMaps.add(child.toMap()); } retVal.put(tableize(childClass.getSimpleName()), childMaps); } return retVal; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Model: ").append(getClass().getName()) .append(", table: '").append(getMetaModelLocal().getTableName()) .append("', attributes: ").append(attributes); if (cachedParents.size() > 0) { sb.append(", parents: ").append(cachedParents); } if (cachedChildren.size() > 0) { sb.append(", children: ").append(cachedChildren); } return sb.toString(); } /** * Parses XML into a model. It expects the same structure of XML as the method {@link #toXml(int, boolean, String...)}. * It ignores children and dependencies (for now) if any. This method will parse the model attributes * from the XML document, and will then call {@link #fromMap(java.util.Map)} method. It does not save data into a database, just sets the * attributes. * * @param xml xml to read model attributes from. */ public void fromXml(String xml) { try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(xml.getBytes())); String attr = null; String chars = null; Map<Object, Object> res = new HashMap<Object, Object>(); while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: attr = reader.getLocalName(); break; case XMLStreamConstants.CHARACTERS: chars = reader.getText().trim();; break; case XMLStreamConstants.END_ELEMENT: if (attr != null && !blank(chars)) { res.put(attr, chars); } attr = chars = null; break; } } fromMap(res); } catch (XMLStreamException e) { throw new InitException(e); } } /** * Generates a XML document from content of this model. * * @param pretty pretty format (human readable), or one line text. * @param declaration true to include XML declaration at the top * @param attributeNames list of attributes to include. No arguments == include all attributes. * @return generated XML. */ public String toXml(boolean pretty, boolean declaration, String... attributeNames) { StringBuilder sb = new StringBuilder(); if(declaration) { sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (pretty) { sb.append('\n'); } } toXmlP(sb, pretty, "", attributeNames); return sb.toString(); } protected void toXmlP(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { String topTag = underscore(getClass().getSimpleName()); if (pretty) { sb.append(indent); } sb.append('<').append(topTag).append('>'); if (pretty) { sb.append('\n'); } String[] names = !empty(attributeNames) ? attributeNames : attributeNamesLowerCased(); for (String name : names) { if (pretty) { sb.append(" ").append(indent); } sb.append('<').append(name).append('>'); Object v = attributes.get(name); if (v != null) { Escape.xml(sb, Convert.toString(v)); } sb.append("</").append(name).append('>'); if (pretty) { sb.append('\n'); } } for (Class childClass : cachedChildren.keySet()) { if (pretty) { sb.append(" ").append(indent); } String tag = pluralize(underscore(childClass.getSimpleName())); sb.append('<').append(tag).append('>'); if (pretty) { sb.append('\n'); } for (Model child : cachedChildren.get(childClass)) { child.toXmlP(sb, pretty, " " + indent); } if (pretty) { sb.append(" ").append(indent); } sb.append("</").append(tag).append('>'); if (pretty) { sb.append('\n'); } } beforeClosingTag(sb, pretty, pretty ? " " + indent : "", attributeNames); if (pretty) { sb.append(indent); } sb.append("</").append(topTag).append('>'); if (pretty) { sb.append('\n'); } } /** * Generates a XML document from content of this model. * * @param spaces by how many spaces to indent. * @param declaration true to include XML declaration at the top * @param attributeNames list of attributes to include. No arguments == include all attributes. * @return generated XML. * * @deprecated use {@link #toXml(boolean, boolean, String...)} instead */ @Deprecated public String toXml(int spaces, boolean declaration, String... attributeNames) { return toXml(spaces > 0, declaration, attributeNames); } /** * Override in a subclass to inject custom content onto XML just before the closing tag. * * <p>To keep the formatting, it is recommended to implement this method as the example below. * * <blockquote><pre> * if (pretty) { sb.append(ident); } * sb.append("&lt;test&gt;...&lt;/test&gt;"); * if (pretty) { sb.append('\n'); } * </pre></blockquote> * * @param sb to write content to. * @param pretty pretty format (human readable), or one line text. * @param indent indent at current level * @param attributeNames list of attributes to include */ public void beforeClosingTag(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { StringWriter writer = new StringWriter(); beforeClosingTag(indent.length(), writer, attributeNames); sb.append(writer.toString()); } /** * Override in a subclass to inject custom content onto XML just before the closing tag. * * @param spaces number of spaces of indent * @param writer to write content to. * @param attributeNames list of attributes to include * * @deprecated use {@link #beforeClosingTag(StringBuilder, boolean, String, String...)} instead */ @Deprecated public void beforeClosingTag(int spaces, StringWriter writer, String... attributeNames) { // do nothing } /** * Generates a JSON document from content of this model. * * @param pretty pretty format (human readable), or one line text. * @param attributeNames list of attributes to include. No arguments == include all attributes. * @return generated JSON. */ public String toJson(boolean pretty, String... attributeNames) { StringBuilder sb = new StringBuilder(); toJsonP(sb, pretty, "", attributeNames); return sb.toString(); } protected void toJsonP(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { if (pretty) { sb.append(indent); } sb.append('{'); String[] names = !empty(attributeNames) ? attributeNames : attributeNamesLowerCased(); for (int i = 0; i < names.length; i++) { if (i > 0) { sb.append(','); } if (pretty) { sb.append("\n ").append(indent); } String name = names[i]; sb.append('"').append(name).append("\":"); Object v = attributes.get(name); if (v == null) { sb.append("null"); } else if (v instanceof Number || v instanceof Boolean) { sb.append(v); } else if (v instanceof Date) { sb.append('"').append(Convert.toIsoString((Date) v)).append('"'); } else { sb.append('"'); Escape.json(sb, Convert.toString(v)); sb.append('"'); } } if (cachedParents.size() > 0) { sb.append(','); if (pretty) { sb.append("\n ").append(indent); } sb.append("\"parents\":{"); List<Class> parentClasses = new ArrayList<Class>(); parentClasses.addAll(cachedParents.keySet()); for (int i = 0; i < parentClasses.size(); i++) { if (i > 0) { sb.append(','); } Class parentClass = parentClasses.get(i); String name = pluralize(parentClasses.get(i).getSimpleName()).toLowerCase(); if (pretty) { sb.append("\n ").append(indent); } sb.append('"').append(name).append("\":["); Model parent = cachedParents.get(parentClass); if (pretty) { sb.append('\n'); } parent.toJsonP(sb, pretty, (pretty ? " " + indent : "")); if(i < (parentClasses.size() - 1)){ sb.append(','); } if (pretty) { sb.append("\n ").append(indent); } sb.append(']'); } if (pretty) { sb.append("\n ").append(indent); } sb.append('}'); } if (cachedChildren.size() > 0) { sb.append(','); if (pretty) { sb.append("\n ").append(indent); } sb.append("\"children\":{"); List<Class> childClasses = new ArrayList<Class>(); childClasses.addAll(cachedChildren.keySet()); for (int i = 0; i < childClasses.size(); i++) { if (i > 0) { sb.append(','); } Class childClass = childClasses.get(i); String name = pluralize(childClass.getSimpleName()).toLowerCase(); if (pretty) { sb.append("\n ").append(indent); } sb.append('"').append(name).append("\":["); List<Model> child = cachedChildren.get(childClass); for (int j = 0; j < child.size(); j++) { if (j > 0) { sb.append(','); } if (pretty) { sb.append('\n'); } child.get(j).toJsonP(sb, pretty, (pretty ? " " + indent : "")); } if (pretty) { sb.append("\n ").append(indent); } sb.append(']'); } if (pretty) { sb.append("\n ").append(indent); } sb.append('}'); } beforeClosingBrace(sb, pretty, pretty ? " " + indent : "", attributeNames); if (pretty) { sb.append('\n').append(indent); } sb.append('}'); } /** * Override in subclasses in order to inject custom content into Json just before the closing brace. * * <p>To keep the formatting, it is recommended to implement this method as the example below. * * <blockquote><pre> * sb.append(','); * if (pretty) { sb.append('\n').append(indent); } * sb.append("\"test\":\"...\""); * </pre></blockquote> * * @param sb to write custom content to * @param pretty pretty format (human readable), or one line text. * @param indent indent at current level * @param attributeNames list of attributes to include */ public void beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { StringWriter writer = new StringWriter(); beforeClosingBrace(pretty, indent, writer); sb.append(writer.toString()); } /** * Override in subclasses in order to inject custom content into Json just before the closing brace. * * @param pretty pretty format (human readable), or one line text. * @param indent indent at current level * @param writer writer to write custom content to * @deprecated use {@link #beforeClosingBrace(StringBuilder, boolean, String, String...)} instead */ @Deprecated public void beforeClosingBrace(boolean pretty, String indent, StringWriter writer) { // do nothing } private String[] attributeNamesLowerCased() { return ModelDelegate.lowerCased(attributes.keySet()); } /** * Returns parent of this model, assuming that this table represents a child. * This method may return <code>null</code> in cases when you have orphan record and * referential integrity is not enforced in DBMS with a foreign key constraint. * * @param parentClass class of a parent model. * @return instance of a parent of this instance in the "belongs to" relationship. */ public <P extends Model> P parent(Class<P> parentClass) { return parent(parentClass, false); } public <P extends Model> P parent(Class<P> parentClass, boolean cache) { P cachedParent = parentClass.cast(cachedParents.get(parentClass)); if (cachedParent != null) { return cachedParent; } MetaModel parentMM = Registry.instance().getMetaModel(parentClass); String parentTable = parentMM.getTableName(); BelongsToAssociation ass = getMetaModelLocal().getAssociationForTarget(parentTable, BelongsToAssociation.class); BelongsToPolymorphicAssociation assP = getMetaModelLocal().getAssociationForTarget( parentTable, BelongsToPolymorphicAssociation.class); Object fkValue; String fkName; if (ass != null) { fkValue = get(ass.getFkName()); fkName = ass.getFkName(); } else if (assP != null) { fkValue = get("parent_id"); fkName = "parent_id"; if (!assP.getTypeLabel().equals(getString("parent_type"))) { throw new IllegalArgumentException("Wrong parent: '" + parentClass + "'. Actual parent type label of this record is: '" + getString("parent_type") + "'"); } } else { throw new IllegalArgumentException("there is no association with table: " + parentTable); } if (fkValue == null) { logger.debug("Attribute: {} is null, cannot determine parent. Child record: {}", fkName, this); return null; } String parentIdName = parentMM.getIdName(); String query = getMetaModelLocal().getDialect().selectStarParametrized(parentTable, parentIdName); if (parentMM.cached()) { P parent = parentClass.cast(QueryCache.instance().getItem(parentTable, query, new Object[]{fkValue})); if (parent != null) { return parent; } } List<Map> results = new DB(getMetaModelLocal().getDbName()).findAll(query, fkValue); //expect only one result here if (results.isEmpty()) { //this should be covered by referential integrity constraint return null; } else { try { P parent = parentClass.newInstance(); parent.hydrate(results.get(0), true); if (parentMM.cached()) { QueryCache.instance().addItem(parentTable, query, new Object[]{fkValue}, parent); } if (cache) { setCachedParent(parent); } return parent; } catch (Exception e) { throw new InitException(e.getMessage(), e); } } } protected void setCachedParent(Model parent) { if (parent != null) { cachedParents.put(parent.getClass(), parent); } } /** * Sets multiple parents on this instance. Basically this sets a correct value of a foreign keys in a * parent/child relationship. This only works for one to many and polymorphic associations. * * @param parents - collection of potential parents of this instance. Its ID values must not be null. */ public void setParents(Model... parents){ for (Model parent : parents) { setParent(parent); } } /** * Sets a parent on this instance. Basically this sets a correct value of a foreign key in a * parent/child relationship. This only works for one to many and polymorphic associations. * The act of setting a parent does not result in saving to a database. * * @param parent potential parent of this instance. Its ID value must not be null. */ public void setParent(Model parent) { if (parent == null || parent.getId() == null) { throw new IllegalArgumentException("parent cannot ne null and parent ID cannot be null"); } List<Association> associations = getMetaModelLocal().getAssociations(); for (Association association : associations) { if (association instanceof BelongsToAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())) { set(((BelongsToAssociation)association).getFkName(), parent.getId()); return; } if(association instanceof BelongsToPolymorphicAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())){ set("parent_id", parent.getId()); set("parent_type", ((BelongsToPolymorphicAssociation)association).getTypeLabel()); return; } } StringBuilder sb = new StringBuilder(); sb.append("Class: ").append(parent.getClass()).append(" is not associated with ").append(this.getClass()) .append(", list of existing associations:\n"); join(sb, getMetaModelLocal().getAssociations(), "\n"); throw new IllegalArgumentException(sb.toString()); } /** * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. * * @param other target model. */ public void copyTo(Model other) { other.copyFrom(this); } /** * Copies all attribute values (except for ID, created_at and updated_at) from other instance to this one. * * @param other source model. */ public void copyFrom(Model other) { if (!getMetaModelLocal().getTableName().equals(other.getMetaModelLocal().getTableName())) { throw new IllegalArgumentException("can only copy between the same types"); } Map<String, Object> otherAttributes = other.getAttributes(); for (String name : getMetaModelLocal().getAttributeNamesSkipId()) { attributes.put(name, otherAttributes.get(name)); dirtyAttributeNames.add(name); // Why not use setRaw() here? Does the same and avoids duplication of code... (Garagoth) // other.setRaw(name, getRaw(name)); } } /** * This method should be called from all instance methods for performance. * * @return */ protected MetaModel getMetaModelLocal() { if (metaModelLocal == null) { // optimized not to depend on static or instrumented methods metaModelLocal = Registry.instance().getMetaModel(this.getClass()); } return metaModelLocal; } protected void setMetamodelLocal(MetaModel metamodelLocal){ this.metaModelLocal = metamodelLocal; } ModelRegistry modelRegistryLocal() { if (modelRegistryLocal == null) { // optimized not to depend on static or instrumented methods modelRegistryLocal = Registry.instance().modelRegistryOf(this.getClass()); } return modelRegistryLocal; } /** * Re-reads all attribute values from DB. * */ public void refresh() { Model fresh = ModelDelegate.findById(this.getClass(), getId()); if (fresh == null) { throw new StaleModelException("Failed to refresh self because probably record with " + "this ID does not exist anymore. Stale model: " + this); } fresh.copyTo(this); dirtyAttributeNames.clear(); } /** * Returns a value for attribute. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Object</code>, given the attribute value is an instance of <code>S</code>, then it will be used. * * <h3>Infer relationship from name of argument</h3> * Besides returning direct attributes of this model, this method is also * aware of relationships and can return collections based on naming conventions. For example, if a model User has a * one to many relationship with a model Address, then the following code will work: * <pre> * Address address = ...; * User user = (User)address.get("user"); * </pre> * Conversely, this will also work: * <pre> * List&lt;Address&gt; addresses = (List&lt;Address&gt;)user.get(&quot;addresses&quot;); * </pre> * * The same would also work for many to many relationships: * <pre> * List&lt;Doctor&gt; doctors = (List&lt;Doctor&gt;)patient.get(&quot;doctors&quot;); * ... * List&lt;Patient&gt; patients = (List&lt;Patient&gt;)doctor.get(&quot;patients&quot;); * </pre> * * This methods will try to infer a name if a table by using {@link org.javalite.common.Inflector} to try to * convert it to singular and them plural form, an attempting to see if this model has an appropriate relationship * with another model, if one is found. This method of finding of relationships is best used in templating * technologies, such as JSPs. For standard cases, please use {@link #parent(Class)}, and {@link #getAll(Class)}. * * <h3>Suppressing inference for performance</h3> * <p> * In some cases, the inference of relationships might take a toll on performance, and if a project is not using * the getter method for inference, than it is wise to turn it off with a system property <code>activejdbc.get.inference</code>: * * <pre> * -Dactivejdbc.get.inference = false * </pre> * If inference is turned off, only a value of the attribute is returned. * </p> * * @param attributeName name of attribute of name or related object. * @return value for attribute. */ public Object get(String attributeName) { if (frozen) { throw new FrozenException(this); } if (attributeName == null) { throw new IllegalArgumentException("attributeName cannot be null"); } // NOTE: this is a workaround for JSP pages. JSTL in cases ${item.id} does not call the getId() method, instead // calls item.get("id"), considering that this is a map only! if (attributeName.equalsIgnoreCase("id") && !attributes.containsKey("id")) { return attributes.get(getIdName()); } if (getMetaModelLocal().hasAttribute(attributeName)) { Object value = attributes.get(attributeName); Converter<Object, Object> converter = modelRegistryLocal().converterForValue(attributeName, value, Object.class); return converter != null ? converter.convert(value) : value; } else { String getInferenceProperty = System.getProperty("activejdbc.get.inference"); if (getInferenceProperty == null || getInferenceProperty.equals("true")) { Object returnValue; if ((returnValue = tryParent(attributeName)) != null) { return returnValue; } else if ((returnValue = tryPolymorphicParent(attributeName)) != null) { return returnValue; } else if ((returnValue = tryChildren(attributeName)) != null) { return returnValue; } else if ((returnValue = tryPolymorphicChildren(attributeName)) != null) { return returnValue; } else if ((returnValue = tryOther(attributeName)) != null) { return returnValue; } else { getMetaModelLocal().checkAttributeOrAssociation(attributeName); return null; } } } return null; } /** * Gets raw value of the attribute, without conversions applied. */ private Object getRaw(String attributeName) { if(frozen) throw new FrozenException(this); if(attributeName == null) throw new IllegalArgumentException("attributeName cannot be null"); return attributes.get(attributeName);//this should account for nulls too! } private Object tryPolymorphicParent(String parentTable){ MetaModel parentMM = inferTargetMetaModel(parentTable); if(parentMM == null){ return null; }else return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToPolymorphicAssociation.class) ? parent(parentMM.getModelClass()): null; } private Object tryParent(String parentTable){ MetaModel parentMM = inferTargetMetaModel(parentTable); if(parentMM == null){ return null; }else return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToAssociation.class) ? parent(parentMM.getModelClass()): null; } private Object tryPolymorphicChildren(String childTable){ MetaModel childMM = inferTargetMetaModel(childTable); if(childMM == null){ return null; }else return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyPolymorphicAssociation.class) ? getAll(childMM.getModelClass()): null; } private Object tryChildren(String childTable){ MetaModel childMM = inferTargetMetaModel(childTable); if(childMM == null){ return null; }else return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyAssociation.class) ? getAll(childMM.getModelClass()): null; } private Object tryOther(String otherTable){ MetaModel otherMM = inferTargetMetaModel(otherTable); if(otherMM == null){ return null; }else return getMetaModelLocal().hasAssociation(otherMM.getTableName(), Many2ManyAssociation.class) ? getAll(otherMM.getModelClass()): null; } private MetaModel inferTargetMetaModel(String targetTableName){ String targetTable = singularize(targetTableName); MetaModel targetMM = Registry.instance().getMetaModel(targetTable); if(targetMM == null){ targetTable = pluralize(targetTableName); targetMM = Registry.instance().getMetaModel(targetTable); } return targetMM != null? targetMM: null; } /*************************** typed getters *****************************************/ /** * Gets attribute value as <code>String</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.String</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toString(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>String</code> */ public String getString(String attributeName) { Object value = getRaw(attributeName); Converter<Object, String> converter = modelRegistryLocal().converterForValue(attributeName, value, String.class); return converter != null ? converter.convert(value) : Convert.toString(value); } /** * Gets a value as bytes. If the column is Blob, bytes are * read directly, if not, then the value is converted to String first, then * string bytes are returned. Be careful out there, this will read entire * Blob onto memory. * * @param attributeName name of attribute * @return value as bytes. */ //TODO: use converters here? public byte[] getBytes(String attributeName) { Object value = get(attributeName); return Convert.toBytes(value); } /** * Gets attribute value as <code>java.math.BigDecimal</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.math.BigDecimal</code>, given the attribute value is an instance of <code>S</code>, then it will be * used, otherwise performs a conversion using {@link Convert#toBigDecimal(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>java.math.BigDecimal</code> */ public BigDecimal getBigDecimal(String attributeName) { Object value = getRaw(attributeName); Converter<Object, BigDecimal> converter = modelRegistryLocal().converterForValue( attributeName, value, BigDecimal.class); return converter != null ? converter.convert(value) : Convert.toBigDecimal(value); } /** * Gets attribute value as <code>Integer</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Integer</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toInteger(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Integer</code> */ public Integer getInteger(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Integer> converter = modelRegistryLocal().converterForValue(attributeName, value, Integer.class); return converter != null ? converter.convert(value) : Convert.toInteger(value); } /** * Gets attribute value as <code>Long</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Long</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toLong(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Long</code> */ public Long getLong(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Long> converter = modelRegistryLocal().converterForValue(attributeName, value, Long.class); return converter != null ? converter.convert(value) : Convert.toLong(value); } /** * Gets attribute value as <code>Short</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Short</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toShort(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Short</code> */ public Short getShort(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Short> converter = modelRegistryLocal().converterForValue(attributeName, value, Short.class); return converter != null ? converter.convert(value) : Convert.toShort(value); } /** * Gets attribute value as <code>Float</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Float</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toFloat(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Float</code> */ public Float getFloat(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Float> converter = modelRegistryLocal().converterForValue(attributeName, value, Float.class); return converter != null ? converter.convert(value) : Convert.toFloat(value); } /** * Gets attribute value as <code>java.sql.Time</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Time</code>, given the attribute value is an instance of <code>S</code>, then it will be * used, otherwise performs a conversion using {@link Convert#toTime(Object)}. * * @param attributeName name of attribute to convert * @return instance of <code>Timestamp</code> */ public Time getTime(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Time> converter = modelRegistryLocal().converterForValue( attributeName, value, Time.class); return converter != null ? converter.convert(value) : Convert.toTime(value); } /** * Gets attribute value as <code>java.sql.Timestamp</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Timestamp</code>, given the attribute value is an instance of <code>S</code>, then it will be * used, otherwise performs a conversion using {@link Convert#toTimestamp(Object)}. * * @param attributeName name of attribute to convert * @return instance of <code>Timestamp</code> */ public Timestamp getTimestamp(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Timestamp> converter = modelRegistryLocal().converterForValue( attributeName, value, Timestamp.class); return converter != null ? converter.convert(value) : Convert.toTimestamp(value); } /** * Gets attribute value as <code>Double</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Double</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toDouble(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Double</code> */ public Double getDouble(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Double> converter = modelRegistryLocal().converterForValue(attributeName, value, Double.class); return converter != null ? converter.convert(value) : Convert.toDouble(value); } /** * Gets attribute value as <code>Boolean</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Boolean</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toBoolean(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Boolean</code> */ public Boolean getBoolean(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Boolean> converter = modelRegistryLocal().converterForValue(attributeName, value, Boolean.class); return converter != null ? converter.convert(value) : Convert.toBoolean(value); } /*************************** typed setters *****************************************/ /** * Sets attribute value as <code>String</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.String</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toString(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setString(String attributeName, Object value) { Converter<Object, String> converter = modelRegistryLocal().converterForValue(attributeName, value, String.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toString(value)); } /** * Sets attribute value as <code>java.math.BigDecimal</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.math.BigDecimal</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toBigDecimal(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setBigDecimal(String attributeName, Object value) { Converter<Object, BigDecimal> converter = modelRegistryLocal().converterForValue( attributeName, value, BigDecimal.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBigDecimal(value)); } /** * Sets attribute value as <code>Short</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Short</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toShort(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setShort(String attributeName, Object value) { Converter<Object, Short> converter = modelRegistryLocal().converterForValue(attributeName, value, Short.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toShort(value)); } /** * Sets attribute value as <code>Integer</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Integer</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toInteger(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setInteger(String attributeName, Object value) { Converter<Object, Integer> converter = modelRegistryLocal().converterForValue(attributeName, value, Integer.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toInteger(value)); } /** * Sets attribute value as <code>Long</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Long</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toLong(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setLong(String attributeName, Object value) { Converter<Object, Long> converter = modelRegistryLocal().converterForValue(attributeName, value, Long.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toLong(value)); } /** * Sets attribute value as <code>Float</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Float</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toFloat(Object)}. * * @param attributeName name of attribute. * @param value value to convert. * @return reference to this model. */ public <T extends Model> T setFloat(String attributeName, Object value) { Converter<Object, Float> converter = modelRegistryLocal().converterForValue(attributeName, value, Float.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toFloat(value)); } /** * Sets attribute value as <code>java.sql.Time</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Time</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toTime(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setTime(String attributeName, Object value) { Converter<Object, Time> converter = modelRegistryLocal().converterForValue( attributeName, value, Time.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toTime(value)); } /** * Sets attribute value as <code>java.sql.Timestamp</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Timestamp</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toTimestamp(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setTimestamp(String attributeName, Object value) { Converter<Object, Timestamp> converter = modelRegistryLocal().converterForValue( attributeName, value, Timestamp.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toTimestamp(value)); } /** * Sets attribute value as <code>Double</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Double</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toDouble(Object)}. * * @param attributeName name of attribute. * @param value value to convert. * @return reference to this model. */ public <T extends Model> T setDouble(String attributeName, Object value) { Converter<Object, Double> converter = modelRegistryLocal().converterForValue(attributeName, value, Double.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toDouble(value)); } /** * Sets attribute value as <code>Boolean</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Boolean</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toBoolean(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setBoolean(String attributeName, Object value) { Converter<Object, Boolean> converter = modelRegistryLocal().converterForValue(attributeName, value, Boolean.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBoolean(value)); } /** * This methods supports one to many, many to many relationships as well as polymorphic associations. * <p/> * In case of one to many, the <code>clazz</code> must be a class of a child model, and it will return a * collection of all children. * <p/> * In case of many to many, the <code>clazz</code> must be a class of a another related model, and it will return a * collection of all related models. * <p/> * In case of polymorphic, the <code>clazz</code> must be a class of a polymorphically related model, and it will return a * collection of all related models. * * * @param clazz class of a child model for one to many, or class of another model, in case of many to many or class of child in case of * polymorphic * * @return list of children in case of one to many, or list of other models, in case many to many. */ public <C extends Model> LazyList<C> getAll(Class<C> clazz) { List<Model> children = cachedChildren.get(clazz); if(children != null){ return (LazyList<C>) children; } String tableName = Registry.instance().getTableName(clazz); if(tableName == null) throw new IllegalArgumentException("table: " + tableName + " does not exist for model: " + clazz); return get(tableName, null); } /** * Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list * by criteria. * * <p/> * <strong>1.</strong> For one to many, the criteria is against the child table. * * <p/> * <strong>2.</strong> For polymorphic association, the criteria is against the child table. * * <p/> * <strong>3.</strong> For many to many, the criteria is against the join table. * For example, if you have table PROJECTS, ASSIGNMENTS and PROGRAMMERS, where a project has many programmers and a programmer * has many projects, and ASSIGNMENTS is a join table, you can write code like this, assuming that the ASSIGNMENTS table * has a column <code>duration_weeks</code>: * * <pre> * List<Project> threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3); * </pre> * where this list will contain all projects to which this programmer is assigned for 3 weeks. * * @param clazz related type * @param query sub-query for join table. * @param params parameters for a sub-query * @return list of relations in many to many */ public <C extends Model> LazyList<C> get(Class<C> clazz, String query, Object ... params){ return get(Registry.instance().getTableName(clazz), query, params); } private <C extends Model> LazyList<C> get(String targetTable, String criteria, Object ...params) { //TODO: interesting thought: is it possible to have two associations of the same name, one to many and many to many? For now, say no. OneToManyAssociation oneToManyAssociation = getMetaModelLocal().getAssociationForTarget( targetTable, OneToManyAssociation.class); Many2ManyAssociation manyToManyAssociation = getMetaModelLocal().getAssociationForTarget( targetTable, Many2ManyAssociation.class); OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = getMetaModelLocal().getAssociationForTarget( targetTable, OneToManyPolymorphicAssociation.class); String additionalCriteria = criteria != null? " AND ( " + criteria + " ) " : ""; String subQuery; if (oneToManyAssociation != null) { subQuery = oneToManyAssociation.getFkName() + " = ? " + additionalCriteria; } else if (manyToManyAssociation != null) { String targetId = Registry.instance().getMetaModel(targetTable).getIdName(); String joinTable = manyToManyAssociation.getJoin(); String query = "SELECT " + targetTable + ".* FROM " + targetTable + ", " + joinTable + " WHERE " + targetTable + "." + targetId + " = " + joinTable + "." + manyToManyAssociation.getTargetFkName() + " AND " + joinTable + "." + manyToManyAssociation.getSourceFkName() + " = ? " + additionalCriteria; Object[] allParams = new Object[params.length + 1]; allParams[0] = getId(); System.arraycopy(params, 0, allParams, 1, params.length); return new LazyList<C>(true, Registry.instance().getMetaModel(targetTable), query, allParams); } else if (oneToManyPolymorphicAssociation != null) { subQuery = "parent_id = ? AND " + " parent_type = '" + oneToManyPolymorphicAssociation.getTypeLabel() + "'" + additionalCriteria; } else { throw new NotAssociatedException(getMetaModelLocal().getTableName(), targetTable); } Object[] allParams = new Object[params.length + 1]; allParams[0] = getId(); System.arraycopy(params, 0, allParams, 1, params.length); return new LazyList<C>(subQuery, Registry.instance().getMetaModel(targetTable), allParams); } protected static NumericValidationBuilder validateNumericalityOf(String... attributeNames) { return ModelDelegate.validateNumericalityOf(modelClass(), attributeNames); } /** * Adds a validator to the model. * * @param validator new validator. */ public static ValidationBuilder addValidator(Validator validator) { return ModelDelegate.validateWith(modelClass(), validator); } /** * Adds a new error to the collection of errors. This is a convenience method to be used from custom validators. * * @param key - key wy which this error can be retrieved from a collection of errors: {@link #errors()}. * @param value - this is a key of the message in the resource bundle. * @see {@link Messages}. */ public void addError(String key, String value){ errors.put(key, value); } /** * Removes a validator from model. * * @param validator validator to remove. It needs to be an exact reference validator instance to * remove. If argument was not added to this model before, this method will * do nothing. */ public static void removeValidator(Validator validator){ ModelDelegate.removeValidator(modelClass(), validator); } //TODO: missing no-arg getValidators()? public static List<Validator> getValidators(Class<? extends Model> clazz) { return ModelDelegate.validatorsOf(clazz); } /** * Validates an attribite format with a ree hand regular expression. * * @param attributeName attribute to validate. * @param pattern regexp pattern which must match the value. * @return */ protected static ValidationBuilder validateRegexpOf(String attributeName, String pattern) { return ModelDelegate.validateRegexpOf(modelClass(), attributeName, pattern); } /** * Validates email format. * * @param attributeName name of attribute that holds email value. * @return */ protected static ValidationBuilder validateEmailOf(String attributeName) { return ModelDelegate.validateEmailOf(modelClass(), attributeName); } /** * Validates range. Accepted types are all java.lang.Number subclasses: * Byte, Short, Integer, Long, Float, Double BigDecimal. * * @param attributeName attribute to validate - should be within range. * @param min min value of range. * @param max max value of range. * @return */ protected static ValidationBuilder validateRange(String attributeName, Number min, Number max) { return ModelDelegate.validateRange(modelClass(), attributeName, min, max); } /** * The validation will not pass if the value is either an empty string "", or null. * * @param attributeNames list of attributes to validate. * @return */ protected static ValidationBuilder validatePresenceOf(String... attributeNames) { return ModelDelegate.validatePresenceOf(modelClass(), attributeNames); } /** * Add a custom validator to the model. * * @param validator custom validator. */ protected static ValidationBuilder validateWith(Validator validator) { return ModelDelegate.validateWith(modelClass(), validator); } /** * Adds a custom converter to the model. * * @param converter custom converter * @deprecated use {@link #convertWith(org.javalite.activejdbc.conversion.Converter, String...)} instead */ @Deprecated protected static ValidationBuilder convertWith(org.javalite.activejdbc.validation.Converter converter) { return ModelDelegate.convertWith(modelClass(), converter); } /** * Registers a custom converter for the specified attributes. * * @param converter custom converter * @param attributeNames attribute names */ protected static void convertWith(Converter converter, String... attributeNames) { ModelDelegate.convertWith(modelClass(), converter, attributeNames); } /** * Converts a named attribute to <code>java.sql.Date</code> if possible. * Acts as a validator if cannot make a conversion. * * @param attributeName name of attribute to convert to <code>java.sql.Date</code>. * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} * @return message passing for custom validation message. * @deprecated use {@link #dateFormat(String, String...) instead */ @Deprecated protected static ValidationBuilder convertDate(String attributeName, String format){ return ModelDelegate.convertDate(modelClass(), attributeName, format); } /** * Converts a named attribute to <code>java.sql.Timestamp</code> if possible. * Acts as a validator if cannot make a conversion. * * @param attributeName name of attribute to convert to <code>java.sql.Timestamp</code>. * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} * @return message passing for custom validation message. * @deprecated use {@link #timestampFormat(String, String...) instead */ @Deprecated protected static ValidationBuilder convertTimestamp(String attributeName, String format){ return ModelDelegate.convertTimestamp(modelClass(), attributeName, format); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Date when using the appropriate getters and setters. * * <p>For example: * <blockquote><pre> * public class Person extends Model { * static { * dateFormat("MM/dd/yyyy", "dob"); * } * } * * Person p = new Person(); * // will convert String -> java.sql.Date * p.setDate("dob", "02/29/2000"); * // will convert Date -> String, if dob value in model is of type Date * String str = p.getString("dob"); * * // will convert Date -> String * p.setString("dob", new Date()); * // will convert String -> java.sql.Date, if dob value in model is of type String * Date date = p.getDate("dob"); * </pre></blockquote> * * @param pattern pattern to use for conversion * @param attributeNames attribute names */ protected static void dateFormat(String pattern, String... attributeNames) { ModelDelegate.dateFormat(modelClass(), pattern, attributeNames); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Date when using the appropriate getters and setters. * * <p>See example in {@link #dateFormat(String, String...)}. * * @param format format to use for conversion * @param attributeNames attribute names */ protected static void dateFormat(DateFormat format, String... attributeNames) { ModelDelegate.dateFormat(modelClass(), format, attributeNames); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Timestamp when using the appropriate getters and setters. * * <p>For example: * <blockquote><pre> * public class Person extends Model { * static { * timestampFormat("MM/dd/yyyy hh:mm a", "birth_datetime"); * } * } * * Person p = new Person(); * // will convert String -> java.sql.Timestamp * p.setTimestamp("birth_datetime", "02/29/2000 12:07 PM"); * // will convert Date -> String, if dob value in model is of type Date or java.sql.Timestamp * String str = p.getString("birth_datetime"); * * // will convert Date -> String * p.setString("birth_datetime", new Date()); * // will convert String -> java.sql.Timestamp, if dob value in model is of type String * Timestamp ts = p.getTimestamp("birth_datetime"); * </pre></blockquote> * * @param pattern pattern to use for conversion * @param attributeNames attribute names */ protected static void timestampFormat(String pattern, String... attributeNames) { ModelDelegate.timestampFormat(modelClass(), pattern, attributeNames); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Timestamp when using the appropriate getters and setters. * * <p>See example in {@link #timestampFormat(String, String...)}. * * @param format format to use for conversion * @param attributeNames attribute names */ protected static void timestampFormat(DateFormat format, String... attributeNames) { ModelDelegate.timestampFormat(modelClass(), format, attributeNames); } /** * Registers {@link BlankToNullConverter} for specified attributes. This will convert instances of <tt>String</tt> * that are empty or contain only whitespaces to <tt>null</tt>. * * @param attributeNames attribute names */ protected static void blankToNull(String... attributeNames) { ModelDelegate.blankToNull(modelClass(), attributeNames); } /** * Registers {@link ZeroToNullConverter} for specified attributes. This will convert instances of <tt>Number</tt> * that are zero to <tt>null</tt>. * * @param attributeNames attribute names */ protected static void zeroToNull(String... attributeNames) { ModelDelegate.zeroToNull(modelClass(), attributeNames); } public static boolean belongsTo(Class<? extends Model> targetClass) { return ModelDelegate.belongsTo(modelClass(), targetClass); } /** * @deprecated use {@link #callbackWith(CallbackListener...)} instead */ @Deprecated public static void addCallbacks(CallbackListener... listeners) { ModelDelegate.callbackWith(modelClass(), listeners); } public static void callbackWith(CallbackListener... listeners) { ModelDelegate.callbackWith(modelClass(), listeners); } /** * This method performs validations and then returns true if no errors were generated, otherwise returns false. * * @return true if no errors were generated, otherwise returns false. */ public boolean isValid(){ validate(); return !hasErrors(); } /** * Executes all validators attached to this model. */ public void validate() { fireBeforeValidation(); errors = new Errors(); List<Validator> validators = modelRegistryLocal().validators(); if (validators != null) { for (Validator validator : validators) { validator.validate(this); } } fireAfterValidation(); } public boolean hasErrors() { return errors != null && errors.size() > 0; } /** * Binds a validator to an attribute if validation fails. * * @param errorKey key of error in errors map. Usually this is a name of attribute, * but not limited to that, can be anything. * * @param validator -validator that failed validation. */ public void addValidator(Validator validator, String errorKey) { if(!errors.containsKey(errorKey)) errors.addValidator(errorKey, validator); } /** * Provides an instance of <code>Errors</code> object, filled with error messages after validation. * * @return an instance of <code>Errors</code> object, filled with error messages after validation. */ public Errors errors() { return errors; } /** * Provides an instance of localized <code>Errors</code> object, filled with error messages after validation. * * @param locale locale. * @return an instance of localized <code>Errors</code> object, filled with error messages after validation. */ public Errors errors(Locale locale) { errors.setLocale(locale); return errors; } /** * This is a convenience method to create a model instance already initialized with values. * Example: * <pre> * Person p = Person.create("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07"); * </pre> * * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every * other is a corresponding value. * * This allows for better readability of code. If you just read this aloud, it will become clear. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model. */ public static <T extends Model> T create(Object... namesAndValues) { return ModelDelegate.create(Model.<T>modelClass(), namesAndValues); } /** * This is a convenience method to set multiple values to a model. * Example: * <pre> * Person p = ... * Person p = p.set("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07"); * </pre> * * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every * other is a corresponding value. * * This allows for better readability of code. If you just read this aloud, it will become clear. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model. */ public <T extends Model> T set(Object... namesAndValues) { if (namesAndValues.length % 2 != 0) { throw new IllegalArgumentException("number of arguments must be even"); } for (int i = 0; i < namesAndValues.length; ) { if (namesAndValues[i] == null) { throw new IllegalArgumentException("attribute names cannot be null"); } set(namesAndValues[i++].toString(), namesAndValues[i++]); } return (T) this; } /** * This is a convenience method to {@link #create(Object...)}. It will create a new model and will save it * to DB. It has the same semantics as {@link #saveIt()}. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model which also has been saved to DB. */ public static <T extends Model> T createIt(Object ... namesAndValues){ return ModelDelegate.createIt(Model.<T>modelClass(), namesAndValues); } public static <T extends Model> T findById(Object id) { return ModelDelegate.findById(Model.<T>modelClass(), id); } /** * Composite PK values in exactly the same order as specified in {@link CompositePK}. * * @param values Composite PK values in exactly the same order as specified in {@link CompositePK}. * @return instance of a found model, or null if nothing found. * @see CompositePK */ public static <T extends Model> T findByCompositeKeys(Object... values) { return ModelDelegate.findByCompositeKeys(Model.<T>modelClass(), values); } /** * Finder method for DB queries based on table represented by this model. Usually the SQL starts with: * * <code>"select * from table_name where " + subquery</code> where table_name is a table represented by this model. * * Code example: * <pre> * * List<Person> teenagers = Person.where("age &gt ? and age &lt ?", 12, 20); * // iterate... * * //same can be achieved (since parameters are optional): * List<Person> teenagers = Person.where("age &gt 12 and age &lt 20"); * //iterate * </pre> * * Limit, offset and order by can be chained like this: * * <pre> * List<Person> teenagers = Person.where("age &gt ? and age &lt ?", 12, 20).offset(101).limit(20).orderBy(age); * //iterate * </pre> * * This is a great way to build paged applications. * * * @param subquery this is a set of conditions that normally follow the "where" clause. Example: * <code>"department = ? and dob > ?"</code>. If this value is "*" and no parameters provided, then {@link #findAll()} is executed. * @param params list of parameters corresponding to the place holders in the subquery. * @return instance of <code>LazyList<Model></code> containing results. */ public static <T extends Model> LazyList<T> where(String subquery, Object... params) { return ModelDelegate.where(Model.<T>modelClass(), subquery, params); } /** * Synonym of {@link #where(String, Object...)} * * @param subquery this is a set of conditions that normally follow the "where" clause. Example: * <code>"department = ? and dob &gt ?"</code>. If this value is "*" and no parameters provided, then {@link #findAll()} is executed. * @param params list of parameters corresponding to the place holders in the subquery. * @return instance of <code>LazyList<Model></code> containing results. */ public static <T extends Model> LazyList<T> find(String subquery, Object... params) { return ModelDelegate.where(Model.<T>modelClass(), subquery, params); } /** * Synonym of {@link #first(String, Object...)}. * * @param subQuery selection criteria, example: * <pre> * Person johnTheTeenager = Person.findFirst("name = ? and age &gt 13 and age &lt 19 order by age", "John") * </pre> * Sometimes a query might be just a clause like this: * <pre> * Person oldest = Person.findFirst("order by age desc") * </pre> * @param params list of parameters if question marks are used as placeholders * @return a first result for this condition. May return null if nothing found. */ public static <T extends Model> T findFirst(String subQuery, Object... params) { return ModelDelegate.findFirst(Model.<T>modelClass(), subQuery, params); } /** * Returns a first result for this condition. May return null if nothing found. * If last result is needed, then order by some field and call this nethod: * * Synonym of {@link #findFirst(String, Object...)}. * <pre> * //first: * Person youngestTeenager= Person.first("age &gt 12 and age &lt 20 order by age"); * * //last: * Person oldestTeenager= Person.first("age &gt 12 and age &lt 20 order by age desc"); * </pre> * * * @param subQuery selection criteria, example: * <pre> * Person johnTheTeenager = Person.first("name = ? and age &lt 13 order by age", "John") * </pre> * Sometimes a query might be just a clause like this: * <pre> * Person p = Person.first("order by age desc") * </pre> * @param params list of parameters if question marks are used as placeholders * @return a first result for this condition. May return null if nothing found. */ public static <T extends Model> T first(String subQuery, Object... params) { return ModelDelegate.findFirst(Model.<T>modelClass(), subQuery, params); } /** * This method is for processing really large result sets. Results found by this method are never cached. * * @param query query text. * @param listener this is a call back implementation which will receive instances of models found. * @deprecated use {@link #findWith(ModelListener, String, Object...)}. */ @Deprecated public static void find(String query, final ModelListener listener) { ModelDelegate.findWith(modelClass(), listener, query); } /** * This method is for processing really large result sets. Results found by this method are never cached. * * @param listener this is a call back implementation which will receive instances of models found. * @param query sub-query (content after "WHERE" clause) * @param params optional parameters for a query. */ public static void findWith(final ModelListener listener, String query, Object ... params) { ModelDelegate.findWith(modelClass(), listener, query, params); } /** * Free form query finder. Example: * <pre> * List<Rule> rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc"); * </pre> * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate themselves properly. * Returned columns that are not part of this model will be ignored, but can be used for clauses like above. * * @param fullQuery free-form SQL. * @param params parameters if query is parametrized. * @param <T> - class that extends Model. * @return list of models representing result set. */ public static <T extends Model> LazyList<T> findBySQL(String fullQuery, Object... params) { return ModelDelegate.findBySql(Model.<T>modelClass(), fullQuery, params); } /** * This method returns all records from this table. If you need to get a subset, look for variations of "find()". * * @return result list */ public static <T extends Model> LazyList<T> findAll() { return ModelDelegate.findAll(Model.<T>modelClass()); } /** * Adds a new child dependency. This method works for all three association types: * <ul> * <li>One to many - argument model should be a child in the relationship. This method will immediately set it's * ID as a foreign key on the child and will then save the child.</li> * <li>Many to many - argument model should be the other model in the relationship. This method will check if the * added child already has an ID. If the child does have an ID, then the method will create a link in the join * table. If the child does not have an ID, then this method saves the child first, then creates a record in the * join table linking this model instance and the child instance.</li> * <li>Polymorphic - argument model should be a polymorphic child of this model. This method will set the * <code>parent_id</code> and <code>parent_type</code> as appropriate and then will then save the child.</li> * </ul> * * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. * * @param child instance of a model that has a relationship to the current model. * Either one to many or many to many relationships are accepted. */ public void add(Model child) { if(child == null) throw new IllegalArgumentException("cannot add what is null"); //TODO: refactor this method String childTable = Registry.instance().getTableName(child.getClass()); MetaModel metaModel = getMetaModelLocal(); if (getId() != null) { if (metaModel.hasAssociation(childTable, OneToManyAssociation.class)) { OneToManyAssociation ass = metaModel.getAssociationForTarget(childTable, OneToManyAssociation.class); String fkName = ass.getFkName(); child.set(fkName, getId()); child.saveIt();//this will cause an exception in case validations fail. }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ Many2ManyAssociation ass = metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); if (child.getId() == null) { child.saveIt(); } MetaModel joinMetaModel = Registry.instance().getMetaModel(ass.getJoin()); if (joinMetaModel == null) { new DB(metaModel.getDbName()).exec(metaModel.getDialect().insertManyToManyAssociation(ass), getId(), child.getId()); } else { //TODO: write a test to cover this case: //this is for Oracle, many 2 many, and all annotations used, including @IdGenerator. In this case, //it is best to delegate generation of insert to a model (sequences, etc.) try { Model joinModel = joinMetaModel.getModelClass().newInstance(); joinModel.set(ass.getSourceFkName(), getId()); joinModel.set(ass.getTargetFkName(), child.getId()); joinModel.saveIt(); } catch (InstantiationException e) { throw new InitException("failed to create a new instance of class: " + joinMetaModel.getClass() + ", are you sure this class has a default constructor?", e); } catch (IllegalAccessException e) { throw new InitException(e); } finally { QueryCache.instance().purgeTableCache(ass.getJoin()); QueryCache.instance().purgeTableCache(metaModel.getTableName()); QueryCache.instance().purgeTableCache(childTable); } } } else if(metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { OneToManyPolymorphicAssociation ass = metaModel.getAssociationForTarget( childTable, OneToManyPolymorphicAssociation.class); child.set("parent_id", getId()); child.set("parent_type", ass.getTypeLabel()); child.saveIt(); }else throw new NotAssociatedException(metaModel.getTableName(), childTable); } else { throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. Save this instance first, then you will be able to add dependencies to it."); } } /** * Removes associated child from this instance. The child model should be either in belongs to association (including polymorphic) to this model * or many to many association. * * <h3>One to many and polymorphic associations</h3> * This method will simply call <code>child.delete()</code> method. This will render the child object frozen. * * <h3>Many to many associations</h3> * This method will remove an associated record from the join table, and will do nothing to the child model or record. * * <p/> * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. * * @param child model representing a "child" as in one to many or many to many association with this model. * @return number of records affected */ public int remove(Model child) { if (child == null) { throw new IllegalArgumentException("cannot remove what is null"); } if (child.frozen() || child.getId() == null) { throw new IllegalArgumentException( "Cannot remove a child that does not exist in DB (either frozen, or ID not set)"); } if (getId() != null) { String childTable = Registry.instance().getTableName(child.getClass()); MetaModel metaModel = getMetaModelLocal(); if (metaModel.hasAssociation(childTable, OneToManyAssociation.class) || metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { child.delete(); return 1; } else if (metaModel.hasAssociation(childTable, Many2ManyAssociation.class)) { return new DB(metaModel.getDbName()).exec(metaModel.getDialect().deleteManyToManyAssociation( metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class)), getId(), child.getId()); } else { throw new NotAssociatedException(metaModel.getTableName(), childTable); } } else { throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. " + "Save this instance first, then you will be able to add dependencies to it."); } } /** * This method will not exit silently like {@link #save()}, it instead will throw {@link org.javalite.activejdbc.validation.ValidationException} * if validations did not pass. * * @return true if the model was saved, false if you set an ID value for the model, but such ID does not exist in DB. */ public boolean saveIt() { boolean result = save(); ModelDelegate.purgeEdges(getMetaModelLocal()); if (!errors.isEmpty()) { throw new ValidationException(this); } return result; } /** * Resets all data in this model, including the ID. * After this method, this instance is equivalent to an empty, just created instance. */ public void reset() { attributes = new CaseInsensitiveMap<Object>(); } /** * Unfreezes this model. After this method it is possible again to call save() and saveIt() methods. * This method will erase the value of ID on this instance, while preserving all other attributes' values. * * If a record was deleted, it is frozen and cannot be saved. After it is thawed, it can be saved again, but it will * generate a new insert statement and create a new record in the table with all the same attribute values. * * <p/><p/> * Synonym for {@link #defrost()}. */ public void thaw(){ attributes.put(getIdName(), null); compositeKeyPersisted = false; dirtyAttributeNames.addAll(attributes.keySet()); frozen = false; } /** * Synonym for {@link #thaw()}. */ public void defrost(){ thaw(); } /** * This method will save data from this instance to a corresponding table in the DB. * It will generate insert SQL if the model is new, or update if the model exists in the DB. * This method will execute all associated validations and if those validations generate errors, * these errors are attached to this instance. Errors are available by {#link #errors() } method. * The <code>save()</code> method is mostly for web applications, where code like this is written: * <pre> * if(person.save()) * //show page success * else{ * request.setAttribute("errors", person.errors()); * //show errors page, or same page so that user can correct errors. * } * </pre> * * In other words, this method will not throw validation exceptions. However, if there is a problem in the DB, then * there can be a runtime exception thrown. * * @return true if a model was saved and false if values did not pass validations and the record was not saved. * False will also be returned if you set an ID value for the model, but such ID does not exist in DB. */ public boolean save() { if(frozen) throw new FrozenException(this); fireBeforeSave(); validate(); if (hasErrors()) { return false; } boolean result; if (getId() == null && !compositeKeyPersisted) { result = insert(); } else { result = update(); } fireAfterSave(); return result; } /** * Returns total count of records in table. * * @return total count of records in table. */ public static Long count() { return ModelDelegate.count(modelClass()); } /** * Returns count of records in table under a condition. * * @param query query to select records to count. * @param params parameters (if any) for the query. * @return count of records in table under a condition. */ public static Long count(String query, Object... params) { return ModelDelegate.count(modelClass(), query, params); } /** * This method will save a model as new. In other words, it will not try to guess if this is a * new record or a one that exists in the table. It does not have "belt and suspenders", it will * simply generate and execute insert statement, assuming that developer knows what he/she is doing. * * @return true if model was saved, false if not */ public boolean insert() { fireBeforeCreate(); //TODO: fix this as created_at and updated_at attributes will be set even if insertion failed doCreatedAt(); doUpdatedAt(); MetaModel metaModel = getMetaModelLocal(); List<String> columns = new ArrayList<String>(); List<Object> values = new ArrayList<Object>(); for (Map.Entry<String, Object> entry : attributes.entrySet()) { if (entry.getValue() == null || metaModel.getVersionColumn().equals(entry.getKey())) { continue; } columns.add(entry.getKey()); values.add(entry.getValue()); } if (metaModel.isVersioned()) { columns.add(metaModel.getVersionColumn()); values.add(1); } //TODO: need to invoke checkAttributes here too, and maybe rely on MetaModel for this. try { boolean containsId = (attributes.get(metaModel.getIdName()) != null); // do not use containsKey boolean done; String query = metaModel.getDialect().insertParametrized(metaModel, columns, containsId); if (containsId || getCompositeKeys() != null) { compositeKeyPersisted = done = (1 == new DB(metaModel.getDbName()).exec(query, values.toArray())); } else { Object id = new DB(metaModel.getDbName()).execInsert(query, metaModel.getIdName(), values.toArray()); attributes.put(metaModel.getIdName(), id); done = (id != null); } if (metaModel.cached()) { QueryCache.instance().purgeTableCache(metaModel.getTableName()); } if (metaModel.isVersioned()) { attributes.put(metaModel.getVersionColumn(), 1); } dirtyAttributeNames.clear(); // Clear all dirty attribute names as all were inserted. What about versionColumn ? fireAfterCreate(); return done; } catch (DBException e) { throw e; } catch (Exception e) { throw new DBException(e.getMessage(), e); } } private void doCreatedAt() { if (manageTime && getMetaModelLocal().hasAttribute("created_at")) { attributes.put("created_at", new Timestamp(System.currentTimeMillis())); } } private void doUpdatedAt() { if (manageTime && getMetaModelLocal().hasAttribute("updated_at")) { attributes.put("updated_at", new Timestamp(System.currentTimeMillis())); } } private boolean update() { fireBeforeUpdate(); doUpdatedAt(); MetaModel metaModel = getMetaModelLocal(); StringBuilder query = new StringBuilder().append("UPDATE ").append(metaModel.getTableName()).append(" SET "); Set<String> attributeNames = metaModel.getAttributeNamesSkipGenerated(manageTime); attributeNames.retainAll(dirtyAttributeNames); if(attributeNames.size() > 0) { join(query, attributeNames, " = ?, "); query.append(" = ?"); } List<Object> values = getAttributeValues(attributeNames); if (manageTime && metaModel.hasAttribute("updated_at")) { if(values.size() > 0) query.append(", "); query.append("updated_at = ?"); values.add(get("updated_at")); } if(metaModel.isVersioned()){ if(values.size() > 0) query.append(", "); query.append(getMetaModelLocal().getVersionColumn()).append(" = ?"); values.add(getLong(getMetaModelLocal().getVersionColumn()) + 1); } if(values.isEmpty()) return false; if (getCompositeKeys() != null) { String[] compositeKeys = getCompositeKeys(); for (int i = 0; i < compositeKeys.length; i++) { query.append(i == 0 ? " WHERE " : " AND ").append(compositeKeys[i]).append(" = ?"); values.add(get(compositeKeys[i])); } } else { query.append(" WHERE ").append(metaModel.getIdName()).append(" = ?"); values.add(getId()); } if (metaModel.isVersioned()) { query.append(" AND ").append(getMetaModelLocal().getVersionColumn()).append(" = ?"); values.add(get(getMetaModelLocal().getVersionColumn())); } int updated = new DB(metaModel.getDbName()).exec(query.toString(), values.toArray()); if(metaModel.isVersioned() && updated == 0){ throw new StaleModelException("Failed to update record for model '" + getClass() + "', with " + getIdName() + " = " + getId() + " and " + getMetaModelLocal().getVersionColumn() + " = " + get(getMetaModelLocal().getVersionColumn()) + ". Either this record does not exist anymore, or has been updated to have another " + getMetaModelLocal().getVersionColumn() + '.'); }else if(metaModel.isVersioned()){ set(getMetaModelLocal().getVersionColumn(), getLong(getMetaModelLocal().getVersionColumn()) + 1); } if(metaModel.cached()){ QueryCache.instance().purgeTableCache(metaModel.getTableName()); } dirtyAttributeNames.clear(); fireAfterUpdate(); return updated > 0; } private List<Object> getAttributeValues(Set<String> attributeNames) { List<Object> values = new ArrayList<Object>(); for (String attribute : attributeNames) { values.add(get(attribute)); } return values; } private static <T extends Model> Class<T> modelClass() { throw new InitException("failed to determine Model class name, are you sure models have been instrumented?"); } /** * Returns name of corresponding table. * * @return name of corresponding table. */ public static String getTableName() { return ModelDelegate.tableNameOf(modelClass()); } /** * Value of ID. * * @return of ID. */ public Object getId() { return get(getIdName()); } /** * Name of ID column. * * @return Name of ID column. */ public String getIdName() { return getMetaModelLocal().getIdName(); } /** * Provides a list of composite keys as specified in {@link CompositePK}. * * @return a list of composite keys as specified in {@link CompositePK}. */ public String[] getCompositeKeys() { return getMetaModelLocal().getCompositeKeys(); } protected void setChildren(Class childClass, List<Model> children) { cachedChildren.put(childClass, children); } /** * Turns off automatic management of time-related attributes <code>created_at</code> and <code>updated_at</code>. * If management of time attributes is turned off, * * @param manage if true, the attributes are managed by the model. If false, they are managed by developer. */ public void manageTime(boolean manage) { this.manageTime = manage; } /** * Generates INSERT SQL based on this model. Uses the dialect associated with this model database to format the * value literals. * Example: * <pre> * String sql = user.toInsert(); * //yields this output: * //INSERT INTO users (id, email, first_name, last_name) VALUES (1, '[email protected]', 'Marilyn', 'Monroe') * </pre> * * @return INSERT SQL based on this model. */ public String toInsert() { return toInsert(getMetaModelLocal().getDialect()); } /** * Generates INSERT SQL based on this model with the provided dialect. * Example: * <pre> * String sql = user.toInsert(new MySQLDialect()); * //yields this output: * //INSERT INTO users (id, email, first_name, last_name) VALUES (1, '[email protected]', 'Marilyn', 'Monroe') * </pre> * * @param dialect dialect to be used to generate the SQL * @return INSERT SQL based on this model. */ public String toInsert(Dialect dialect) { return dialect.insert(getMetaModelLocal(), attributes); } /** * Generates UPDATE SQL based on this model. Uses the dialect associated with this model database to format the * value literals. * Example: * <pre> * String sql = user.toUpdate(); * //yields this output: * //UPDATE users SET email = '[email protected]', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1 * </pre> * * @return UPDATE SQL based on this model. */ public String toUpdate() { return toUpdate(getMetaModelLocal().getDialect()); } /** * Generates UPDATE SQL based on this model with the provided dialect. * Example: * <pre> * String sql = user.toUpdate(new MySQLDialect()); * //yields this output: * //UPDATE users SET email = '[email protected]', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1 * </pre> * * @param dialect dialect to be used to generate the SQL * @return UPDATE SQL based on this model. */ public String toUpdate(Dialect dialect) { return dialect.update(getMetaModelLocal(), attributes); } /** * Generates INSERT SQL based on this model. * For instance, for Oracle, the left quote is: "q'{" and the right quote is: "}'". * The output will also use single quotes for <code>java.sql.Timestamp</code> and <code>java.sql.Date</code> types. * * Example: * <pre> * String insert = u.toInsert("q'{", "}'"); * //yields this output * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, q'{Marilyn}', q'{[email protected]}', q'{Monroe}'); * </pre> * @param leftStringQuote - left quote for a string value, this can be different for different databases. * @param rightStringQuote - left quote for a string value, this can be different for different databases. * @return SQL INSERT string; * @deprecated Use {@link #toInsert(Dialect)} instead. */ @Deprecated public String toInsert(String leftStringQuote, String rightStringQuote){ return toInsert(new SimpleFormatter(java.sql.Date.class, "'", "'"), new SimpleFormatter(Timestamp.class, "'", "'"), new SimpleFormatter(String.class, leftStringQuote, rightStringQuote)); } /** * @param formatters * @return * @deprecated Use {@link #toInsert(Dialect)} instead. */ @Deprecated public String toInsert(Formatter... formatters){ HashMap<Class, Formatter> formatterMap = new HashMap<Class, Formatter>(); for(Formatter f: formatters){ formatterMap.put(f.getValueClass(), f); } StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO ").append(getMetaModelLocal().getTableName()).append(" ("); join(sb, attributes.keySet(), ", "); sb.append(") VALUES ("); Iterator<Object> it = attributes.values().iterator(); while (it.hasNext()) { Object value = it.next(); if (value == null) { sb.append("NULL"); } else if (value instanceof String && !formatterMap.containsKey(String.class)){ sb.append('\'').append(value).append('\''); }else{ if(formatterMap.containsKey(value.getClass())){ sb.append(formatterMap.get(value.getClass()).format(value)); }else{ sb.append(value); } } if (it.hasNext()) { sb.append(", "); } } sb.append(')'); return sb.toString(); } /** * Use to force-purge cache associated with this table. If this table is not cached, this method has no side effect. */ public static void purgeCache(){ ModelDelegate.purgeCache(modelClass()); } /** * Convenience method: converts ID value to Long and returns it. * * @return value of attribute corresponding to <code>getIdName()</code>, converted to Long. */ public Long getLongId() { Object id = getId(); if (id == null) { throw new NullPointerException(getIdName() + " is null, cannot convert to Long"); } return Convert.toLong(id); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(attributes); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { attributes = new CaseInsensitiveMap<Object>(); attributes.putAll((Map<String, Object>) in.readObject()); } }
activejdbc/src/main/java/org/javalite/activejdbc/Model.java
/* Copyright 2009-2015 Igor Polevoy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.javalite.activejdbc; import org.javalite.activejdbc.annotations.CompositePK; import org.javalite.activejdbc.associations.*; import org.javalite.activejdbc.cache.QueryCache; import org.javalite.activejdbc.conversion.BlankToNullConverter; import org.javalite.activejdbc.conversion.Converter; import org.javalite.activejdbc.conversion.ZeroToNullConverter; import org.javalite.activejdbc.dialects.Dialect; import org.javalite.activejdbc.validation.NumericValidationBuilder; import org.javalite.activejdbc.validation.ValidationBuilder; import org.javalite.activejdbc.validation.ValidationException; import org.javalite.activejdbc.validation.Validator; import org.javalite.common.Convert; import org.javalite.common.Escape; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.*; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.util.*; import static org.javalite.common.Inflector.*; import static org.javalite.common.Util.blank; import static org.javalite.common.Util.empty; import static org.javalite.common.Util.join; /** * This class is a super class of all "models" and provides most functionality * necessary for implementation of Active Record pattern. * * @author Igor Polevoy * @author Eric Nielsen */ public abstract class Model extends CallbackSupport implements Externalizable { private final static Logger logger = LoggerFactory.getLogger(Model.class); private Map<String, Object> attributes = new CaseInsensitiveMap<Object>(); private final Set<String> dirtyAttributeNames = new CaseInsensitiveSet(); private boolean frozen = false; private MetaModel metaModelLocal; private ModelRegistry modelRegistryLocal; private final Map<Class, Model> cachedParents = new HashMap<Class, Model>(); private final Map<Class, List<Model>> cachedChildren = new HashMap<Class, List<Model>>(); private boolean manageTime = true; private boolean compositeKeyPersisted = false; private Errors errors = new Errors(); protected Model() { } private void fireAfterLoad() { afterLoad(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterLoad(this); } } private void fireBeforeSave() { beforeSave(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeSave(this); } } private void fireAfterSave() { afterSave(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterSave(this); } } private void fireBeforeCreate() { beforeCreate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeCreate(this); } } private void fireAfterCreate() { afterCreate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterCreate(this); } } private void fireBeforeUpdate() { beforeUpdate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeUpdate(this); } } private void fireAfterUpdate() { afterUpdate(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterUpdate(this); } } private void fireBeforeDelete() { beforeDelete(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.beforeDelete(this); } } private void fireAfterDelete() { afterDelete(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterDelete(this); } } private void fireBeforeValidation() { beforeValidation(); for(CallbackListener callback: modelRegistryLocal().callbacks()) callback.beforeValidation(this); } private void fireAfterValidation() { afterValidation(); for (CallbackListener callback : modelRegistryLocal().callbacks()) { callback.afterValidation(this); } } public static MetaModel getMetaModel() { return ModelDelegate.metaModelOf(modelClass()); } protected Map<String, Object> getAttributes() { return Collections.unmodifiableMap(attributes); } protected Set<String> dirtyAttributeNames() { return Collections.unmodifiableSet(dirtyAttributeNames); } /** * Overrides attribute values from input map. The input map may have attributes whose name do not match the * attribute names (columns) of this model. Such attributes will be ignored. Those values whose names are * not present in the argument map, will stay untouched. The input map may have only partial list of attributes. * * @param input map with attributes to overwrite this models'. Keys are names of attributes of this model, values * are new values for it. */ public <T extends Model> T fromMap(Map input) { hydrate(input, false); dirtyAttributeNames.addAll(input.keySet()); return (T) this; } /** * Hydrates a this instance of model from a map. Only picks values from a map that match * this instance's attribute names, while ignoring the others. * * @param attributesMap map containing values for this instance. */ protected void hydrate(Map<String, Object> attributesMap, boolean fireAfterLoad) { Set<String> attributeNames = getMetaModelLocal().getAttributeNames(); for (Map.Entry<String, Object> entry : attributesMap.entrySet()) { if (attributeNames.contains(entry.getKey())) { if (entry.getValue() instanceof Clob && getMetaModelLocal().cached()) { this.attributes.put(entry.getKey(), Convert.toString(entry.getValue())); } else { this.attributes.put(entry.getKey(), getMetaModelLocal().getDialect().overrideDriverTypeConversion( getMetaModelLocal(), entry.getKey(), entry.getValue())); } } } if (getCompositeKeys() != null){ compositeKeyPersisted = true; } if(fireAfterLoad){ fireAfterLoad(); } } /** * Convenience method, sets ID value on this model, equivalent to <code>set(getIdName(), id)</code>. * * @param id value of ID * @return reference to self for chaining. */ public <T extends Model> T setId(Object id) { return set(getIdName(), id); } /** * Sets attribute value as <code>java.sql.Date</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Date</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toSqlDate(Object)}. * * @param attributeName name of attribute. * @param value value to convert. * @return reference to this model. */ public <T extends Model> T setDate(String attributeName, Object value) { Converter<Object, java.sql.Date> converter = modelRegistryLocal().converterForValue( attributeName, value, java.sql.Date.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toSqlDate(value)); } /** * Gets attribute value as <code>java.sql.Date</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Date</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toSqlDate(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>java.sql.Date</code> */ public java.sql.Date getDate(String attributeName) { Object value = getRaw(attributeName); Converter<Object, java.sql.Date> converter = modelRegistryLocal().converterForValue( attributeName, value, java.sql.Date.class); return converter != null ? converter.convert(value) : Convert.toSqlDate(value); } /** * Performs a primitive conversion of <code>java.util.Date</code> to <code>java.sql.Timestamp</code> * based on the time value. * * @param name name of field. * @param date date value. * @deprecated use {@link #setTimestamp(String, Object)} instead. */ @Deprecated public void setTS(String name, java.util.Date date) { if(date == null) { set(name, null); } else { set(name, new java.sql.Timestamp(date.getTime())); } } /** * Sets values for this model instance. The sequence of values must correspond to sequence of names. * * @param attributeNames names of attributes. * @param values values for this instance. */ public void set(String[] attributeNames, Object[] values) { if (attributeNames == null || values == null || attributeNames.length != values.length) { throw new IllegalArgumentException("must pass non-null arrays of equal length"); } for (int i = 0; i < attributeNames.length; i++) { set(attributeNames[i], values[i]); } } /** * Sets a value of an attribute. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Object</code>, given the value is an instance of <code>S</code>, then it will be used and the * converted value will be set. * * @param attributeName name of attribute to set. Names not related to this model will be rejected (those not matching table columns). * @param value value of attribute. Feel free to set any type, as long as it can be accepted by your driver. * @return reference to self, so you can string these methods one after another. */ public <T extends Model> T set(String attributeName, Object value) { Converter<Object, Object> converter = modelRegistryLocal().converterForValue(attributeName, value, Object.class); return setRaw(attributeName, converter != null ? converter.convert(value) : value); } /** * Sets raw value of an attribute, without applying conversions. */ private <T extends Model> T setRaw(String attributeName, Object value) { if (manageTime && attributeName.equalsIgnoreCase("created_at")) { throw new IllegalArgumentException("cannot set 'created_at'"); } getMetaModelLocal().checkAttributeOrAssociation(attributeName); attributes.put(attributeName, value); dirtyAttributeNames.add(attributeName); return (T) this; } /** * Will return true if any attribute of this instance was changed after latest load/save. * (Instance state differs from state in DB) * @return true if this instance was modified. */ public boolean isModified() { return !dirtyAttributeNames.isEmpty(); } /** * Will return true if this instance is frozen, false otherwise. * A frozen instance cannot use used, as it has no relation to a record in table. * * @return true if this instance is frozen, false otherwise. */ public boolean isFrozen(){ return frozen; } /** * Synonym for {@link #isModified()}. * * @return true if this instance was modified. */ public boolean modified() { return isModified(); } /** * Returns names of all attributes from this model. * @return names of all attributes from this model. * @deprecated use {@link #attributeNames()} instead */ @Deprecated public static List<String> attributes(){ return ModelDelegate.attributes(modelClass()); } /** * Returns names of all attributes from this model. * @return names of all attributes from this model. */ public static Set<String> attributeNames() { return ModelDelegate.attributeNames(modelClass()); } /** * Returns all associations of this model. * @return all associations of this model. */ public static List<Association> associations() { return ModelDelegate.associations(modelClass()); } /** * returns true if this is a new instance, not saved yet to DB, false otherwise. * * @return true if this is a new instance, not saved yet to DB, false otherwise */ public boolean isNew(){ return getId() == null && !compositeKeyPersisted; } /** * Synonym for {@link #isFrozen()}. if(m.frozen()) seems to read better than classical Java convention. * * @return true if this instance is frozen, false otherwise. */ public boolean frozen(){ return isFrozen(); } /** * Deletes a single table record represented by this instance. This method assumes that a corresponding table * has only one record whose PK is the ID of this instance. * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. * * @return true if a record was deleted, false if not. */ public boolean delete() { fireBeforeDelete(); int result; if (getCompositeKeys() != null) { String[] compositeKeys = getCompositeKeys(); StringBuilder query = new StringBuilder(); Object[] values = new Object[compositeKeys.length]; for (int i = 0; i < compositeKeys.length; i++) { query.append(i == 0 ? "DELETE FROM " + getMetaModelLocal().getTableName() + " WHERE " : " AND ").append(compositeKeys[i]).append(" = ?"); values[i] = get(compositeKeys[i]); } result = new DB(getMetaModelLocal().getDbName()).exec(query.toString(), values); } else { result = new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + getMetaModelLocal().getTableName() + " WHERE " + getIdName() + "= ?", getId()); } if (1 == result) { frozen = true; if (getMetaModelLocal().cached()) { QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); } ModelDelegate.purgeEdges(getMetaModelLocal()); fireAfterDelete(); return true; } fireAfterDelete(); return false; } /** * Convenience method, will call {@link #delete()} or {@link #deleteCascade()}. * * @param cascade true to call {@link #deleteCascade()}, false to call {@link #delete()}. */ public void delete(boolean cascade){ if(cascade){ deleteCascade(); }else{ delete(); } } /** * Deletes this record from associated table, as well as children. * * Deletes current model and all of its child and many to many associations. This is not a high performance method, as it will * load every row into a model instance before deleting, effectively calling (N + 1) per table queries to the DB, one to select all * the associated records (per table), and one delete statement per record. Use it for small data sets. * * <p/> * In cases of simple one to many and polymorphic associations, things are as expected, a parent is deleted an all children are * deleted as well, but in more complicated cases, this method will walk entire three of associated tables, sometimes * coming back to the same one where it all started. * It will follow associations of children and their associations too; consider this a true cascade delete with all implications * (circular dependencies, referential integrity constraints, potential performance bottlenecks, etc.) * <p/> * * Imagine a situation where you have DOCTORS and PATIENTS in many to many relationship (with DOCTORS_PATIENTS table * as a join table), and in addition PATIENTS and PRESCRIPTIONS in one to many relationship, where a patient might * have many prescriptions: * <pre> DOCTORS +----+------------+-----------+-----------------+ | id | first_name | last_name | discipline | +----+------------+-----------+-----------------+ | 1 | John | Kentor | otolaryngology | | 2 | Hellen | Hunt | dentistry | | 3 | John | Druker | oncology | +----+------------+-----------+-----------------+ PATIENTS +----+------------+-----------+ | id | first_name | last_name | +----+------------+-----------+ | 1 | Jim | Cary | | 2 | John | Carpenter | | 3 | John | Doe | +----+------------+-----------+ DOCTORS_PATIENTS +----+-----------+------------+ | id | doctor_id | patient_id | +----+-----------+------------+ | 1 | 1 | 2 | | 2 | 1 | 1 | | 3 | 2 | 1 | | 4 | 3 | 3 | +----+-----------+------------+ PRESCRIPTIONS +----+------------------------+------------+ | id | name | patient_id | +----+------------------------+------------+ | 1 | Viagra | 1 | | 2 | Prozac | 1 | | 3 | Valium | 2 | | 4 | Marijuana (medicinal) | 2 | | 5 | CML treatment | 3 | +----+------------------------+------------+ * </pre> * * Lets start with a simple example, Doctor John Druker. This doctor has one patient John Doe, and the patient has one prescription. * So, when an instance of this doctor model is issued statement: * <pre> * drDruker.deleteCascade(); * </pre> * , the result is as expected: the DOCTORS:ID=3 is deleted, DOCTORS_PATIENTS:ID=4 is deleted, PATIENTS:ID=3 is deleted * and PRESCRIPTIONS:ID=5 is deleted. * * <p/> * However, when doctor Kentor(#1) is deleted, the following records are also deleted: * <ul> * <li>DOCTORS_PATIENTS:ID=1, 2 - these are links to patients</li> * <li>PATIENTS:ID=1,2 these are patients themselves</li> * <li>PRESCRIPTIONS:ID=1,2,3,4 - these are prescriptions of patients 1 and 2</li> * </ul> * But, in addition, since this is a many to many relationship, deleting patients 1 and 2 results in also deleting * doctor Hellen Hunt(#2), since she is a doctor of patient Jim Cary(#1), deleting all corresponding join links from * table DOCTORS_PATIENTS. So, deleting doctor Kentor, deleted most all records from related tables, leaving only these * records in place: * <ul> * <li>DOCTORS:ID=3</li> * <li>DOCTORS_PATIENTS:ID=4</li> * <li>PATIENTS:ID=3</li> * <li>PRESCRIPTIONS:ID=5</li> * </ul> * Had doctor Hellen Hunt(#2) had more patients, it would delete them too, and so on. This goes a long way to say that it * could be easy to be tangled up in web of associations, so be careful out there. * * <p/> * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. */ public void deleteCascade(){ deleteCascadeExcept(); } /** * This method does everything {@link #deleteCascade()} does, but in addition allows to exclude some associations * from this action. This is necessary because {@link #deleteCascade()} method can be far too eager to delete * records in a database, and this is a good way to tell the model to exclude some associations from deletes. * * <p>Example:</p> * <code> * Patient.findById(3).deleteCascadeExcept(Patient.getMetaModel().getAssociationForTarget("prescriptions")); * </code> * * @see {@link #deleteCascade()} - see for more information. * @param excludedAssociations associations */ public void deleteCascadeExcept(Association ... excludedAssociations){ List<Association> excludedAssociationsList = Arrays.asList(excludedAssociations); deleteMany2ManyDeep(getMetaModelLocal().getManyToManyAssociations(excludedAssociationsList)); deleteChildrenDeep(getMetaModelLocal().getOneToManyAssociations(excludedAssociationsList)); deleteChildrenDeep(getMetaModelLocal().getPolymorphicAssociations(excludedAssociationsList)); delete(); } private void deleteMany2ManyDeep(List<Many2ManyAssociation> many2ManyAssociations){ List<Model> allMany2ManyChildren = new ArrayList<Model>(); for (Association association : many2ManyAssociations) { String targetTableName = association.getTarget(); Class c = Registry.instance().getModelClass(targetTableName, false); if(c == null){// this model is probably not defined as a class, but the table exists! logger.error("ActiveJDBC WARNING: failed to find a model class for: {}, maybe model is not defined for this table?" + " There might be a risk of running into integrity constrain violation if this model is not defined.", targetTableName); } else{ allMany2ManyChildren.addAll(getAll(c)); } } deleteJoinsForManyToMany(); for (Model model : allMany2ManyChildren) { model.deleteCascade(); } } /** * Deletes this record from associated table, as well as its immediate children. This is a high performance method * because it does not walk through a chain of child dependencies like {@link #deleteCascade()} does, but rather issues * one DELETE statement per child dependency table. Also, its semantics are a bit different between than {@link #deleteCascade()}. * It only deletes current record and immediate children, but not their children (no grand kinds are dead as a result :)). * <h4>One to many and polymorphic associations</h4> * The current record is deleted, as well as immediate children. * <h4>Many to many associations</h4> * The current record is deleted, as well as links in a join table. Nothing else is deleted. * <p/> * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. */ public void deleteCascadeShallow(){ deleteJoinsForManyToMany(); deleteOne2ManyChildrenShallow(); deletePolymorphicChildrenShallow(); delete(); } private void deleteJoinsForManyToMany() { List<? extends Association> associations = getMetaModelLocal().getManyToManyAssociations(Collections.<Association>emptyList()); for (Association association : associations) { String join = ((Many2ManyAssociation)association).getJoin(); String sourceFK = ((Many2ManyAssociation)association).getSourceFkName(); new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + join + " WHERE " + sourceFK + " = ?", getId()); } } private void deleteOne2ManyChildrenShallow() { List<OneToManyAssociation> childAssociations = getMetaModelLocal().getOneToManyAssociations(Collections.<Association>emptyList()); for (OneToManyAssociation association : childAssociations) { String target = association.getTarget(); new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + target + " WHERE " + association.getFkName() + " = ?", getId()); } } private void deletePolymorphicChildrenShallow() { List<OneToManyPolymorphicAssociation> polymorphics = getMetaModelLocal().getPolymorphicAssociations(new ArrayList<Association>()); for (OneToManyPolymorphicAssociation association : polymorphics) { String target = association.getTarget(); String parentType = association.getTypeLabel(); new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + target + " WHERE parent_id = ? AND parent_type = ?", getId(), parentType); } } private void deleteChildrenDeep(List<? extends Association> childAssociations){ for (Association association : childAssociations) { String targetTableName = association.getTarget(); Class c = Registry.instance().getModelClass(targetTableName, false); if(c == null){// this model is probably not defined as a class, but the table exists! logger.error("ActiveJDBC WARNING: failed to find a model class for: {}, maybe model is not defined for this table?" + " There might be a risk of running into integrity constrain violation if this model is not defined.", targetTableName); } else{ List<Model> dependencies = getAll(c); for (Model model : dependencies) { model.deleteCascade(); } } } } /** * Deletes some records from associated table. This method does not follow any associations. * If this model has one to many associations, you might end up with either orphan records in child * tables, or run into integrity constraint violations. However, this method if very efficient as it deletes all records * in one shot, without pre-loading them. * This method also has a side-effect: it will not mark loaded instances corresponding to deleted records as "frozen". * This means that such an instance would allow calling save() and saveIt() methods resulting DB errors, as you * would be attempting to update phantom records. * * * @param query narrows which records to delete. Example: <pre>"last_name like '%sen%'"</pre>. * @param params (optional) - list of parameters if a query is parametrized. * @return number of deleted records. */ public static int delete(String query, Object... params) { return ModelDelegate.delete(modelClass(), query, params); } /** * Returns true if record corresponding to the id passed exists in the DB. * * @param id id in question. * @return true if corresponding record exists in DB, false if it does not. */ public static boolean exists(Object id) { return ModelDelegate.exists(modelClass(), id); } /** * Returns true if record corresponding to the id of this instance exists in the DB. * * @return true if corresponding record exists in DB, false if it does not. */ public boolean exists(){ MetaModel metaModel = getMetaModelLocal(); return null != new DB(metaModel.getDbName()).firstCell(metaModel.getDialect().selectExists(metaModel), getId()); } /** * Deletes all records from associated table. This methods does not take associations into account. * * @return number of records deleted. */ public static int deleteAll() { return ModelDelegate.deleteAll(modelClass()); } /** * Updates records associated with this model. * * This example : * <pre> * Employee.update("bonus = ?", "years_at_company > ?", "5", "10"); * </pre * In this example, employees who worked for more than 10 years, get a bonus of 5% (not so generous :)). * * * @param updates - what needs to be updated. * @param conditions specifies which records to update. If this argument is <code>null</code>, all records in table will be updated. * In such cases, use a more explicit {@link #updateAll(String, Object...)} method. * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, * updates first, then conditions. * @return number of updated records. */ public static int update(String updates, String conditions, Object ... params) { return ModelDelegate.update(modelClass(), updates, conditions, params); } /** * Updates all records associated with this model. * * This example : * <pre> * Employee.updateAll("bonus = ?", "10"); * </pre> * In this example, all employees get a bonus of 10%. * * * @param updates - what needs to be updated. * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, * updates first, then conditions. * @return number of updated records. */ public static int updateAll(String updates, Object ... params) { return ModelDelegate.updateAll(modelClass(), updates, params); } /** * Returns all values of the model with all attribute names converted to lower case, * regardless how these names came from DB. This method is a convenience * method for displaying values on web pages. * * <p/> * If {@link LazyList#include(Class[])} method was used, and this * model belongs to a parent (as in many to one relationship), then the parent * will be eagerly loaded and also converted to a map. Parents' maps are keyed in the * returned map by underscored name of a parent model class name. * <p/> * For example, if this model were <code>Address</code> * and a parent is <code>User</code> (and user has many addresses), then the resulting map would * have all the attributes of the current table and another map representing a parent user with a * key "user" in current map. * * @return all values of the model with all attribute names converted to lower case. */ public Map<String, Object> toMap(){ Map<String, Object> retVal = new TreeMap<String, Object>(); for (Map.Entry<String, Object> entry : attributes.entrySet()) { Object v = entry.getValue(); if (v == null) { continue; } if (v instanceof Clob) { retVal.put(entry.getKey().toLowerCase(), Convert.toString(v)); } else { retVal.put(entry.getKey().toLowerCase(), v); } } for(Class parentClass: cachedParents.keySet()){ retVal.put(underscore(parentClass.getSimpleName()), cachedParents.get(parentClass).toMap()); } for(Class childClass: cachedChildren.keySet()){ List<Model> children = cachedChildren.get(childClass); List<Map> childMaps = new ArrayList<Map>(children.size()); for(Model child:children){ childMaps.add(child.toMap()); } retVal.put(tableize(childClass.getSimpleName()), childMaps); } return retVal; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Model: ").append(getClass().getName()) .append(", table: '").append(getMetaModelLocal().getTableName()) .append("', attributes: ").append(attributes); if (cachedParents.size() > 0) { sb.append(", parents: ").append(cachedParents); } if (cachedChildren.size() > 0) { sb.append(", children: ").append(cachedChildren); } return sb.toString(); } /** * Parses XML into a model. It expects the same structure of XML as the method {@link #toXml(int, boolean, String...)}. * It ignores children and dependencies (for now) if any. This method will parse the model attributes * from the XML document, and will then call {@link #fromMap(java.util.Map)} method. It does not save data into a database, just sets the * attributes. * * @param xml xml to read model attributes from. */ public void fromXml(String xml) { try { XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(xml.getBytes())); String attr = null; String chars = null; Map<Object, Object> res = new HashMap<Object, Object>(); while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: attr = reader.getLocalName(); break; case XMLStreamConstants.CHARACTERS: chars = reader.getText().trim();; break; case XMLStreamConstants.END_ELEMENT: if (attr != null && !blank(chars)) { res.put(attr, chars); } attr = chars = null; break; } } fromMap(res); } catch (XMLStreamException e) { throw new InitException(e); } } /** * Generates a XML document from content of this model. * * @param pretty pretty format (human readable), or one line text. * @param declaration true to include XML declaration at the top * @param attributeNames list of attributes to include. No arguments == include all attributes. * @return generated XML. */ public String toXml(boolean pretty, boolean declaration, String... attributeNames) { StringBuilder sb = new StringBuilder(); if(declaration) { sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); if (pretty) { sb.append('\n'); } } toXmlP(sb, pretty, "", attributeNames); return sb.toString(); } protected void toXmlP(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { String topTag = underscore(getClass().getSimpleName()); if (pretty) { sb.append(indent); } sb.append('<').append(topTag).append('>'); if (pretty) { sb.append('\n'); } String[] names = !empty(attributeNames) ? attributeNames : attributeNamesLowerCased(); for (String name : names) { if (pretty) { sb.append(" ").append(indent); } sb.append('<').append(name).append('>'); Object v = attributes.get(name); if (v != null) { Escape.xml(sb, Convert.toString(v)); } sb.append("</").append(name).append('>'); if (pretty) { sb.append('\n'); } } for (Class childClass : cachedChildren.keySet()) { if (pretty) { sb.append(" ").append(indent); } String tag = pluralize(underscore(childClass.getSimpleName())); sb.append('<').append(tag).append('>'); if (pretty) { sb.append('\n'); } for (Model child : cachedChildren.get(childClass)) { child.toXmlP(sb, pretty, " " + indent); } if (pretty) { sb.append(" ").append(indent); } sb.append("</").append(tag).append('>'); if (pretty) { sb.append('\n'); } } beforeClosingTag(sb, pretty, pretty ? " " + indent : "", attributeNames); if (pretty) { sb.append(indent); } sb.append("</").append(topTag).append('>'); if (pretty) { sb.append('\n'); } } /** * Generates a XML document from content of this model. * * @param spaces by how many spaces to indent. * @param declaration true to include XML declaration at the top * @param attributeNames list of attributes to include. No arguments == include all attributes. * @return generated XML. * * @deprecated use {@link #toXml(boolean, boolean, String...)} instead */ @Deprecated public String toXml(int spaces, boolean declaration, String... attributeNames) { return toXml(spaces > 0, declaration, attributeNames); } /** * Override in a subclass to inject custom content onto XML just before the closing tag. * * <p>To keep the formatting, it is recommended to implement this method as the example below. * * <blockquote><pre> * if (pretty) { sb.append(ident); } * sb.append("&lt;test&gt;...&lt;/test&gt;"); * if (pretty) { sb.append('\n'); } * </pre></blockquote> * * @param sb to write content to. * @param pretty pretty format (human readable), or one line text. * @param indent indent at current level * @param attributeNames list of attributes to include */ public void beforeClosingTag(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { StringWriter writer = new StringWriter(); beforeClosingTag(indent.length(), writer, attributeNames); sb.append(writer.toString()); } /** * Override in a subclass to inject custom content onto XML just before the closing tag. * * @param spaces number of spaces of indent * @param writer to write content to. * @param attributeNames list of attributes to include * * @deprecated use {@link #beforeClosingTag(StringBuilder, boolean, String, String...)} instead */ @Deprecated public void beforeClosingTag(int spaces, StringWriter writer, String... attributeNames) { // do nothing } /** * Generates a JSON document from content of this model. * * @param pretty pretty format (human readable), or one line text. * @param attributeNames list of attributes to include. No arguments == include all attributes. * @return generated JSON. */ public String toJson(boolean pretty, String... attributeNames) { StringBuilder sb = new StringBuilder(); toJsonP(sb, pretty, "", attributeNames); return sb.toString(); } protected void toJsonP(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { if (pretty) { sb.append(indent); } sb.append('{'); String[] names = !empty(attributeNames) ? attributeNames : attributeNamesLowerCased(); for (int i = 0; i < names.length; i++) { if (i > 0) { sb.append(','); } if (pretty) { sb.append("\n ").append(indent); } String name = names[i]; sb.append('"').append(name).append("\":"); Object v = attributes.get(name); if (v == null) { sb.append("null"); } else if (v instanceof Number || v instanceof Boolean) { sb.append(v); } else if (v instanceof Date) { sb.append('"').append(Convert.toIsoString((Date) v)).append('"'); } else { sb.append('"'); Escape.json(sb, Convert.toString(v)); sb.append('"'); } } if (cachedParents.size() > 0) { sb.append(','); if (pretty) { sb.append("\n ").append(indent); } sb.append("\"parents\":{"); List<Class> parentClasses = new ArrayList<Class>(); parentClasses.addAll(cachedParents.keySet()); for (int i = 0; i < parentClasses.size(); i++) { if (i > 0) { sb.append(','); } Class parentClass = parentClasses.get(i); String name = pluralize(parentClasses.get(i).getSimpleName()).toLowerCase(); if (pretty) { sb.append("\n ").append(indent); } sb.append('"').append(name).append("\":["); Model parent = cachedParents.get(parentClass); if (pretty) { sb.append('\n'); } parent.toJsonP(sb, pretty, (pretty ? " " + indent : "")); if(i < (parentClasses.size() - 1)){ sb.append(','); } if (pretty) { sb.append("\n ").append(indent); } sb.append(']'); } if (pretty) { sb.append("\n ").append(indent); } sb.append('}'); } if (cachedChildren.size() > 0) { sb.append(','); if (pretty) { sb.append("\n ").append(indent); } sb.append("\"children\":{"); List<Class> childClasses = new ArrayList<Class>(); childClasses.addAll(cachedChildren.keySet()); for (int i = 0; i < childClasses.size(); i++) { if (i > 0) { sb.append(','); } Class childClass = childClasses.get(i); String name = pluralize(childClass.getSimpleName()).toLowerCase(); if (pretty) { sb.append("\n ").append(indent); } sb.append('"').append(name).append("\":["); List<Model> child = cachedChildren.get(childClass); for (int j = 0; j < child.size(); j++) { if (j > 0) { sb.append(','); } if (pretty) { sb.append('\n'); } child.get(j).toJsonP(sb, pretty, (pretty ? " " + indent : "")); } if (pretty) { sb.append("\n ").append(indent); } sb.append(']'); } if (pretty) { sb.append("\n ").append(indent); } sb.append('}'); } beforeClosingBrace(sb, pretty, pretty ? " " + indent : "", attributeNames); if (pretty) { sb.append('\n').append(indent); } sb.append('}'); } /** * Override in subclasses in order to inject custom content into Json just before the closing brace. * * <p>To keep the formatting, it is recommended to implement this method as the example below. * * <blockquote><pre> * sb.append(','); * if (pretty) { sb.append('\n').append(indent); } * sb.append("\"test\":\"...\""); * </pre></blockquote> * * @param sb to write custom content to * @param pretty pretty format (human readable), or one line text. * @param indent indent at current level * @param attributeNames list of attributes to include */ public void beforeClosingBrace(StringBuilder sb, boolean pretty, String indent, String... attributeNames) { StringWriter writer = new StringWriter(); beforeClosingBrace(pretty, indent, writer); sb.append(writer.toString()); } /** * Override in subclasses in order to inject custom content into Json just before the closing brace. * * @param pretty pretty format (human readable), or one line text. * @param indent indent at current level * @param writer writer to write custom content to * @deprecated use {@link #beforeClosingBrace(StringBuilder, boolean, String, String...)} instead */ @Deprecated public void beforeClosingBrace(boolean pretty, String indent, StringWriter writer) { // do nothing } private String[] attributeNamesLowerCased() { return ModelDelegate.lowerCased(attributes.keySet()); } /** * Returns parent of this model, assuming that this table represents a child. * This method may return <code>null</code> in cases when you have orphan record and * referential integrity is not enforced in DBMS with a foreign key constraint. * * @param parentClass class of a parent model. * @return instance of a parent of this instance in the "belongs to" relationship. */ public <P extends Model> P parent(Class<P> parentClass) { return parent(parentClass, false); } public <P extends Model> P parent(Class<P> parentClass, boolean cache) { P cachedParent = parentClass.cast(cachedParents.get(parentClass)); if (cachedParent != null) { return cachedParent; } MetaModel parentMM = Registry.instance().getMetaModel(parentClass); String parentTable = parentMM.getTableName(); BelongsToAssociation ass = getMetaModelLocal().getAssociationForTarget(parentTable, BelongsToAssociation.class); BelongsToPolymorphicAssociation assP = getMetaModelLocal().getAssociationForTarget( parentTable, BelongsToPolymorphicAssociation.class); Object fkValue; String fkName; if (ass != null) { fkValue = get(ass.getFkName()); fkName = ass.getFkName(); } else if (assP != null) { fkValue = get("parent_id"); fkName = "parent_id"; if (!assP.getTypeLabel().equals(getString("parent_type"))) { throw new IllegalArgumentException("Wrong parent: '" + parentClass + "'. Actual parent type label of this record is: '" + getString("parent_type") + "'"); } } else { throw new IllegalArgumentException("there is no association with table: " + parentTable); } if (fkValue == null) { logger.debug("Attribute: {} is null, cannot determine parent. Child record: {}", fkName, this); return null; } String parentIdName = parentMM.getIdName(); String query = getMetaModelLocal().getDialect().selectStarParametrized(parentTable, parentIdName); if (parentMM.cached()) { P parent = parentClass.cast(QueryCache.instance().getItem(parentTable, query, new Object[]{fkValue})); if (parent != null) { return parent; } } List<Map> results = new DB(getMetaModelLocal().getDbName()).findAll(query, fkValue); //expect only one result here if (results.isEmpty()) { //this should be covered by referential integrity constraint return null; } else { try { P parent = parentClass.newInstance(); parent.hydrate(results.get(0), true); if (parentMM.cached()) { QueryCache.instance().addItem(parentTable, query, new Object[]{fkValue}, parent); } if (cache) { setCachedParent(parent); } return parent; } catch (Exception e) { throw new InitException(e.getMessage(), e); } } } protected void setCachedParent(Model parent) { if (parent != null) { cachedParents.put(parent.getClass(), parent); } } /** * Sets multiple parents on this instance. Basically this sets a correct value of a foreign keys in a * parent/child relationship. This only works for one to many and polymorphic associations. * * @param parents - collection of potential parents of this instance. Its ID values must not be null. */ public void setParents(Model... parents){ for (Model parent : parents) { setParent(parent); } } /** * Sets a parent on this instance. Basically this sets a correct value of a foreign key in a * parent/child relationship. This only works for one to many and polymorphic associations. * The act of setting a parent does not result in saving to a database. * * @param parent potential parent of this instance. Its ID value must not be null. */ public void setParent(Model parent) { if (parent == null || parent.getId() == null) { throw new IllegalArgumentException("parent cannot ne null and parent ID cannot be null"); } List<Association> associations = getMetaModelLocal().getAssociations(); for (Association association : associations) { if (association instanceof BelongsToAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())) { set(((BelongsToAssociation)association).getFkName(), parent.getId()); return; } if(association instanceof BelongsToPolymorphicAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())){ set("parent_id", parent.getId()); set("parent_type", ((BelongsToPolymorphicAssociation)association).getTypeLabel()); return; } } StringBuilder sb = new StringBuilder(); sb.append("Class: ").append(parent.getClass()).append(" is not associated with ").append(this.getClass()) .append(", list of existing associations:\n"); join(sb, getMetaModelLocal().getAssociations(), "\n"); throw new IllegalArgumentException(sb.toString()); } /** * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. * * @param other target model. */ public void copyTo(Model other) { other.copyFrom(this); } /** * Copies all attribute values (except for ID, created_at and updated_at) from other instance to this one. * * @param other source model. */ public void copyFrom(Model other) { if (!getMetaModelLocal().getTableName().equals(other.getMetaModelLocal().getTableName())) { throw new IllegalArgumentException("can only copy between the same types"); } Map<String, Object> otherAttributes = other.getAttributes(); for (String name : getMetaModelLocal().getAttributeNamesSkipId()) { attributes.put(name, otherAttributes.get(name)); dirtyAttributeNames.add(name); // Why not use setRaw() here? Does the same and avoids duplication of code... (Garagoth) // other.setRaw(name, getRaw(name)); } } /** * This method should be called from all instance methods for performance. * * @return */ protected MetaModel getMetaModelLocal() { if (metaModelLocal == null) { // optimized not to depend on static or instrumented methods metaModelLocal = Registry.instance().getMetaModel(this.getClass()); } return metaModelLocal; } protected void setMetamodelLocal(MetaModel metamodelLocal){ this.metaModelLocal = metamodelLocal; } ModelRegistry modelRegistryLocal() { if (modelRegistryLocal == null) { // optimized not to depend on static or instrumented methods modelRegistryLocal = Registry.instance().modelRegistryOf(this.getClass()); } return modelRegistryLocal; } /** * Re-reads all attribute values from DB. * */ public void refresh() { Model fresh = ModelDelegate.findById(this.getClass(), getId()); if (fresh == null) { throw new StaleModelException("Failed to refresh self because probably record with " + "this ID does not exist anymore. Stale model: " + this); } fresh.copyTo(this); dirtyAttributeNames.clear(); } /** * Returns a value for attribute. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Object</code>, given the attribute value is an instance of <code>S</code>, then it will be used. * * <h3>Infer relationship from name of argument</h3> * Besides returning direct attributes of this model, this method is also * aware of relationships and can return collections based on naming conventions. For example, if a model User has a * one to many relationship with a model Address, then the following code will work: * <pre> * Address address = ...; * User user = (User)address.get("user"); * </pre> * Conversely, this will also work: * <pre> * List&lt;Address&gt; addresses = (List&lt;Address&gt;)user.get(&quot;addresses&quot;); * </pre> * * The same would also work for many to many relationships: * <pre> * List&lt;Doctor&gt; doctors = (List&lt;Doctor&gt;)patient.get(&quot;doctors&quot;); * ... * List&lt;Patient&gt; patients = (List&lt;Patient&gt;)doctor.get(&quot;patients&quot;); * </pre> * * This methods will try to infer a name if a table by using {@link org.javalite.common.Inflector} to try to * convert it to singular and them plural form, an attempting to see if this model has an appropriate relationship * with another model, if one is found. This method of finding of relationships is best used in templating * technologies, such as JSPs. For standard cases, please use {@link #parent(Class)}, and {@link #getAll(Class)}. * * <h3>Suppressing inference for performance</h3> * <p> * In some cases, the inference of relationships might take a toll on performance, and if a project is not using * the getter method for inference, than it is wise to turn it off with a system property <code>activejdbc.get.inference</code>: * * <pre> * -Dactivejdbc.get.inference = false * </pre> * If inference is turned off, only a value of the attribute is returned. * </p> * * @param attributeName name of attribute of name or related object. * @return value for attribute. */ public Object get(String attributeName) { if (frozen) { throw new FrozenException(this); } if (attributeName == null) { throw new IllegalArgumentException("attributeName cannot be null"); } // NOTE: this is a workaround for JSP pages. JSTL in cases ${item.id} does not call the getId() method, instead // calls item.get("id"), considering that this is a map only! if (attributeName.equalsIgnoreCase("id") && !attributes.containsKey("id")) { return attributes.get(getIdName()); } if (getMetaModelLocal().hasAttribute(attributeName)) { Object value = attributes.get(attributeName); Converter<Object, Object> converter = modelRegistryLocal().converterForValue(attributeName, value, Object.class); return converter != null ? converter.convert(value) : value; } else { String getInferenceProperty = System.getProperty("activejdbc.get.inference"); if (getInferenceProperty == null || getInferenceProperty.equals("true")) { Object returnValue; if ((returnValue = tryParent(attributeName)) != null) { return returnValue; } else if ((returnValue = tryPolymorphicParent(attributeName)) != null) { return returnValue; } else if ((returnValue = tryChildren(attributeName)) != null) { return returnValue; } else if ((returnValue = tryPolymorphicChildren(attributeName)) != null) { return returnValue; } else if ((returnValue = tryOther(attributeName)) != null) { return returnValue; } else { getMetaModelLocal().checkAttributeOrAssociation(attributeName); return null; } } } return null; } /** * Gets raw value of the attribute, without conversions applied. */ private Object getRaw(String attributeName) { if(frozen) throw new FrozenException(this); if(attributeName == null) throw new IllegalArgumentException("attributeName cannot be null"); return attributes.get(attributeName);//this should account for nulls too! } private Object tryPolymorphicParent(String parentTable){ MetaModel parentMM = inferTargetMetaModel(parentTable); if(parentMM == null){ return null; }else return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToPolymorphicAssociation.class) ? parent(parentMM.getModelClass()): null; } private Object tryParent(String parentTable){ MetaModel parentMM = inferTargetMetaModel(parentTable); if(parentMM == null){ return null; }else return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToAssociation.class) ? parent(parentMM.getModelClass()): null; } private Object tryPolymorphicChildren(String childTable){ MetaModel childMM = inferTargetMetaModel(childTable); if(childMM == null){ return null; }else return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyPolymorphicAssociation.class) ? getAll(childMM.getModelClass()): null; } private Object tryChildren(String childTable){ MetaModel childMM = inferTargetMetaModel(childTable); if(childMM == null){ return null; }else return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyAssociation.class) ? getAll(childMM.getModelClass()): null; } private Object tryOther(String otherTable){ MetaModel otherMM = inferTargetMetaModel(otherTable); if(otherMM == null){ return null; }else return getMetaModelLocal().hasAssociation(otherMM.getTableName(), Many2ManyAssociation.class) ? getAll(otherMM.getModelClass()): null; } private MetaModel inferTargetMetaModel(String targetTableName){ String targetTable = singularize(targetTableName); MetaModel targetMM = Registry.instance().getMetaModel(targetTable); if(targetMM == null){ targetTable = pluralize(targetTableName); targetMM = Registry.instance().getMetaModel(targetTable); } return targetMM != null? targetMM: null; } /*************************** typed getters *****************************************/ /** * Gets attribute value as <code>String</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.String</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toString(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>String</code> */ public String getString(String attributeName) { Object value = getRaw(attributeName); Converter<Object, String> converter = modelRegistryLocal().converterForValue(attributeName, value, String.class); return converter != null ? converter.convert(value) : Convert.toString(value); } /** * Gets a value as bytes. If the column is Blob, bytes are * read directly, if not, then the value is converted to String first, then * string bytes are returned. Be careful out there, this will read entire * Blob onto memory. * * @param attributeName name of attribute * @return value as bytes. */ //TODO: use converters here? public byte[] getBytes(String attributeName) { Object value = get(attributeName); return Convert.toBytes(value); } /** * Gets attribute value as <code>java.math.BigDecimal</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.math.BigDecimal</code>, given the attribute value is an instance of <code>S</code>, then it will be * used, otherwise performs a conversion using {@link Convert#toBigDecimal(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>java.math.BigDecimal</code> */ public BigDecimal getBigDecimal(String attributeName) { Object value = getRaw(attributeName); Converter<Object, BigDecimal> converter = modelRegistryLocal().converterForValue( attributeName, value, BigDecimal.class); return converter != null ? converter.convert(value) : Convert.toBigDecimal(value); } /** * Gets attribute value as <code>Integer</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Integer</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toInteger(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Integer</code> */ public Integer getInteger(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Integer> converter = modelRegistryLocal().converterForValue(attributeName, value, Integer.class); return converter != null ? converter.convert(value) : Convert.toInteger(value); } /** * Gets attribute value as <code>Long</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Long</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toLong(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Long</code> */ public Long getLong(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Long> converter = modelRegistryLocal().converterForValue(attributeName, value, Long.class); return converter != null ? converter.convert(value) : Convert.toLong(value); } /** * Gets attribute value as <code>Short</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Short</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toShort(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Short</code> */ public Short getShort(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Short> converter = modelRegistryLocal().converterForValue(attributeName, value, Short.class); return converter != null ? converter.convert(value) : Convert.toShort(value); } /** * Gets attribute value as <code>Float</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Float</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toFloat(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Float</code> */ public Float getFloat(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Float> converter = modelRegistryLocal().converterForValue(attributeName, value, Float.class); return converter != null ? converter.convert(value) : Convert.toFloat(value); } /** * Gets attribute value as <code>java.sql.Time</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Time</code>, given the attribute value is an instance of <code>S</code>, then it will be * used, otherwise performs a conversion using {@link Convert#toTime(Object)}. * * @param attributeName name of attribute to convert * @return instance of <code>Timestamp</code> */ public Time getTime(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Time> converter = modelRegistryLocal().converterForValue( attributeName, value, Time.class); return converter != null ? converter.convert(value) : Convert.toTime(value); } /** * Gets attribute value as <code>java.sql.Timestamp</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Timestamp</code>, given the attribute value is an instance of <code>S</code>, then it will be * used, otherwise performs a conversion using {@link Convert#toTimestamp(Object)}. * * @param attributeName name of attribute to convert * @return instance of <code>Timestamp</code> */ public Timestamp getTimestamp(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Timestamp> converter = modelRegistryLocal().converterForValue( attributeName, value, Timestamp.class); return converter != null ? converter.convert(value) : Convert.toTimestamp(value); } /** * Gets attribute value as <code>Double</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Double</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toDouble(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Double</code> */ public Double getDouble(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Double> converter = modelRegistryLocal().converterForValue(attributeName, value, Double.class); return converter != null ? converter.convert(value) : Convert.toDouble(value); } /** * Gets attribute value as <code>Boolean</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Boolean</code>, given the attribute value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toBoolean(Object)}. * * @param attributeName name of attribute to convert * @return value converted to <code>Boolean</code> */ public Boolean getBoolean(String attributeName) { Object value = getRaw(attributeName); Converter<Object, Boolean> converter = modelRegistryLocal().converterForValue(attributeName, value, Boolean.class); return converter != null ? converter.convert(value) : Convert.toBoolean(value); } /*************************** typed setters *****************************************/ /** * Sets attribute value as <code>String</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.String</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toString(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setString(String attributeName, Object value) { Converter<Object, String> converter = modelRegistryLocal().converterForValue(attributeName, value, String.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toString(value)); } /** * Sets attribute value as <code>java.math.BigDecimal</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.math.BigDecimal</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toBigDecimal(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setBigDecimal(String attributeName, Object value) { Converter<Object, BigDecimal> converter = modelRegistryLocal().converterForValue( attributeName, value, BigDecimal.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBigDecimal(value)); } /** * Sets attribute value as <code>Short</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Short</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toShort(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setShort(String attributeName, Object value) { Converter<Object, Short> converter = modelRegistryLocal().converterForValue(attributeName, value, Short.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toShort(value)); } /** * Sets attribute value as <code>Integer</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Integer</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toInteger(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setInteger(String attributeName, Object value) { Converter<Object, Integer> converter = modelRegistryLocal().converterForValue(attributeName, value, Integer.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toInteger(value)); } /** * Sets attribute value as <code>Long</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Long</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toLong(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setLong(String attributeName, Object value) { Converter<Object, Long> converter = modelRegistryLocal().converterForValue(attributeName, value, Long.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toLong(value)); } /** * Sets attribute value as <code>Float</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Float</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toFloat(Object)}. * * @param attributeName name of attribute. * @param value value to convert. * @return reference to this model. */ public <T extends Model> T setFloat(String attributeName, Object value) { Converter<Object, Float> converter = modelRegistryLocal().converterForValue(attributeName, value, Float.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toFloat(value)); } /** * Sets attribute value as <code>java.sql.Time</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Time</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toTime(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setTime(String attributeName, Object value) { Converter<Object, Time> converter = modelRegistryLocal().converterForValue( attributeName, value, Time.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toTime(value)); } /** * Sets attribute value as <code>java.sql.Timestamp</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.sql.Timestamp</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toTimestamp(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setTimestamp(String attributeName, Object value) { Converter<Object, Timestamp> converter = modelRegistryLocal().converterForValue( attributeName, value, Timestamp.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toTimestamp(value)); } /** * Sets attribute value as <code>Double</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Double</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toDouble(Object)}. * * @param attributeName name of attribute. * @param value value to convert. * @return reference to this model. */ public <T extends Model> T setDouble(String attributeName, Object value) { Converter<Object, Double> converter = modelRegistryLocal().converterForValue(attributeName, value, Double.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toDouble(value)); } /** * Sets attribute value as <code>Boolean</code>. * If there is a {@link Converter} registered for the attribute that converts from Class <code>S</code> to Class * <code>java.lang.Boolean</code>, given the value is an instance of <code>S</code>, then it will be used, * otherwise performs a conversion using {@link Convert#toBoolean(Object)}. * * @param attributeName name of attribute. * @param value value * @return reference to this model. */ public <T extends Model> T setBoolean(String attributeName, Object value) { Converter<Object, Boolean> converter = modelRegistryLocal().converterForValue(attributeName, value, Boolean.class); return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBoolean(value)); } /** * This methods supports one to many, many to many relationships as well as polymorphic associations. * <p/> * In case of one to many, the <code>clazz</code> must be a class of a child model, and it will return a * collection of all children. * <p/> * In case of many to many, the <code>clazz</code> must be a class of a another related model, and it will return a * collection of all related models. * <p/> * In case of polymorphic, the <code>clazz</code> must be a class of a polymorphically related model, and it will return a * collection of all related models. * * * @param clazz class of a child model for one to many, or class of another model, in case of many to many or class of child in case of * polymorphic * * @return list of children in case of one to many, or list of other models, in case many to many. */ public <C extends Model> LazyList<C> getAll(Class<C> clazz) { List<Model> children = cachedChildren.get(clazz); if(children != null){ return (LazyList<C>) children; } String tableName = Registry.instance().getTableName(clazz); if(tableName == null) throw new IllegalArgumentException("table: " + tableName + " does not exist for model: " + clazz); return get(tableName, null); } /** * Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list * by criteria. * * <p/> * <strong>1.</strong> For one to many, the criteria is against the child table. * * <p/> * <strong>2.</strong> For polymorphic association, the criteria is against the child table. * * <p/> * <strong>3.</strong> For many to many, the criteria is against the join table. * For example, if you have table PROJECTS, ASSIGNMENTS and PROGRAMMERS, where a project has many programmers and a programmer * has many projects, and ASSIGNMENTS is a join table, you can write code like this, assuming that the ASSIGNMENTS table * has a column <code>duration_weeks</code>: * * <pre> * List<Project> threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3); * </pre> * where this list will contain all projects to which this programmer is assigned for 3 weeks. * * @param clazz related type * @param query sub-query for join table. * @param params parameters for a sub-query * @return list of relations in many to many */ public <C extends Model> LazyList<C> get(Class<C> clazz, String query, Object ... params){ return get(Registry.instance().getTableName(clazz), query, params); } private <C extends Model> LazyList<C> get(String targetTable, String criteria, Object ...params) { //TODO: interesting thought: is it possible to have two associations of the same name, one to many and many to many? For now, say no. OneToManyAssociation oneToManyAssociation = getMetaModelLocal().getAssociationForTarget( targetTable, OneToManyAssociation.class); Many2ManyAssociation manyToManyAssociation = getMetaModelLocal().getAssociationForTarget( targetTable, Many2ManyAssociation.class); OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = getMetaModelLocal().getAssociationForTarget( targetTable, OneToManyPolymorphicAssociation.class); String additionalCriteria = criteria != null? " AND ( " + criteria + " ) " : ""; String subQuery; if (oneToManyAssociation != null) { subQuery = oneToManyAssociation.getFkName() + " = ? " + additionalCriteria; } else if (manyToManyAssociation != null) { String targetId = Registry.instance().getMetaModel(targetTable).getIdName(); String joinTable = manyToManyAssociation.getJoin(); String query = "SELECT " + targetTable + ".* FROM " + targetTable + ", " + joinTable + " WHERE " + targetTable + "." + targetId + " = " + joinTable + "." + manyToManyAssociation.getTargetFkName() + " AND " + joinTable + "." + manyToManyAssociation.getSourceFkName() + " = ? " + additionalCriteria; Object[] allParams = new Object[params.length + 1]; allParams[0] = getId(); System.arraycopy(params, 0, allParams, 1, params.length); return new LazyList<C>(true, Registry.instance().getMetaModel(targetTable), query, allParams); } else if (oneToManyPolymorphicAssociation != null) { subQuery = "parent_id = ? AND " + " parent_type = '" + oneToManyPolymorphicAssociation.getTypeLabel() + "'" + additionalCriteria; } else { throw new NotAssociatedException(getMetaModelLocal().getTableName(), targetTable); } Object[] allParams = new Object[params.length + 1]; allParams[0] = getId(); System.arraycopy(params, 0, allParams, 1, params.length); return new LazyList<C>(subQuery, Registry.instance().getMetaModel(targetTable), allParams); } protected static NumericValidationBuilder validateNumericalityOf(String... attributeNames) { return ModelDelegate.validateNumericalityOf(modelClass(), attributeNames); } /** * Adds a validator to the model. * * @param validator new validator. */ public static ValidationBuilder addValidator(Validator validator) { return ModelDelegate.validateWith(modelClass(), validator); } /** * Adds a new error to the collection of errors. This is a convenience method to be used from custom validators. * * @param key - key wy which this error can be retrieved from a collection of errors: {@link #errors()}. * @param value - this is a key of the message in the resource bundle. * @see {@link Messages}. */ public void addError(String key, String value){ errors.put(key, value); } /** * Removes a validator from model. * * @param validator validator to remove. It needs to be an exact reference validator instance to * remove. If argument was not added to this model before, this method will * do nothing. */ public static void removeValidator(Validator validator){ ModelDelegate.removeValidator(modelClass(), validator); } //TODO: missing no-arg getValidators()? public static List<Validator> getValidators(Class<? extends Model> clazz) { return ModelDelegate.validatorsOf(clazz); } /** * Validates an attribite format with a ree hand regular expression. * * @param attributeName attribute to validate. * @param pattern regexp pattern which must match the value. * @return */ protected static ValidationBuilder validateRegexpOf(String attributeName, String pattern) { return ModelDelegate.validateRegexpOf(modelClass(), attributeName, pattern); } /** * Validates email format. * * @param attributeName name of attribute that holds email value. * @return */ protected static ValidationBuilder validateEmailOf(String attributeName) { return ModelDelegate.validateEmailOf(modelClass(), attributeName); } /** * Validates range. Accepted types are all java.lang.Number subclasses: * Byte, Short, Integer, Long, Float, Double BigDecimal. * * @param attributeName attribute to validate - should be within range. * @param min min value of range. * @param max max value of range. * @return */ protected static ValidationBuilder validateRange(String attributeName, Number min, Number max) { return ModelDelegate.validateRange(modelClass(), attributeName, min, max); } /** * The validation will not pass if the value is either an empty string "", or null. * * @param attributeNames list of attributes to validate. * @return */ protected static ValidationBuilder validatePresenceOf(String... attributeNames) { return ModelDelegate.validatePresenceOf(modelClass(), attributeNames); } /** * Add a custom validator to the model. * * @param validator custom validator. */ protected static ValidationBuilder validateWith(Validator validator) { return ModelDelegate.validateWith(modelClass(), validator); } /** * Adds a custom converter to the model. * * @param converter custom converter * @deprecated use {@link #convertWith(org.javalite.activejdbc.conversion.Converter, String...)} instead */ @Deprecated protected static ValidationBuilder convertWith(org.javalite.activejdbc.validation.Converter converter) { return ModelDelegate.convertWith(modelClass(), converter); } /** * Registers a custom converter for the specified attributes. * * @param converter custom converter * @param attributeNames attribute names */ protected static void convertWith(Converter converter, String... attributeNames) { ModelDelegate.convertWith(modelClass(), converter, attributeNames); } /** * Converts a named attribute to <code>java.sql.Date</code> if possible. * Acts as a validator if cannot make a conversion. * * @param attributeName name of attribute to convert to <code>java.sql.Date</code>. * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} * @return message passing for custom validation message. * @deprecated use {@link #dateFormat(String, String...) instead */ @Deprecated protected static ValidationBuilder convertDate(String attributeName, String format){ return ModelDelegate.convertDate(modelClass(), attributeName, format); } /** * Converts a named attribute to <code>java.sql.Timestamp</code> if possible. * Acts as a validator if cannot make a conversion. * * @param attributeName name of attribute to convert to <code>java.sql.Timestamp</code>. * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} * @return message passing for custom validation message. * @deprecated use {@link #timestampFormat(String, String...) instead */ @Deprecated protected static ValidationBuilder convertTimestamp(String attributeName, String format){ return ModelDelegate.convertTimestamp(modelClass(), attributeName, format); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Date when using the appropriate getters and setters. * * <p>For example: * <blockquote><pre> * public class Person extends Model { * static { * dateFormat("MM/dd/yyyy", "dob"); * } * } * * Person p = new Person(); * // will convert String -> java.sql.Date * p.setDate("dob", "02/29/2000"); * // will convert Date -> String, if dob value in model is of type Date * String str = p.getString("dob"); * * // will convert Date -> String * p.setString("dob", new Date()); * // will convert String -> java.sql.Date, if dob value in model is of type String * Date date = p.getDate("dob"); * </pre></blockquote> * * @param pattern pattern to use for conversion * @param attributeNames attribute names */ protected static void dateFormat(String pattern, String... attributeNames) { ModelDelegate.dateFormat(modelClass(), pattern, attributeNames); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Date when using the appropriate getters and setters. * * <p>See example in {@link #dateFormat(String, String...)}. * * @param format format to use for conversion * @param attributeNames attribute names */ protected static void dateFormat(DateFormat format, String... attributeNames) { ModelDelegate.dateFormat(modelClass(), format, attributeNames); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Timestamp when using the appropriate getters and setters. * * <p>For example: * <blockquote><pre> * public class Person extends Model { * static { * timestampFormat("MM/dd/yyyy hh:mm a", "birth_datetime"); * } * } * * Person p = new Person(); * // will convert String -> java.sql.Timestamp * p.setTimestamp("birth_datetime", "02/29/2000 12:07 PM"); * // will convert Date -> String, if dob value in model is of type Date or java.sql.Timestamp * String str = p.getString("birth_datetime"); * * // will convert Date -> String * p.setString("birth_datetime", new Date()); * // will convert String -> java.sql.Timestamp, if dob value in model is of type String * Timestamp ts = p.getTimestamp("birth_datetime"); * </pre></blockquote> * * @param pattern pattern to use for conversion * @param attributeNames attribute names */ protected static void timestampFormat(String pattern, String... attributeNames) { ModelDelegate.timestampFormat(modelClass(), pattern, attributeNames); } /** * Registers date format for specified attributes. This format will be used to convert between * Date -> String -> java.sql.Timestamp when using the appropriate getters and setters. * * <p>See example in {@link #timestampFormat(String, String...)}. * * @param format format to use for conversion * @param attributeNames attribute names */ protected static void timestampFormat(DateFormat format, String... attributeNames) { ModelDelegate.timestampFormat(modelClass(), format, attributeNames); } /** * Registers {@link BlankToNullConverter} for specified attributes. This will convert instances of <tt>String</tt> * that are empty or contain only whitespaces to <tt>null</tt>. * * @param attributeNames attribute names */ protected static void blankToNull(String... attributeNames) { ModelDelegate.blankToNull(modelClass(), attributeNames); } /** * Registers {@link ZeroToNullConverter} for specified attributes. This will convert instances of <tt>Number</tt> * that are zero to <tt>null</tt>. * * @param attributeNames attribute names */ protected static void zeroToNull(String... attributeNames) { ModelDelegate.zeroToNull(modelClass(), attributeNames); } public static boolean belongsTo(Class<? extends Model> targetClass) { return ModelDelegate.belongsTo(modelClass(), targetClass); } /** * @deprecated use {@link #callbackWith(CallbackListener...)} instead */ @Deprecated public static void addCallbacks(CallbackListener... listeners) { ModelDelegate.callbackWith(modelClass(), listeners); } public static void callbackWith(CallbackListener... listeners) { ModelDelegate.callbackWith(modelClass(), listeners); } /** * This method performs validations and then returns true if no errors were generated, otherwise returns false. * * @return true if no errors were generated, otherwise returns false. */ public boolean isValid(){ validate(); return !hasErrors(); } /** * Executes all validators attached to this model. */ public void validate() { fireBeforeValidation(); errors = new Errors(); List<Validator> validators = modelRegistryLocal().validators(); if (validators != null) { for (Validator validator : validators) { validator.validate(this); } } fireAfterValidation(); } public boolean hasErrors() { return errors != null && errors.size() > 0; } /** * Binds a validator to an attribute if validation fails. * * @param errorKey key of error in errors map. Usually this is a name of attribute, * but not limited to that, can be anything. * * @param validator -validator that failed validation. */ public void addValidator(Validator validator, String errorKey) { if(!errors.containsKey(errorKey)) errors.addValidator(errorKey, validator); } /** * Provides an instance of <code>Errors</code> object, filled with error messages after validation. * * @return an instance of <code>Errors</code> object, filled with error messages after validation. */ public Errors errors() { return errors; } /** * Provides an instance of localized <code>Errors</code> object, filled with error messages after validation. * * @param locale locale. * @return an instance of localized <code>Errors</code> object, filled with error messages after validation. */ public Errors errors(Locale locale) { errors.setLocale(locale); return errors; } /** * This is a convenience method to create a model instance already initialized with values. * Example: * <pre> * Person p = Person.create("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07"); * </pre> * * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every * other is a corresponding value. * * This allows for better readability of code. If you just read this aloud, it will become clear. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model. */ public static <T extends Model> T create(Object... namesAndValues) { return ModelDelegate.create(Model.<T>modelClass(), namesAndValues); } /** * This is a convenience method to set multiple values to a model. * Example: * <pre> * Person p = ... * Person p = p.set("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07"); * </pre> * * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every * other is a corresponding value. * * This allows for better readability of code. If you just read this aloud, it will become clear. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model. */ public <T extends Model> T set(Object... namesAndValues) { if (namesAndValues.length % 2 != 0) { throw new IllegalArgumentException("number of arguments must be even"); } for (int i = 0; i < namesAndValues.length; ) { if (namesAndValues[i] == null) { throw new IllegalArgumentException("attribute names cannot be null"); } set(namesAndValues[i++].toString(), namesAndValues[i++]); } return (T) this; } /** * This is a convenience method to {@link #create(Object...)}. It will create a new model and will save it * to DB. It has the same semantics as {@link #saveIt()}. * * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. * @return newly instantiated model which also has been saved to DB. */ public static <T extends Model> T createIt(Object ... namesAndValues){ return ModelDelegate.createIt(Model.<T>modelClass(), namesAndValues); } public static <T extends Model> T findById(Object id) { return ModelDelegate.findById(Model.<T>modelClass(), id); } /** * Composite PK values in exactly the same order as specified in {@link CompositePK}. * * @param values Composite PK values in exactly the same order as specified in {@link CompositePK}. * @return instance of a found model, or null if nothing found. * @see CompositePK */ public static <T extends Model> T findByCompositeKeys(Object... values) { return ModelDelegate.findByCompositeKeys(Model.<T>modelClass(), values); } /** * Finder method for DB queries based on table represented by this model. Usually the SQL starts with: * * <code>"select * from table_name where " + subquery</code> where table_name is a table represented by this model. * * Code example: * <pre> * * List<Person> teenagers = Person.where("age &gt ? and age &lt ?", 12, 20); * // iterate... * * //same can be achieved (since parameters are optional): * List<Person> teenagers = Person.where("age &gt 12 and age &lt 20"); * //iterate * </pre> * * Limit, offset and order by can be chained like this: * * <pre> * List<Person> teenagers = Person.where("age &gt ? and age &lt ?", 12, 20).offset(101).limit(20).orderBy(age); * //iterate * </pre> * * This is a great way to build paged applications. * * * @param subquery this is a set of conditions that normally follow the "where" clause. Example: * <code>"department = ? and dob > ?"</code>. If this value is "*" and no parameters provided, then {@link #findAll()} is executed. * @param params list of parameters corresponding to the place holders in the subquery. * @return instance of <code>LazyList<Model></code> containing results. */ public static <T extends Model> LazyList<T> where(String subquery, Object... params) { return ModelDelegate.where(Model.<T>modelClass(), subquery, params); } /** * Synonym of {@link #where(String, Object...)} * * @param subquery this is a set of conditions that normally follow the "where" clause. Example: * <code>"department = ? and dob &gt ?"</code>. If this value is "*" and no parameters provided, then {@link #findAll()} is executed. * @param params list of parameters corresponding to the place holders in the subquery. * @return instance of <code>LazyList<Model></code> containing results. */ public static <T extends Model> LazyList<T> find(String subquery, Object... params) { return ModelDelegate.where(Model.<T>modelClass(), subquery, params); } /** * Synonym of {@link #first(String, Object...)}. * * @param subQuery selection criteria, example: * <pre> * Person johnTheTeenager = Person.findFirst("name = ? and age &gt 13 and age &lt 19 order by age", "John") * </pre> * Sometimes a query might be just a clause like this: * <pre> * Person oldest = Person.findFirst("order by age desc") * </pre> * @param params list of parameters if question marks are used as placeholders * @return a first result for this condition. May return null if nothing found. */ public static <T extends Model> T findFirst(String subQuery, Object... params) { return ModelDelegate.findFirst(Model.<T>modelClass(), subQuery, params); } /** * Returns a first result for this condition. May return null if nothing found. * If last result is needed, then order by some field and call this nethod: * * Synonym of {@link #findFirst(String, Object...)}. * <pre> * //first: * Person youngestTeenager= Person.first("age &gt 12 and age &lt 20 order by age"); * * //last: * Person oldestTeenager= Person.first("age &gt 12 and age &lt 20 order by age desc"); * </pre> * * * @param subQuery selection criteria, example: * <pre> * Person johnTheTeenager = Person.first("name = ? and age &lt 13 order by age", "John") * </pre> * Sometimes a query might be just a clause like this: * <pre> * Person p = Person.first("order by age desc") * </pre> * @param params list of parameters if question marks are used as placeholders * @return a first result for this condition. May return null if nothing found. */ public static <T extends Model> T first(String subQuery, Object... params) { return ModelDelegate.findFirst(Model.<T>modelClass(), subQuery, params); } /** * This method is for processing really large result sets. Results found by this method are never cached. * * @param query query text. * @param listener this is a call back implementation which will receive instances of models found. * @deprecated use {@link #findWith(ModelListener, String, Object...)}. */ @Deprecated public static void find(String query, final ModelListener listener) { ModelDelegate.findWith(modelClass(), listener, query); } /** * This method is for processing really large result sets. Results found by this method are never cached. * * @param listener this is a call back implementation which will receive instances of models found. * @param query sub-query (content after "WHERE" clause) * @param params optional parameters for a query. */ public static void findWith(final ModelListener listener, String query, Object ... params) { ModelDelegate.findWith(modelClass(), listener, query, params); } /** * Free form query finder. Example: * <pre> * List<Rule> rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc"); * </pre> * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate itself properly. * Returned columns that are not part of this model will be ignored, but can be used for caluses like above. * * @param fullQuery free-form SQL. * @param params parameters if query is parametrized. * @param <T> - class that extends Model. * @return list of models representing result set. */ public static <T extends Model> LazyList<T> findBySQL(String fullQuery, Object... params) { return ModelDelegate.findBySql(Model.<T>modelClass(), fullQuery, params); } /** * This method returns all records from this table. If you need to get a subset, look for variations of "find()". * * @return result list */ public static <T extends Model> LazyList<T> findAll() { return ModelDelegate.findAll(Model.<T>modelClass()); } /** * Adds a new child dependency. This method works for all three association types: * <ul> * <li>One to many - argument model should be a child in the relationship. This method will immediately set it's * ID as a foreign key on the child and will then save the child.</li> * <li>Many to many - argument model should be the other model in the relationship. This method will check if the * added child already has an ID. If the child does have an ID, then the method will create a link in the join * table. If the child does not have an ID, then this method saves the child first, then creates a record in the * join table linking this model instance and the child instance.</li> * <li>Polymorphic - argument model should be a polymorphic child of this model. This method will set the * <code>parent_id</code> and <code>parent_type</code> as appropriate and then will then save the child.</li> * </ul> * * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. * * @param child instance of a model that has a relationship to the current model. * Either one to many or many to many relationships are accepted. */ public void add(Model child) { if(child == null) throw new IllegalArgumentException("cannot add what is null"); //TODO: refactor this method String childTable = Registry.instance().getTableName(child.getClass()); MetaModel metaModel = getMetaModelLocal(); if (getId() != null) { if (metaModel.hasAssociation(childTable, OneToManyAssociation.class)) { OneToManyAssociation ass = metaModel.getAssociationForTarget(childTable, OneToManyAssociation.class); String fkName = ass.getFkName(); child.set(fkName, getId()); child.saveIt();//this will cause an exception in case validations fail. }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ Many2ManyAssociation ass = metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); if (child.getId() == null) { child.saveIt(); } MetaModel joinMetaModel = Registry.instance().getMetaModel(ass.getJoin()); if (joinMetaModel == null) { new DB(metaModel.getDbName()).exec(metaModel.getDialect().insertManyToManyAssociation(ass), getId(), child.getId()); } else { //TODO: write a test to cover this case: //this is for Oracle, many 2 many, and all annotations used, including @IdGenerator. In this case, //it is best to delegate generation of insert to a model (sequences, etc.) try { Model joinModel = joinMetaModel.getModelClass().newInstance(); joinModel.set(ass.getSourceFkName(), getId()); joinModel.set(ass.getTargetFkName(), child.getId()); joinModel.saveIt(); } catch (InstantiationException e) { throw new InitException("failed to create a new instance of class: " + joinMetaModel.getClass() + ", are you sure this class has a default constructor?", e); } catch (IllegalAccessException e) { throw new InitException(e); } finally { QueryCache.instance().purgeTableCache(ass.getJoin()); QueryCache.instance().purgeTableCache(metaModel.getTableName()); QueryCache.instance().purgeTableCache(childTable); } } } else if(metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { OneToManyPolymorphicAssociation ass = metaModel.getAssociationForTarget( childTable, OneToManyPolymorphicAssociation.class); child.set("parent_id", getId()); child.set("parent_type", ass.getTypeLabel()); child.saveIt(); }else throw new NotAssociatedException(metaModel.getTableName(), childTable); } else { throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. Save this instance first, then you will be able to add dependencies to it."); } } /** * Removes associated child from this instance. The child model should be either in belongs to association (including polymorphic) to this model * or many to many association. * * <h3>One to many and polymorphic associations</h3> * This method will simply call <code>child.delete()</code> method. This will render the child object frozen. * * <h3>Many to many associations</h3> * This method will remove an associated record from the join table, and will do nothing to the child model or record. * * <p/> * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. * * @param child model representing a "child" as in one to many or many to many association with this model. * @return number of records affected */ public int remove(Model child) { if (child == null) { throw new IllegalArgumentException("cannot remove what is null"); } if (child.frozen() || child.getId() == null) { throw new IllegalArgumentException( "Cannot remove a child that does not exist in DB (either frozen, or ID not set)"); } if (getId() != null) { String childTable = Registry.instance().getTableName(child.getClass()); MetaModel metaModel = getMetaModelLocal(); if (metaModel.hasAssociation(childTable, OneToManyAssociation.class) || metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { child.delete(); return 1; } else if (metaModel.hasAssociation(childTable, Many2ManyAssociation.class)) { return new DB(metaModel.getDbName()).exec(metaModel.getDialect().deleteManyToManyAssociation( metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class)), getId(), child.getId()); } else { throw new NotAssociatedException(metaModel.getTableName(), childTable); } } else { throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. " + "Save this instance first, then you will be able to add dependencies to it."); } } /** * This method will not exit silently like {@link #save()}, it instead will throw {@link org.javalite.activejdbc.validation.ValidationException} * if validations did not pass. * * @return true if the model was saved, false if you set an ID value for the model, but such ID does not exist in DB. */ public boolean saveIt() { boolean result = save(); ModelDelegate.purgeEdges(getMetaModelLocal()); if (!errors.isEmpty()) { throw new ValidationException(this); } return result; } /** * Resets all data in this model, including the ID. * After this method, this instance is equivalent to an empty, just created instance. */ public void reset() { attributes = new CaseInsensitiveMap<Object>(); } /** * Unfreezes this model. After this method it is possible again to call save() and saveIt() methods. * This method will erase the value of ID on this instance, while preserving all other attributes' values. * * If a record was deleted, it is frozen and cannot be saved. After it is thawed, it can be saved again, but it will * generate a new insert statement and create a new record in the table with all the same attribute values. * * <p/><p/> * Synonym for {@link #defrost()}. */ public void thaw(){ attributes.put(getIdName(), null); compositeKeyPersisted = false; dirtyAttributeNames.addAll(attributes.keySet()); frozen = false; } /** * Synonym for {@link #thaw()}. */ public void defrost(){ thaw(); } /** * This method will save data from this instance to a corresponding table in the DB. * It will generate insert SQL if the model is new, or update if the model exists in the DB. * This method will execute all associated validations and if those validations generate errors, * these errors are attached to this instance. Errors are available by {#link #errors() } method. * The <code>save()</code> method is mostly for web applications, where code like this is written: * <pre> * if(person.save()) * //show page success * else{ * request.setAttribute("errors", person.errors()); * //show errors page, or same page so that user can correct errors. * } * </pre> * * In other words, this method will not throw validation exceptions. However, if there is a problem in the DB, then * there can be a runtime exception thrown. * * @return true if a model was saved and false if values did not pass validations and the record was not saved. * False will also be returned if you set an ID value for the model, but such ID does not exist in DB. */ public boolean save() { if(frozen) throw new FrozenException(this); fireBeforeSave(); validate(); if (hasErrors()) { return false; } boolean result; if (getId() == null && !compositeKeyPersisted) { result = insert(); } else { result = update(); } fireAfterSave(); return result; } /** * Returns total count of records in table. * * @return total count of records in table. */ public static Long count() { return ModelDelegate.count(modelClass()); } /** * Returns count of records in table under a condition. * * @param query query to select records to count. * @param params parameters (if any) for the query. * @return count of records in table under a condition. */ public static Long count(String query, Object... params) { return ModelDelegate.count(modelClass(), query, params); } /** * This method will save a model as new. In other words, it will not try to guess if this is a * new record or a one that exists in the table. It does not have "belt and suspenders", it will * simply generate and execute insert statement, assuming that developer knows what he/she is doing. * * @return true if model was saved, false if not */ public boolean insert() { fireBeforeCreate(); //TODO: fix this as created_at and updated_at attributes will be set even if insertion failed doCreatedAt(); doUpdatedAt(); MetaModel metaModel = getMetaModelLocal(); List<String> columns = new ArrayList<String>(); List<Object> values = new ArrayList<Object>(); for (Map.Entry<String, Object> entry : attributes.entrySet()) { if (entry.getValue() == null || metaModel.getVersionColumn().equals(entry.getKey())) { continue; } columns.add(entry.getKey()); values.add(entry.getValue()); } if (metaModel.isVersioned()) { columns.add(metaModel.getVersionColumn()); values.add(1); } //TODO: need to invoke checkAttributes here too, and maybe rely on MetaModel for this. try { boolean containsId = (attributes.get(metaModel.getIdName()) != null); // do not use containsKey boolean done; String query = metaModel.getDialect().insertParametrized(metaModel, columns, containsId); if (containsId || getCompositeKeys() != null) { compositeKeyPersisted = done = (1 == new DB(metaModel.getDbName()).exec(query, values.toArray())); } else { Object id = new DB(metaModel.getDbName()).execInsert(query, metaModel.getIdName(), values.toArray()); attributes.put(metaModel.getIdName(), id); done = (id != null); } if (metaModel.cached()) { QueryCache.instance().purgeTableCache(metaModel.getTableName()); } if (metaModel.isVersioned()) { attributes.put(metaModel.getVersionColumn(), 1); } dirtyAttributeNames.clear(); // Clear all dirty attribute names as all were inserted. What about versionColumn ? fireAfterCreate(); return done; } catch (DBException e) { throw e; } catch (Exception e) { throw new DBException(e.getMessage(), e); } } private void doCreatedAt() { if (manageTime && getMetaModelLocal().hasAttribute("created_at")) { attributes.put("created_at", new Timestamp(System.currentTimeMillis())); } } private void doUpdatedAt() { if (manageTime && getMetaModelLocal().hasAttribute("updated_at")) { attributes.put("updated_at", new Timestamp(System.currentTimeMillis())); } } private boolean update() { fireBeforeUpdate(); doUpdatedAt(); MetaModel metaModel = getMetaModelLocal(); StringBuilder query = new StringBuilder().append("UPDATE ").append(metaModel.getTableName()).append(" SET "); Set<String> attributeNames = metaModel.getAttributeNamesSkipGenerated(manageTime); attributeNames.retainAll(dirtyAttributeNames); if(attributeNames.size() > 0) { join(query, attributeNames, " = ?, "); query.append(" = ?"); } List<Object> values = getAttributeValues(attributeNames); if (manageTime && metaModel.hasAttribute("updated_at")) { if(values.size() > 0) query.append(", "); query.append("updated_at = ?"); values.add(get("updated_at")); } if(metaModel.isVersioned()){ if(values.size() > 0) query.append(", "); query.append(getMetaModelLocal().getVersionColumn()).append(" = ?"); values.add(getLong(getMetaModelLocal().getVersionColumn()) + 1); } if(values.isEmpty()) return false; if (getCompositeKeys() != null) { String[] compositeKeys = getCompositeKeys(); for (int i = 0; i < compositeKeys.length; i++) { query.append(i == 0 ? " WHERE " : " AND ").append(compositeKeys[i]).append(" = ?"); values.add(get(compositeKeys[i])); } } else { query.append(" WHERE ").append(metaModel.getIdName()).append(" = ?"); values.add(getId()); } if (metaModel.isVersioned()) { query.append(" AND ").append(getMetaModelLocal().getVersionColumn()).append(" = ?"); values.add(get(getMetaModelLocal().getVersionColumn())); } int updated = new DB(metaModel.getDbName()).exec(query.toString(), values.toArray()); if(metaModel.isVersioned() && updated == 0){ throw new StaleModelException("Failed to update record for model '" + getClass() + "', with " + getIdName() + " = " + getId() + " and " + getMetaModelLocal().getVersionColumn() + " = " + get(getMetaModelLocal().getVersionColumn()) + ". Either this record does not exist anymore, or has been updated to have another " + getMetaModelLocal().getVersionColumn() + '.'); }else if(metaModel.isVersioned()){ set(getMetaModelLocal().getVersionColumn(), getLong(getMetaModelLocal().getVersionColumn()) + 1); } if(metaModel.cached()){ QueryCache.instance().purgeTableCache(metaModel.getTableName()); } dirtyAttributeNames.clear(); fireAfterUpdate(); return updated > 0; } private List<Object> getAttributeValues(Set<String> attributeNames) { List<Object> values = new ArrayList<Object>(); for (String attribute : attributeNames) { values.add(get(attribute)); } return values; } private static <T extends Model> Class<T> modelClass() { throw new InitException("failed to determine Model class name, are you sure models have been instrumented?"); } /** * Returns name of corresponding table. * * @return name of corresponding table. */ public static String getTableName() { return ModelDelegate.tableNameOf(modelClass()); } /** * Value of ID. * * @return of ID. */ public Object getId() { return get(getIdName()); } /** * Name of ID column. * * @return Name of ID column. */ public String getIdName() { return getMetaModelLocal().getIdName(); } /** * Provides a list of composite keys as specified in {@link CompositePK}. * * @return a list of composite keys as specified in {@link CompositePK}. */ public String[] getCompositeKeys() { return getMetaModelLocal().getCompositeKeys(); } protected void setChildren(Class childClass, List<Model> children) { cachedChildren.put(childClass, children); } /** * Turns off automatic management of time-related attributes <code>created_at</code> and <code>updated_at</code>. * If management of time attributes is turned off, * * @param manage if true, the attributes are managed by the model. If false, they are managed by developer. */ public void manageTime(boolean manage) { this.manageTime = manage; } /** * Generates INSERT SQL based on this model. Uses the dialect associated with this model database to format the * value literals. * Example: * <pre> * String sql = user.toInsert(); * //yields this output: * //INSERT INTO users (id, email, first_name, last_name) VALUES (1, '[email protected]', 'Marilyn', 'Monroe') * </pre> * * @return INSERT SQL based on this model. */ public String toInsert() { return toInsert(getMetaModelLocal().getDialect()); } /** * Generates INSERT SQL based on this model with the provided dialect. * Example: * <pre> * String sql = user.toInsert(new MySQLDialect()); * //yields this output: * //INSERT INTO users (id, email, first_name, last_name) VALUES (1, '[email protected]', 'Marilyn', 'Monroe') * </pre> * * @param dialect dialect to be used to generate the SQL * @return INSERT SQL based on this model. */ public String toInsert(Dialect dialect) { return dialect.insert(getMetaModelLocal(), attributes); } /** * Generates UPDATE SQL based on this model. Uses the dialect associated with this model database to format the * value literals. * Example: * <pre> * String sql = user.toUpdate(); * //yields this output: * //UPDATE users SET email = '[email protected]', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1 * </pre> * * @return UPDATE SQL based on this model. */ public String toUpdate() { return toUpdate(getMetaModelLocal().getDialect()); } /** * Generates UPDATE SQL based on this model with the provided dialect. * Example: * <pre> * String sql = user.toUpdate(new MySQLDialect()); * //yields this output: * //UPDATE users SET email = '[email protected]', first_name = 'Marilyn', last_name = 'Monroe' WHERE id = 1 * </pre> * * @param dialect dialect to be used to generate the SQL * @return UPDATE SQL based on this model. */ public String toUpdate(Dialect dialect) { return dialect.update(getMetaModelLocal(), attributes); } /** * Generates INSERT SQL based on this model. * For instance, for Oracle, the left quote is: "q'{" and the right quote is: "}'". * The output will also use single quotes for <code>java.sql.Timestamp</code> and <code>java.sql.Date</code> types. * * Example: * <pre> * String insert = u.toInsert("q'{", "}'"); * //yields this output * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, q'{Marilyn}', q'{[email protected]}', q'{Monroe}'); * </pre> * @param leftStringQuote - left quote for a string value, this can be different for different databases. * @param rightStringQuote - left quote for a string value, this can be different for different databases. * @return SQL INSERT string; * @deprecated Use {@link #toInsert(Dialect)} instead. */ @Deprecated public String toInsert(String leftStringQuote, String rightStringQuote){ return toInsert(new SimpleFormatter(java.sql.Date.class, "'", "'"), new SimpleFormatter(Timestamp.class, "'", "'"), new SimpleFormatter(String.class, leftStringQuote, rightStringQuote)); } /** * @param formatters * @return * @deprecated Use {@link #toInsert(Dialect)} instead. */ @Deprecated public String toInsert(Formatter... formatters){ HashMap<Class, Formatter> formatterMap = new HashMap<Class, Formatter>(); for(Formatter f: formatters){ formatterMap.put(f.getValueClass(), f); } StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO ").append(getMetaModelLocal().getTableName()).append(" ("); join(sb, attributes.keySet(), ", "); sb.append(") VALUES ("); Iterator<Object> it = attributes.values().iterator(); while (it.hasNext()) { Object value = it.next(); if (value == null) { sb.append("NULL"); } else if (value instanceof String && !formatterMap.containsKey(String.class)){ sb.append('\'').append(value).append('\''); }else{ if(formatterMap.containsKey(value.getClass())){ sb.append(formatterMap.get(value.getClass()).format(value)); }else{ sb.append(value); } } if (it.hasNext()) { sb.append(", "); } } sb.append(')'); return sb.toString(); } /** * Use to force-purge cache associated with this table. If this table is not cached, this method has no side effect. */ public static void purgeCache(){ ModelDelegate.purgeCache(modelClass()); } /** * Convenience method: converts ID value to Long and returns it. * * @return value of attribute corresponding to <code>getIdName()</code>, converted to Long. */ public Long getLongId() { Object id = getId(); if (id == null) { throw new NullPointerException(getIdName() + " is null, cannot convert to Long"); } return Convert.toLong(id); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(attributes); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { attributes = new CaseInsensitiveMap<Object>(); attributes.putAll((Map<String, Object>) in.readObject()); } }
typoes
activejdbc/src/main/java/org/javalite/activejdbc/Model.java
typoes
<ide><path>ctivejdbc/src/main/java/org/javalite/activejdbc/Model.java <ide> * <pre> <ide> * List<Rule> rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc"); <ide> * </pre> <del> * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate itself properly. <del> * Returned columns that are not part of this model will be ignored, but can be used for caluses like above. <add> * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate themselves properly. <add> * Returned columns that are not part of this model will be ignored, but can be used for clauses like above. <ide> * <ide> * @param fullQuery free-form SQL. <ide> * @param params parameters if query is parametrized.
Java
apache-2.0
b25d15db6eab89ea7217ede9b28a0f6aee924004
0
apache/maven-plugins,jdcasey/maven-plugins-fixes,restlet/maven-plugins,kidaa/maven-plugins,hgschmie/apache-maven-plugins,apache/maven-plugins,omnidavesz/maven-plugins,rkorpachyov/maven-plugins,mcculls/maven-plugins,ptahchiev/maven-plugins,sonatype/maven-plugins,Orange-OpenSource/maven-plugins,restlet/maven-plugins,PressAssociation/maven-plugins,kikinteractive/maven-plugins,PressAssociation/maven-plugins,rkorpachyov/maven-plugins,HubSpot/maven-plugins,sonatype/maven-plugins,mikkokar/maven-plugins,hazendaz/maven-plugins,criteo-forks/maven-plugins,krosenvold/maven-plugins,kidaa/maven-plugins,omnidavesz/maven-plugins,zigarn/maven-plugins,sonatype/maven-plugins,omnidavesz/maven-plugins,kikinteractive/maven-plugins,lennartj/maven-plugins,mikkokar/maven-plugins,zigarn/maven-plugins,edwardmlyte/maven-plugins,lennartj/maven-plugins,edwardmlyte/maven-plugins,HubSpot/maven-plugins,PressAssociation/maven-plugins,ptahchiev/maven-plugins,hgschmie/apache-maven-plugins,edwardmlyte/maven-plugins,kidaa/maven-plugins,dmlloyd/maven-plugins,zigarn/maven-plugins,apache/maven-plugins,criteo-forks/maven-plugins,Orange-OpenSource/maven-plugins,Orange-OpenSource/maven-plugins,Orange-OpenSource/maven-plugins,ptahchiev/maven-plugins,HubSpot/maven-plugins,apache/maven-plugins,mcculls/maven-plugins,zigarn/maven-plugins,jdcasey/maven-plugins-fixes,hazendaz/maven-plugins,hazendaz/maven-plugins,dmlloyd/maven-plugins,hgschmie/apache-maven-plugins,HubSpot/maven-plugins,rkorpachyov/maven-plugins,PressAssociation/maven-plugins,mcculls/maven-plugins,mcculls/maven-plugins,johnmccabe/maven-plugins,sonatype/maven-plugins,johnmccabe/maven-plugins,lennartj/maven-plugins,mikkokar/maven-plugins,hgschmie/apache-maven-plugins,restlet/maven-plugins,krosenvold/maven-plugins,ptahchiev/maven-plugins,edwardmlyte/maven-plugins,dmlloyd/maven-plugins,hazendaz/maven-plugins,hazendaz/maven-plugins,rkorpachyov/maven-plugins,johnmccabe/maven-plugins,kidaa/maven-plugins,johnmccabe/maven-plugins,kikinteractive/maven-plugins,rkorpachyov/maven-plugins,criteo-forks/maven-plugins,mikkokar/maven-plugins,omnidavesz/maven-plugins,jdcasey/maven-plugins-fixes,lennartj/maven-plugins,apache/maven-plugins,criteo-forks/maven-plugins,krosenvold/maven-plugins,krosenvold/maven-plugins,restlet/maven-plugins
package org.apache.maven.plugin.resources.remote; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.model.Organization; import org.apache.maven.model.Resource; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.resources.remote.io.xpp3.RemoteResourcesBundleXpp3Reader; import org.apache.maven.plugin.resources.remote.io.xpp3.SupplementalDataModelXpp3Reader; import org.apache.maven.project.InvalidProjectModelException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectUtils; import org.apache.maven.project.inheritance.ModelInheritanceAssembler; import org.apache.maven.reporting.MavenReportException; import org.apache.maven.shared.downloader.DownloadException; import org.apache.maven.shared.downloader.DownloadNotFoundException; import org.apache.maven.shared.downloader.Downloader; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.codehaus.plexus.resource.ResourceManager; import org.codehaus.plexus.resource.loader.FileResourceLoader; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.codehaus.plexus.velocity.VelocityComponent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * <p> * Pull down resourceBundles containing remote resources and process the * resources contained inside. When that is done the resources are injected * into the current (in-memory) Maven project, making them available to the * process-resources phase. * </p> * <p> * Resources that end in ".vm" are treated as velocity templates. For those, the ".vm" is * stripped off for the final artifact name and it's fed through velocity to have properties * expanded, conditions processed, etc... * </p> * <p> * Resources that don't end in ".vm" are copied "as is". * </p> * * @goal process * @requiresDependencyResolution runtime * @phase generate-resources */ public class ProcessRemoteResourcesMojo extends AbstractMojo { /** * The local repository taken from Maven's runtime. Typically $HOME/.m2/repository. * * @parameter expression="${localRepository}" */ private ArtifactRepository localRepository; /** * The remote repositories used as specified in your POM. * * @parameter expression="${project.repositories}" */ private List repositories; /** * List of Remote Repositories used by the resolver * * @parameter expression="${project.remoteArtifactRepositories}" * @readonly * @required */ private List remoteArtifactRepositories; /** * The current Maven project. * * @parameter expression="${project}" */ private MavenProject project; /** * The directory where processed resources will be placed for packaging. * * @parameter expression="${project.build.directory}/maven-shared-archive-resources" */ private File outputDirectory; /** * The directory containing extra information appended to the generated resources. * * @parameter expression="${basedir}/src/main/appended-resources" */ private File appendedResourcesDirectory; /** * Supplemental model data. Useful when processing * artifacts with incomplete POM metadata. * <p/> * By default, this Mojo looks for supplemental model * data in the file "${appendedResourcesDirectory}/supplemental-models.xml". * * @parameter * @since 1.0-alpha-5 */ private String[] supplementalModels; /** * Map of artifacts to supplemental project object models. */ private Map supplementModels; /** * Merges supplemental data model with artifact * metadata. Useful when processing artifacts with * incomplete POM metadata. * * @component */ private ModelInheritanceAssembler inheritanceAssembler; /** * The resource bundles that will be retrieved and processed. * * @parameter * @required */ private List resourceBundles; /** * Skip remote-resource processing * * @parameter expression="${remoteresources.skip}" default-value="false" * @since 1.0-alpha-5 */ private boolean skip; /** * Skip remote-resource processing * * @parameter default-value="true" * @since 1.0-beta-1 */ private boolean attached = true; /** * Additional properties to be passed to velocity. * <p/> * Several properties are automatically added:<br/> * project - the current MavenProject <br/> * projects - the list of dependency projects<br/> * projectTimespan - the timespan of the current project (requires inceptionYear in pom)<br/> * <p/> * See <a href="http://maven.apache.org/ref/current/maven-project/apidocs/org/apache/maven/project/MavenProject.html"> * the javadoc for MavenProject</a> for information about the properties on the MavenProject. * * @parameter */ private Map properties = new HashMap(); /** * The list of resources defined for the project. * * @parameter expression="${project.resources}" * @required */ private List resources; /** * Artifact downloader. * * @component */ private Downloader downloader; /** * Velocity component. * * @component */ private VelocityComponent velocity; // These two things make this horrible. Maven artifact is way too complicated and the relationship between // the model usage and maven-artifact needs to be reworked as well as all our tools that deal with it. The // ProjectUtils should be a component so I don't have to expose the container and artifact factory here. Can't // change it now because it's not released ... /** * Artifact repository factory component. * * @component */ private ArtifactRepositoryFactory artifactRepositoryFactory; /** * Artifact factory, needed to create artifacts. * * @component */ private ArtifactFactory artifactFactory; /** * The Maven session. * * @parameter expression="${session}" */ private MavenSession mavenSession; /** * ProjectBuilder, needed to create projects from the artifacts. * * @component role="org.apache.maven.project.MavenProjectBuilder" * @required * @readonly */ private MavenProjectBuilder mavenProjectBuilder; /** * @component * @required * @readonly */ private ResourceManager locator; public void execute() throws MojoExecutionException { if ( skip ) { return; } if ( supplementalModels == null ) { File sups = new File( appendedResourcesDirectory, "supplemental-models.xml" ); if ( sups.exists() ) { try { supplementalModels = new String[]{sups.toURL().toString()}; } catch ( MalformedURLException e ) { //ignore getLog().debug( "URL issue with supplemental-models.xml: " + e.toString() ); } } } locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() ); if ( appendedResourcesDirectory != null ) { locator.addSearchPath( FileResourceLoader.ID, appendedResourcesDirectory.getAbsolutePath() ); } locator.addSearchPath( "url", "" ); locator.setOutputDirectory( new File( project.getBuild().getDirectory() ) ); ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() ); validate(); List resourceBundleArtifacts = downloadResourceBundles( resourceBundles ); supplementModels = loadSupplements( supplementalModels ); VelocityContext context = new VelocityContext( properties ); configureVelocityContext( context ); RemoteResourcesClassLoader classLoader = new RemoteResourcesClassLoader( null ); initalizeClassloader( classLoader, resourceBundleArtifacts ); Thread.currentThread().setContextClassLoader( classLoader ); processResourceBundles( classLoader, context ); try { if ( outputDirectory.exists() ) { // ---------------------------------------------------------------------------- // Push our newly generated resources directory into the MavenProject so that // these resources can be picked up by the process-resources phase. // ---------------------------------------------------------------------------- if ( attached ) { Resource resource = new Resource(); resource.setDirectory( outputDirectory.getAbsolutePath() ); project.getResources().add( resource ); project.getTestResources().add( resource ); } // ---------------------------------------------------------------------------- // Write out archiver dot file // ---------------------------------------------------------------------------- File dotFile = new File( project.getBuild().getDirectory(), ".plxarc" ); FileUtils.mkdir( dotFile.getParentFile().getAbsolutePath() ); FileUtils.fileWrite( dotFile.getAbsolutePath(), outputDirectory.getName() ); } } catch ( IOException e ) { throw new MojoExecutionException( "Error creating dot file for archiving instructions.", e ); } } finally { Thread.currentThread().setContextClassLoader( origLoader ); } } protected List getProjects() throws MojoExecutionException { List projects = new ArrayList(); for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); try { List remoteRepo = repositories; if ( artifact.isSnapshot() ) { VersionRange rng = VersionRange.createFromVersion( artifact.getBaseVersion() ); artifact = artifactFactory.createDependencyArtifact( artifact.getGroupId(), artifact.getArtifactId(), rng, artifact.getType(), artifact.getClassifier(), artifact.getScope(), null, artifact.isOptional() ); remoteRepo = remoteArtifactRepositories; } getLog().debug( "Building project for " + artifact ); MavenProject p = null; try { p = mavenProjectBuilder.buildFromRepository( artifact, remoteRepo, localRepository, true ); } catch ( InvalidProjectModelException e ) { getLog().warn( "Invalid project model for artifact [" + artifact.getArtifactId() + ":" + artifact.getGroupId() + ":" + artifact.getVersion() + "]. " + "It will be ignored by the remote resources Mojo." ); continue; } String supplementKey = generateSupplementMapKey( p.getModel().getGroupId(), p.getModel().getArtifactId() ); if ( supplementModels.containsKey( supplementKey ) ) { Model mergedModel = mergeModels( p.getModel(), (Model) supplementModels.get( supplementKey ) ); MavenProject mergedProject = new MavenProject( mergedModel ); projects.add( mergedProject ); mergedProject.setArtifact( artifact ); mergedProject.setVersion( artifact.getVersion() ); getLog().debug( "Adding project with groupId [" + mergedProject.getGroupId() + "] (supplemented)" ); } else { projects.add( p ); getLog().debug( "Adding project with groupId [" + p.getGroupId() + "]" ); } } catch ( ProjectBuildingException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } Collections.sort( projects, new ProjectComparator() ); return projects; } protected Map getProjectsSortedByOrganization( List projects ) throws MojoExecutionException { Map organizations = new TreeMap( new OrganizationComparator() ); List unknownOrganization = new ArrayList(); for ( Iterator i = projects.iterator(); i.hasNext(); ) { MavenProject p = (MavenProject) i.next(); if ( p.getOrganization() != null && StringUtils.isNotEmpty( p.getOrganization().getName() ) ) { List sortedProjects = (List) organizations.get( p.getOrganization() ); if ( sortedProjects == null ) { sortedProjects = new ArrayList(); } sortedProjects.add( p ); organizations.put( p.getOrganization(), sortedProjects ); } else { unknownOrganization.add( p ); } } if ( !unknownOrganization.isEmpty() ) { Organization unknownOrg = new Organization(); unknownOrg.setName( "an unknown organization" ); organizations.put( unknownOrg, unknownOrganization ); } return organizations; } protected boolean copyResourceIfExists( File file, String relFileName ) throws IOException { for ( Iterator i = resources.iterator(); i.hasNext(); ) { Resource resource = (Resource) i.next(); File resourceDirectory = new File( resource.getDirectory() ); if ( !resourceDirectory.exists() ) { continue; } //TODO - really should use the resource includes/excludes and name mapping File source = new File( resourceDirectory, relFileName ); if ( source.exists() && !source.equals( file ) ) { //TODO - should use filters here FileUtils.copyFile( source, file ); //exclude the original (so eclipse doesn't complain about duplicate resources) resource.addExclude( relFileName ); return true; } } return false; } protected void validate() throws MojoExecutionException { int bundleCount = 1; for ( Iterator i = resourceBundles.iterator(); i.hasNext(); ) { String artifactDescriptor = (String) i.next(); // groupId:artifactId:version String[] s = StringUtils.split( artifactDescriptor, ":" ); if ( s.length != 3 ) { String position; if ( bundleCount == 1 ) { position = "1st"; } else if ( bundleCount == 2 ) { position = "2nd"; } else if ( bundleCount == 3 ) { position = "3rd"; } else { position = bundleCount + "th"; } throw new MojoExecutionException( "The " + position + " resource bundle configured must specify a groupId, artifactId, and" + " version for a remote resource bundle. " + "Must be of the form <resourceBundle>groupId:artifactId:version</resourceBundle>" ); } bundleCount++; } } protected void configureVelocityContext( VelocityContext context ) throws MojoExecutionException { String inceptionYear = project.getInceptionYear(); String year = new SimpleDateFormat( "yyyy" ).format( new Date() ); if ( StringUtils.isEmpty( inceptionYear ) ) { getLog().info( "inceptionYear not specified, defaulting to " + year ); inceptionYear = year; } context.put( "project", project ); List projects = getProjects(); context.put( "projects", projects ); context.put( "projectsSortedByOrganization", getProjectsSortedByOrganization( projects ) ); context.put( "presentYear", year ); if ( inceptionYear.equals( year ) ) { context.put( "projectTimespan", year ); } else { context.put( "projectTimespan", inceptionYear + "-" + year ); } } private List downloadResourceBundles( List resourceBundles ) throws MojoExecutionException { List resourceBundleArtifacts = new ArrayList(); try { for ( Iterator i = resourceBundles.iterator(); i.hasNext(); ) { String artifactDescriptor = (String) i.next(); // groupId:artifactId:version String[] s = artifactDescriptor.split( ":" ); File artifact = downloader.download( s[0], s[1], s[2], localRepository, ProjectUtils.buildArtifactRepositories( repositories, artifactRepositoryFactory, mavenSession.getContainer() ) ); resourceBundleArtifacts.add( artifact ); } } catch ( DownloadException e ) { throw new MojoExecutionException( "Error downloading resources JAR.", e ); } catch ( DownloadNotFoundException e ) { throw new MojoExecutionException( "Resources JAR cannot be found.", e ); } catch ( InvalidRepositoryException e ) { throw new MojoExecutionException( "Resources JAR cannot be found.", e ); } return resourceBundleArtifacts; } private void initalizeClassloader( RemoteResourcesClassLoader cl, List artifacts ) throws MojoExecutionException { try { for ( Iterator i = artifacts.iterator(); i.hasNext(); ) { File artifact = (File) i.next(); cl.addURL( artifact.toURI().toURL() ); } } catch ( MalformedURLException e ) { throw new MojoExecutionException( "Unable to configure resources classloader: " + e.getMessage(), e ); } } protected void processResourceBundles( RemoteResourcesClassLoader classLoader, VelocityContext context ) throws MojoExecutionException { InputStreamReader reader = null; try { for ( Enumeration e = classLoader.getResources( BundleRemoteResourcesMojo.RESOURCES_MANIFEST ); e.hasMoreElements(); ) { URL url = (URL) e.nextElement(); URLConnection conn = url.openConnection(); conn.connect(); reader = new InputStreamReader( conn.getInputStream() ); try { RemoteResourcesBundleXpp3Reader bundleReader = new RemoteResourcesBundleXpp3Reader(); RemoteResourcesBundle bundle = bundleReader.read( reader ); for ( Iterator i = bundle.getRemoteResources().iterator(); i.hasNext(); ) { String bundleResource = (String) i.next(); String projectResource = bundleResource; boolean doVelocity = false; if ( projectResource.endsWith( ".vm" ) ) { projectResource = projectResource.substring( 0, projectResource.length() - 3 ); doVelocity = true; } // Don't overwrite resource that are already being provided. File f = new File( outputDirectory, projectResource ); FileUtils.mkdir( f.getParentFile().getAbsolutePath() ); if ( !copyResourceIfExists( f, projectResource ) ) { if ( doVelocity ) { PrintWriter writer = new PrintWriter( new FileWriter( f ) ); try { velocity.getEngine().mergeTemplate( bundleResource, context, writer ); } finally { IOUtil.close(writer); } } else { URL resUrl = classLoader.getResource( bundleResource ); if ( resUrl != null ) { FileUtils.copyURLToFile( resUrl, f ); } } File appendedResourceFile = new File( appendedResourcesDirectory, projectResource ); File appendedVmResourceFile = new File( appendedResourcesDirectory, projectResource + ".vm" ); if ( appendedResourceFile.exists() ) { PrintWriter writer = new PrintWriter( new FileWriter( f, true ) ); FileReader freader = new FileReader( appendedResourceFile ); BufferedReader breader = new BufferedReader( freader ); try { String line = breader.readLine(); while ( line != null ) { writer.println( line ); line = breader.readLine(); } } finally { IOUtil.close(writer); IOUtil.close(breader); } } else if ( appendedVmResourceFile.exists() ) { PrintWriter writer = new PrintWriter( new FileWriter( f, true ) ); FileReader freader = new FileReader( appendedVmResourceFile ); try { Velocity.init(); Velocity.evaluate( context, writer, "remote-resources", freader ); } finally { IOUtil.close(writer); IOUtil.close(freader); } } } } } finally { reader.close(); } } } catch ( IOException e ) { throw new MojoExecutionException( "Error finding remote resources manifests", e ); } catch ( XmlPullParserException e ) { throw new MojoExecutionException( "Error parsing remote resource bundle descriptor.", e ); } catch ( Exception e ) { throw new MojoExecutionException( "Error rendering velocity resource.", e ); } } protected Model getSupplement( Xpp3Dom supplementModelXml ) throws MojoExecutionException { MavenXpp3Reader modelReader = new MavenXpp3Reader(); Model model = null; try { model = modelReader.read( new StringReader( supplementModelXml.toString() ) ); String groupId = model.getGroupId(); String artifactId = model.getArtifactId(); if ( groupId == null || groupId.trim().equals( "" ) ) { throw new MojoExecutionException( "Supplemental project XML " + "requires that a <groupId> element be present." ); } if ( artifactId == null || artifactId.trim().equals( "" ) ) { throw new MojoExecutionException( "Supplemental project XML " + "requires that a <artifactId> element be present." ); } } catch ( IOException e ) { getLog().warn( "Unable to read supplemental XML: " + e.getMessage(), e ); } catch ( XmlPullParserException e ) { getLog().warn( "Unable to parse supplemental XML: " + e.getMessage(), e ); } return model; } protected Model mergeModels( Model parent, Model child ) { inheritanceAssembler.assembleModelInheritance( child, parent ); return child; } private static String generateSupplementMapKey( String groupId, String artifactId ) { return groupId.trim() + ":" + artifactId.trim(); } private Map loadSupplements( String models[] ) throws MojoExecutionException { if ( models == null ) { getLog().debug( "Supplemental data models won't be loaded. " + "No models specified." ); return Collections.EMPTY_MAP; } List supplements = new ArrayList(); for ( int idx = 0; idx < models.length; idx++ ) { String set = models[idx]; getLog().debug( "Preparing ruleset: " + set ); try { File f = locator.getResourceAsFile( set, getLocationTemp( set ) ); if ( null == f || !f.exists() ) { throw new MavenReportException( "Cold not resolve " + set ); } if ( !f.canRead() ) { throw new MavenReportException( "Supplemental data models won't be loaded. " + "File " + f.getAbsolutePath() + " cannot be read, check permissions on the file." ); } getLog().debug( "Loading supplemental models from " + f.getAbsolutePath() ); SupplementalDataModelXpp3Reader reader = new SupplementalDataModelXpp3Reader(); SupplementalDataModel supplementalModel = reader.read( new FileReader( f ) ); supplements.addAll( supplementalModel.getSupplement() ); } catch ( Exception e ) { String msg = "Error loading supplemental data models: " + e.getMessage(); getLog().error( msg, e ); throw new MojoExecutionException( msg, e ); } } getLog().debug( "Loading supplements complete." ); Map supplementMap = new HashMap(); for ( Iterator i = supplements.iterator(); i.hasNext(); ) { Supplement sd = (Supplement) i.next(); Xpp3Dom dom = (Xpp3Dom) sd.getProject(); Model m = getSupplement( dom ); supplementMap.put( generateSupplementMapKey( m.getGroupId(), m.getArtifactId() ), m ); } return supplementMap; } /** * Convenience method to get the location of the specified file name. * * @param name the name of the file whose location is to be resolved * @return a String that contains the absolute file name of the file */ private String getLocationTemp( String name ) { String loc = name; if ( loc.indexOf( '/' ) != -1 ) { loc = loc.substring( loc.lastIndexOf( '/' ) + 1 ); } if ( loc.indexOf( '\\' ) != -1 ) { loc = loc.substring( loc.lastIndexOf( '\\' ) + 1 ); } getLog().debug( "Before: " + name + " After: " + loc ); return loc; } class OrganizationComparator implements Comparator { public int compare( Object o1, Object o2 ) { Organization org1 = (Organization) o1; Organization org2 = (Organization) o2; int i = compareStrings( org1.getName(), org2.getName() ); if (i == 0) { i = compareStrings( org1.getUrl(), org2.getUrl() ); } return i; } public boolean equals( Object o1, Object o2 ) { return compare(o1, o2) == 0; } private int compareStrings( String s1, String s2 ) { if ( s1 == null && s2 == null ) { return 0; } else if ( s1 == null && s2 != null ) { return 1; } else if ( s1 != null && s2 == null ) { return -1; } return s1.compareToIgnoreCase( s2 ); } } class ProjectComparator implements Comparator { public int compare( Object o1, Object o2 ) { MavenProject p1 = (MavenProject) o1; MavenProject p2 = (MavenProject) o2; return p1.getArtifact().compareTo( p2.getArtifact() ); } public boolean equals( Object o1, Object o2 ) { MavenProject p1 = (MavenProject) o1; MavenProject p2 = (MavenProject) o2; return p1.getArtifact().equals( p2.getArtifact() ); } } }
maven-remote-resources-plugin/src/main/java/org/apache/maven/plugin/resources/remote/ProcessRemoteResourcesMojo.java
package org.apache.maven.plugin.resources.remote; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.model.Organization; import org.apache.maven.model.Resource; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.resources.remote.io.xpp3.RemoteResourcesBundleXpp3Reader; import org.apache.maven.plugin.resources.remote.io.xpp3.SupplementalDataModelXpp3Reader; import org.apache.maven.project.InvalidProjectModelException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectUtils; import org.apache.maven.project.inheritance.ModelInheritanceAssembler; import org.apache.maven.reporting.MavenReportException; import org.apache.maven.shared.downloader.DownloadException; import org.apache.maven.shared.downloader.DownloadNotFoundException; import org.apache.maven.shared.downloader.Downloader; import org.apache.velocity.VelocityContext; import org.codehaus.plexus.resource.ResourceManager; import org.codehaus.plexus.resource.loader.FileResourceLoader; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.codehaus.plexus.velocity.VelocityComponent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * <p> * Pull down resourceBundles containing remote resources and process the * resources contained inside. When that is done the resources are injected * into the current (in-memory) Maven project, making them available to the * process-resources phase. * </p> * <p> * Resources that end in ".vm" are treated as velocity templates. For those, the ".vm" is * stripped off for the final artifact name and it's fed through velocity to have properties * expanded, conditions processed, etc... * </p> * <p> * Resources that don't end in ".vm" are copied "as is". * </p> * * @goal process * @requiresDependencyResolution runtime * @phase generate-resources */ public class ProcessRemoteResourcesMojo extends AbstractMojo { /** * The local repository taken from Maven's runtime. Typically $HOME/.m2/repository. * * @parameter expression="${localRepository}" */ private ArtifactRepository localRepository; /** * The remote repositories used as specified in your POM. * * @parameter expression="${project.repositories}" */ private List repositories; /** * List of Remote Repositories used by the resolver * * @parameter expression="${project.remoteArtifactRepositories}" * @readonly * @required */ private List remoteArtifactRepositories; /** * The current Maven project. * * @parameter expression="${project}" */ private MavenProject project; /** * The directory where processed resources will be placed for packaging. * * @parameter expression="${project.build.directory}/maven-shared-archive-resources" */ private File outputDirectory; /** * The directory containing extra information appended to the generated resources. * * @parameter expression="${basedir}/src/main/appended-resources" */ private File appendedResourcesDirectory; /** * Supplemental model data. Useful when processing * artifacts with incomplete POM metadata. * <p/> * By default, this Mojo looks for supplemental model * data in the file "${appendedResourcesDirectory}/supplemental-models.xml". * * @parameter * @since 1.0-alpha-5 */ private String[] supplementalModels; /** * Map of artifacts to supplemental project object models. */ private Map supplementModels; /** * Merges supplemental data model with artifact * metadata. Useful when processing artifacts with * incomplete POM metadata. * * @component */ private ModelInheritanceAssembler inheritanceAssembler; /** * The resource bundles that will be retrieved and processed. * * @parameter * @required */ private List resourceBundles; /** * Skip remote-resource processing * * @parameter expression="${remoteresources.skip}" default-value="false" * @since 1.0-alpha-5 */ private boolean skip; /** * Skip remote-resource processing * * @parameter default-value="true" * @since 1.0-beta-1 */ private boolean attached = true; /** * Additional properties to be passed to velocity. * <p/> * Several properties are automatically added:<br/> * project - the current MavenProject <br/> * projects - the list of dependency projects<br/> * projectTimespan - the timespan of the current project (requires inceptionYear in pom)<br/> * <p/> * See <a href="http://maven.apache.org/ref/current/maven-project/apidocs/org/apache/maven/project/MavenProject.html"> * the javadoc for MavenProject</a> for information about the properties on the MavenProject. * * @parameter */ private Map properties = new HashMap(); /** * The list of resources defined for the project. * * @parameter expression="${project.resources}" * @required */ private List resources; /** * Artifact downloader. * * @component */ private Downloader downloader; /** * Velocity component. * * @component */ private VelocityComponent velocity; // These two things make this horrible. Maven artifact is way too complicated and the relationship between // the model usage and maven-artifact needs to be reworked as well as all our tools that deal with it. The // ProjectUtils should be a component so I don't have to expose the container and artifact factory here. Can't // change it now because it's not released ... /** * Artifact repository factory component. * * @component */ private ArtifactRepositoryFactory artifactRepositoryFactory; /** * Artifact factory, needed to create artifacts. * * @component */ private ArtifactFactory artifactFactory; /** * The Maven session. * * @parameter expression="${session}" */ private MavenSession mavenSession; /** * ProjectBuilder, needed to create projects from the artifacts. * * @component role="org.apache.maven.project.MavenProjectBuilder" * @required * @readonly */ private MavenProjectBuilder mavenProjectBuilder; /** * @component * @required * @readonly */ private ResourceManager locator; public void execute() throws MojoExecutionException { if ( skip ) { return; } if ( supplementalModels == null ) { File sups = new File( appendedResourcesDirectory, "supplemental-models.xml" ); if ( sups.exists() ) { try { supplementalModels = new String[]{sups.toURL().toString()}; } catch ( MalformedURLException e ) { //ignore getLog().debug( "URL issue with supplemental-models.xml: " + e.toString() ); } } } locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() ); if ( appendedResourcesDirectory != null ) { locator.addSearchPath( FileResourceLoader.ID, appendedResourcesDirectory.getAbsolutePath() ); } locator.addSearchPath( "url", "" ); locator.setOutputDirectory( new File( project.getBuild().getDirectory() ) ); ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() ); validate(); List resourceBundleArtifacts = downloadResourceBundles( resourceBundles ); supplementModels = loadSupplements( supplementalModels ); VelocityContext context = new VelocityContext( properties ); configureVelocityContext( context ); RemoteResourcesClassLoader classLoader = new RemoteResourcesClassLoader( null ); initalizeClassloader( classLoader, resourceBundleArtifacts ); Thread.currentThread().setContextClassLoader( classLoader ); processResourceBundles( classLoader, context ); try { if ( outputDirectory.exists() ) { // ---------------------------------------------------------------------------- // Push our newly generated resources directory into the MavenProject so that // these resources can be picked up by the process-resources phase. // ---------------------------------------------------------------------------- if ( attached ) { Resource resource = new Resource(); resource.setDirectory( outputDirectory.getAbsolutePath() ); project.getResources().add( resource ); project.getTestResources().add( resource ); } // ---------------------------------------------------------------------------- // Write out archiver dot file // ---------------------------------------------------------------------------- File dotFile = new File( project.getBuild().getDirectory(), ".plxarc" ); FileUtils.mkdir( dotFile.getParentFile().getAbsolutePath() ); FileUtils.fileWrite( dotFile.getAbsolutePath(), outputDirectory.getName() ); } } catch ( IOException e ) { throw new MojoExecutionException( "Error creating dot file for archiving instructions.", e ); } } finally { Thread.currentThread().setContextClassLoader( origLoader ); } } protected List getProjects() throws MojoExecutionException { List projects = new ArrayList(); for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); try { List remoteRepo = repositories; if ( artifact.isSnapshot() ) { VersionRange rng = VersionRange.createFromVersion( artifact.getBaseVersion() ); artifact = artifactFactory.createDependencyArtifact( artifact.getGroupId(), artifact.getArtifactId(), rng, artifact.getType(), artifact.getClassifier(), artifact.getScope(), null, artifact.isOptional() ); remoteRepo = remoteArtifactRepositories; } getLog().debug( "Building project for " + artifact ); MavenProject p = null; try { p = mavenProjectBuilder.buildFromRepository( artifact, remoteRepo, localRepository, true ); } catch ( InvalidProjectModelException e ) { getLog().warn( "Invalid project model for artifact [" + artifact.getArtifactId() + ":" + artifact.getGroupId() + ":" + artifact.getVersion() + "]. " + "It will be ignored by the remote resources Mojo." ); continue; } String supplementKey = generateSupplementMapKey( p.getModel().getGroupId(), p.getModel().getArtifactId() ); if ( supplementModels.containsKey( supplementKey ) ) { Model mergedModel = mergeModels( p.getModel(), (Model) supplementModels.get( supplementKey ) ); MavenProject mergedProject = new MavenProject( mergedModel ); projects.add( mergedProject ); mergedProject.setArtifact( artifact ); mergedProject.setVersion( artifact.getVersion() ); getLog().debug( "Adding project with groupId [" + mergedProject.getGroupId() + "] (supplemented)" ); } else { projects.add( p ); getLog().debug( "Adding project with groupId [" + p.getGroupId() + "]" ); } } catch ( ProjectBuildingException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } Collections.sort( projects, new ProjectComparator() ); return projects; } protected Map getProjectsSortedByOrganization( List projects ) throws MojoExecutionException { Map organizations = new TreeMap( new OrganizationComparator() ); List unknownOrganization = new ArrayList(); for ( Iterator i = projects.iterator(); i.hasNext(); ) { MavenProject p = (MavenProject) i.next(); if ( p.getOrganization() != null && StringUtils.isNotEmpty( p.getOrganization().getName() ) ) { List sortedProjects = (List) organizations.get( p.getOrganization() ); if ( sortedProjects == null ) { sortedProjects = new ArrayList(); } sortedProjects.add( p ); organizations.put( p.getOrganization(), sortedProjects ); } else { unknownOrganization.add( p ); } } if ( !unknownOrganization.isEmpty() ) { Organization unknownOrg = new Organization(); unknownOrg.setName( "an unknown organization" ); organizations.put( unknownOrg, unknownOrganization ); } return organizations; } protected boolean copyResourceIfExists( File file, String relFileName ) throws IOException { for ( Iterator i = resources.iterator(); i.hasNext(); ) { Resource resource = (Resource) i.next(); File resourceDirectory = new File( resource.getDirectory() ); if ( !resourceDirectory.exists() ) { continue; } //TODO - really should use the resource includes/excludes and name mapping File source = new File( resourceDirectory, relFileName ); if ( source.exists() && !source.equals( file ) ) { //TODO - should use filters here FileUtils.copyFile( source, file ); //exclude the original (so eclipse doesn't complain about duplicate resources) resource.addExclude( relFileName ); return true; } } return false; } protected void validate() throws MojoExecutionException { int bundleCount = 1; for ( Iterator i = resourceBundles.iterator(); i.hasNext(); ) { String artifactDescriptor = (String) i.next(); // groupId:artifactId:version String[] s = StringUtils.split( artifactDescriptor, ":" ); if ( s.length != 3 ) { String position; if ( bundleCount == 1 ) { position = "1st"; } else if ( bundleCount == 2 ) { position = "2nd"; } else if ( bundleCount == 3 ) { position = "3rd"; } else { position = bundleCount + "th"; } throw new MojoExecutionException( "The " + position + " resource bundle configured must specify a groupId, artifactId, and" + " version for a remote resource bundle. " + "Must be of the form <resourceBundle>groupId:artifactId:version</resourceBundle>" ); } bundleCount++; } } protected void configureVelocityContext( VelocityContext context ) throws MojoExecutionException { String inceptionYear = project.getInceptionYear(); String year = new SimpleDateFormat( "yyyy" ).format( new Date() ); if ( StringUtils.isEmpty( inceptionYear ) ) { getLog().info( "inceptionYear not specified, defaulting to " + year ); inceptionYear = year; } context.put( "project", project ); List projects = getProjects(); context.put( "projects", projects ); context.put( "projectsSortedByOrganization", getProjectsSortedByOrganization( projects ) ); context.put( "presentYear", year ); if ( inceptionYear.equals( year ) ) { context.put( "projectTimespan", year ); } else { context.put( "projectTimespan", inceptionYear + "-" + year ); } } private List downloadResourceBundles( List resourceBundles ) throws MojoExecutionException { List resourceBundleArtifacts = new ArrayList(); try { for ( Iterator i = resourceBundles.iterator(); i.hasNext(); ) { String artifactDescriptor = (String) i.next(); // groupId:artifactId:version String[] s = artifactDescriptor.split( ":" ); File artifact = downloader.download( s[0], s[1], s[2], localRepository, ProjectUtils.buildArtifactRepositories( repositories, artifactRepositoryFactory, mavenSession.getContainer() ) ); resourceBundleArtifacts.add( artifact ); } } catch ( DownloadException e ) { throw new MojoExecutionException( "Error downloading resources JAR.", e ); } catch ( DownloadNotFoundException e ) { throw new MojoExecutionException( "Resources JAR cannot be found.", e ); } catch ( InvalidRepositoryException e ) { throw new MojoExecutionException( "Resources JAR cannot be found.", e ); } return resourceBundleArtifacts; } private void initalizeClassloader( RemoteResourcesClassLoader cl, List artifacts ) throws MojoExecutionException { try { for ( Iterator i = artifacts.iterator(); i.hasNext(); ) { File artifact = (File) i.next(); cl.addURL( artifact.toURI().toURL() ); } } catch ( MalformedURLException e ) { throw new MojoExecutionException( "Unable to configure resources classloader: " + e.getMessage(), e ); } } protected void processResourceBundles( RemoteResourcesClassLoader classLoader, VelocityContext context ) throws MojoExecutionException { InputStreamReader reader = null; try { for ( Enumeration e = classLoader.getResources( BundleRemoteResourcesMojo.RESOURCES_MANIFEST ); e.hasMoreElements(); ) { URL url = (URL) e.nextElement(); URLConnection conn = url.openConnection(); conn.connect(); reader = new InputStreamReader( conn.getInputStream() ); try { RemoteResourcesBundleXpp3Reader bundleReader = new RemoteResourcesBundleXpp3Reader(); RemoteResourcesBundle bundle = bundleReader.read( reader ); for ( Iterator i = bundle.getRemoteResources().iterator(); i.hasNext(); ) { String bundleResource = (String) i.next(); String projectResource = bundleResource; boolean doVelocity = false; if ( projectResource.endsWith( ".vm" ) ) { projectResource = projectResource.substring( 0, projectResource.length() - 3 ); doVelocity = true; } // Don't overwrite resource that are already being provided. File f = new File( outputDirectory, projectResource ); FileUtils.mkdir( f.getParentFile().getAbsolutePath() ); if ( !copyResourceIfExists( f, projectResource ) ) { if ( doVelocity ) { PrintWriter writer = new PrintWriter( new FileWriter( f ) ); try { velocity.getEngine().mergeTemplate( bundleResource, context, writer ); File appendedResourceFile = new File( appendedResourcesDirectory, projectResource ); if ( appendedResourceFile.exists() ) { FileReader freader = new FileReader( appendedResourceFile ); BufferedReader breader = new BufferedReader( freader ); String line = breader.readLine(); while ( line != null ) { writer.println( line ); line = breader.readLine(); } } } finally { writer.close(); } } else { URL resUrl = classLoader.getResource( bundleResource ); if ( resUrl != null ) { FileUtils.copyURLToFile( resUrl, f ); } } } } } finally { reader.close(); } } } catch ( IOException e ) { throw new MojoExecutionException( "Error finding remote resources manifests", e ); } catch ( XmlPullParserException e ) { throw new MojoExecutionException( "Error parsing remote resource bundle descriptor.", e ); } catch ( Exception e ) { throw new MojoExecutionException( "Error rendering velocity resource.", e ); } } protected Model getSupplement( Xpp3Dom supplementModelXml ) throws MojoExecutionException { MavenXpp3Reader modelReader = new MavenXpp3Reader(); Model model = null; try { model = modelReader.read( new StringReader( supplementModelXml.toString() ) ); String groupId = model.getGroupId(); String artifactId = model.getArtifactId(); if ( groupId == null || groupId.trim().equals( "" ) ) { throw new MojoExecutionException( "Supplemental project XML " + "requires that a <groupId> element be present." ); } if ( artifactId == null || artifactId.trim().equals( "" ) ) { throw new MojoExecutionException( "Supplemental project XML " + "requires that a <artifactId> element be present." ); } } catch ( IOException e ) { getLog().warn( "Unable to read supplemental XML: " + e.getMessage(), e ); } catch ( XmlPullParserException e ) { getLog().warn( "Unable to parse supplemental XML: " + e.getMessage(), e ); } return model; } protected Model mergeModels( Model parent, Model child ) { inheritanceAssembler.assembleModelInheritance( child, parent ); return child; } private static String generateSupplementMapKey( String groupId, String artifactId ) { return groupId.trim() + ":" + artifactId.trim(); } private Map loadSupplements( String models[] ) throws MojoExecutionException { if ( models == null ) { getLog().debug( "Supplemental data models won't be loaded. " + "No models specified." ); return Collections.EMPTY_MAP; } List supplements = new ArrayList(); for ( int idx = 0; idx < models.length; idx++ ) { String set = models[idx]; getLog().debug( "Preparing ruleset: " + set ); try { File f = locator.getResourceAsFile( set, getLocationTemp( set ) ); if ( null == f || !f.exists() ) { throw new MavenReportException( "Cold not resolve " + set ); } if ( !f.canRead() ) { throw new MavenReportException( "Supplemental data models won't be loaded. " + "File " + f.getAbsolutePath() + " cannot be read, check permissions on the file." ); } getLog().debug( "Loading supplemental models from " + f.getAbsolutePath() ); SupplementalDataModelXpp3Reader reader = new SupplementalDataModelXpp3Reader(); SupplementalDataModel supplementalModel = reader.read( new FileReader( f ) ); supplements.addAll( supplementalModel.getSupplement() ); } catch ( Exception e ) { String msg = "Error loading supplemental data models: " + e.getMessage(); getLog().error( msg, e ); throw new MojoExecutionException( msg, e ); } } getLog().debug( "Loading supplements complete." ); Map supplementMap = new HashMap(); for ( Iterator i = supplements.iterator(); i.hasNext(); ) { Supplement sd = (Supplement) i.next(); Xpp3Dom dom = (Xpp3Dom) sd.getProject(); Model m = getSupplement( dom ); supplementMap.put( generateSupplementMapKey( m.getGroupId(), m.getArtifactId() ), m ); } return supplementMap; } /** * Convenience method to get the location of the specified file name. * * @param name the name of the file whose location is to be resolved * @return a String that contains the absolute file name of the file */ private String getLocationTemp( String name ) { String loc = name; if ( loc.indexOf( '/' ) != -1 ) { loc = loc.substring( loc.lastIndexOf( '/' ) + 1 ); } if ( loc.indexOf( '\\' ) != -1 ) { loc = loc.substring( loc.lastIndexOf( '\\' ) + 1 ); } getLog().debug( "Before: " + name + " After: " + loc ); return loc; } class OrganizationComparator implements Comparator { public int compare( Object o1, Object o2 ) { Organization org1 = (Organization) o1; Organization org2 = (Organization) o2; int i = compareStrings( org1.getName(), org2.getName() ); if (i == 0) { i = compareStrings( org1.getUrl(), org2.getUrl() ); } return i; } public boolean equals( Object o1, Object o2 ) { return compare(o1, o2) == 0; } private int compareStrings( String s1, String s2 ) { if ( s1 == null && s2 == null ) { return 0; } else if ( s1 == null && s2 != null ) { return 1; } else if ( s1 != null && s2 == null ) { return -1; } return s1.compareToIgnoreCase( s2 ); } } class ProjectComparator implements Comparator { public int compare( Object o1, Object o2 ) { MavenProject p1 = (MavenProject) o1; MavenProject p2 = (MavenProject) o2; return p1.getArtifact().compareTo( p2.getArtifact() ); } public boolean equals( Object o1, Object o2 ) { MavenProject p1 = (MavenProject) o1; MavenProject p2 = (MavenProject) o2; return p1.getArtifact().equals( p2.getArtifact() ); } } }
Allow appended resource things to be appended to copied (not velocity processed) resources Allow appended resource things to be processed by velocity git-svn-id: 6038db50b076e48c7926ed71fd94f8e91be2fbc9@637608 13f79535-47bb-0310-9956-ffa450edef68
maven-remote-resources-plugin/src/main/java/org/apache/maven/plugin/resources/remote/ProcessRemoteResourcesMojo.java
Allow appended resource things to be appended to copied (not velocity processed) resources Allow appended resource things to be processed by velocity
<ide><path>aven-remote-resources-plugin/src/main/java/org/apache/maven/plugin/resources/remote/ProcessRemoteResourcesMojo.java <ide> import org.apache.maven.shared.downloader.DownloadNotFoundException; <ide> import org.apache.maven.shared.downloader.Downloader; <ide> import org.apache.velocity.VelocityContext; <add>import org.apache.velocity.app.Velocity; <ide> import org.codehaus.plexus.resource.ResourceManager; <ide> import org.codehaus.plexus.resource.loader.FileResourceLoader; <ide> import org.codehaus.plexus.util.FileUtils; <add>import org.codehaus.plexus.util.IOUtil; <ide> import org.codehaus.plexus.util.StringUtils; <ide> import org.codehaus.plexus.util.xml.Xpp3Dom; <ide> import org.codehaus.plexus.util.xml.pull.XmlPullParserException; <ide> import java.io.InputStreamReader; <ide> import java.io.PrintWriter; <ide> import java.io.StringReader; <add>import java.io.Writer; <ide> import java.net.MalformedURLException; <ide> import java.net.URL; <ide> import java.net.URLConnection; <ide> try <ide> { <ide> velocity.getEngine().mergeTemplate( bundleResource, context, writer ); <del> <del> File appendedResourceFile = new File( appendedResourcesDirectory, projectResource ); <del> if ( appendedResourceFile.exists() ) <del> { <del> FileReader freader = new FileReader( appendedResourceFile ); <del> BufferedReader breader = new BufferedReader( freader ); <del> <del> String line = breader.readLine(); <del> <del> while ( line != null ) <del> { <del> writer.println( line ); <del> line = breader.readLine(); <del> } <del> } <ide> } <ide> finally <ide> { <del> writer.close(); <add> IOUtil.close(writer); <ide> } <ide> } <ide> else <ide> FileUtils.copyURLToFile( resUrl, f ); <ide> } <ide> } <add> File appendedResourceFile = new File( appendedResourcesDirectory, projectResource ); <add> File appendedVmResourceFile = new File( appendedResourcesDirectory, <add> projectResource + ".vm" ); <add> if ( appendedResourceFile.exists() ) <add> { <add> PrintWriter writer = new PrintWriter( new FileWriter( f, true ) ); <add> FileReader freader = new FileReader( appendedResourceFile ); <add> BufferedReader breader = new BufferedReader( freader ); <add> <add> try <add> { <add> String line = breader.readLine(); <add> <add> while ( line != null ) <add> { <add> writer.println( line ); <add> line = breader.readLine(); <add> } <add> } <add> finally <add> { <add> IOUtil.close(writer); <add> IOUtil.close(breader); <add> } <add> } <add> else if ( appendedVmResourceFile.exists() ) <add> { <add> PrintWriter writer = new PrintWriter( new FileWriter( f, true ) ); <add> FileReader freader = new FileReader( appendedVmResourceFile ); <add> try <add> { <add> Velocity.init(); <add> Velocity.evaluate( context, writer, "remote-resources", freader ); <add> } <add> finally <add> { <add> IOUtil.close(writer); <add> IOUtil.close(freader); <add> } <add> } <add> <ide> } <ide> } <ide> }
Java
apache-2.0
e642e8f8737af8efd0b40ff815a83859614da29e
0
arnost-starosta/midpoint,rpudil/midpoint,Pardus-Engerek/engerek,rpudil/midpoint,rpudil/midpoint,gureronder/midpoint,gureronder/midpoint,Pardus-Engerek/engerek,arnost-starosta/midpoint,PetrGasparik/midpoint,Pardus-Engerek/engerek,PetrGasparik/midpoint,arnost-starosta/midpoint,sabriarabacioglu/engerek,gureronder/midpoint,sabriarabacioglu/engerek,PetrGasparik/midpoint,sabriarabacioglu/engerek,arnost-starosta/midpoint,arnost-starosta/midpoint,rpudil/midpoint,gureronder/midpoint,PetrGasparik/midpoint,Pardus-Engerek/engerek
/* * Copyright (c) 2011 Evolveum * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1 or * CDDLv1.0.txt file in the source code distribution. * See the License for the specific language governing * permission and limitations under the License. * * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * your own identifying information: * * Portions Copyrighted 2011 [name of copyright owner] * Portions Copyrighted 2011 Igor Farinic */ package com.evolveum.midpoint.repo.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceIterator; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XPathQueryService; import com.evolveum.midpoint.api.logging.Trace; import com.evolveum.midpoint.common.jaxb.JAXBUtil; import com.evolveum.midpoint.common.patch.PatchXml; import com.evolveum.midpoint.common.result.OperationResult; import com.evolveum.midpoint.logging.TraceManager; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.ObjectTypes; import com.evolveum.midpoint.schema.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.schema.exception.ObjectNotFoundException; import com.evolveum.midpoint.schema.exception.SchemaException; import com.evolveum.midpoint.schema.exception.SystemException; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.patch.PatchException; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectContainerType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PagingType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PropertyAvailableValuesListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_1.UserType; import com.evolveum.midpoint.xml.schema.SchemaConstants; import com.evolveum.midpoint.xml.schema.XPathType; public class XmlRepositoryService implements RepositoryService { private static final String DECLARE_NAMESPACE_C = "declare namespace c='"+SchemaConstants.NS_C+"';\n"; private static final Trace TRACE = TraceManager.getTrace(XmlRepositoryService.class); private Collection collection; XmlRepositoryService(Collection collection) { super(); this.collection = collection; } @Override public String addObject(ObjectType object, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException { String oid = null; try { checkAndFailIfObjectAlreadyExists(object.getOid()); // generate new oid, if necessary oid = (null != object.getOid() ? object.getOid() : UUID.randomUUID().toString()); object.setOid(oid); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); String serializedObject = JAXBUtil.marshalWrap(properties, object, SchemaConstants.C_OBJECT); // FIXME: try to find another solution how to escape XQuery special // characters in XMLs serializedObject = StringUtils.replace(serializedObject, "{", "{{"); serializedObject = StringUtils.replace(serializedObject, "}", "}}"); XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( DECLARE_NAMESPACE_C) .append("let $x := ").append(serializedObject).append("\n") .append("return insert node $x into //c:objects"); TRACE.trace("generated query: " + query); service.query(query.toString()); return oid; } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } } @Override public ObjectType getObject(String oid, PropertyReferenceListType resolve, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { validateOid(oid); ByteArrayInputStream in = null; ObjectType object = null; try { XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( DECLARE_NAMESPACE_C); query.append("for $x in //c:object where $x/@oid=\"").append(oid).append("\" return $x"); TRACE.trace("generated query: " + query); ResourceSet set = service.query(query.toString()); ResourceIterator iter = set.getIterator(); // Loop through all result items. while (iter.hasMoreResources()) { Resource res = iter.nextResource(); if (null != object) { TRACE.error("More than one object with oid {} found", oid); throw new SystemException("More than one object with oid " + oid + " found"); } Object c = res.getContent(); if (c instanceof String) { in = new ByteArrayInputStream(((String) c).getBytes("UTF-8")); JAXBElement<ObjectType> o = (JAXBElement<ObjectType>) JAXBUtil.unmarshal(in); if (o != null) { object = o.getValue(); } } } } catch (UnsupportedEncodingException ex) { TRACE.error("UTF-8 is unsupported encoding", ex); throw new SystemException("UTF-8 is unsupported encoding", ex); } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } if (object == null) { throw new ObjectNotFoundException("Object not found. OID: " + oid); } return object; } @Override public ObjectListType listObjects(Class objectType, PagingType paging, OperationResult parentResult) { if (null == objectType) { TRACE.error("objectType is null"); throw new IllegalArgumentException("objectType is null"); } //validation if object type is supported ObjectTypes objType = ObjectTypes.getObjectType(objectType); String oType = objType.getValue(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); namespaces.put("idmdn", SchemaConstants.NS_C); return searchObjects(oType, paging, null, namespaces); } @Override public ObjectListType searchObjects(QueryType query, PagingType paging, OperationResult parentResult) throws SchemaException { validateQuery(query); NodeList children = query.getFilter().getChildNodes(); String objectType = null; Map<String, String> filters = new HashMap<String, String>(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); namespaces.put("idmdn", SchemaConstants.NS_C); for (int index = 0; index < children.getLength(); index++) { Node child = children.item(index); if (child.getNodeType() != Node.ELEMENT_NODE) { // Skipping all non-element nodes continue; } if (!StringUtils.equals(SchemaConstants.NS_C, child.getNamespaceURI())) { TRACE.warn("Found query's filter element from unsupported namespace. Ignoring filter {}", child); continue; } if (validateFilterElement(SchemaConstants.NS_C, "type", child)) { objectType = child.getAttributes().getNamedItem("uri").getTextContent(); } else if (validateFilterElement(SchemaConstants.NS_C, "equal", child)) { Node criteria = DOMUtil.getFirstChildElement(child); if (validateFilterElement(SchemaConstants.NS_C, "path", criteria)) { XPathType xpathType = new XPathType((Element) criteria); String parentPath = xpathType.getXPath(); Node criteriaValueNode = DOMUtil.getNextSiblingElement(criteria); processValueNode(criteriaValueNode, filters, namespaces, parentPath); } if (validateFilterElement(SchemaConstants.NS_C, "value", criteria)) { processValueNode(criteria, filters, namespaces, null); } } } return searchObjects(objectType, paging, filters, namespaces); } @Override public void modifyObject(ObjectModificationType objectChange, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { validateObjectChange(objectChange); try { // get object from repo // FIXME: possible problems with resolving property reference before // xml patching ObjectType objectType = this.getObject(objectChange.getOid(), new PropertyReferenceListType(), null); // modify the object PatchXml xmlPatchTool = new PatchXml(); String serializedObject = xmlPatchTool.applyDifferences(objectChange, objectType); // store modified object in repo // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( DECLARE_NAMESPACE_C) .append("replace node //c:object[@oid=\"").append(objectChange.getOid()) .append("\"] with ").append(serializedObject); TRACE.trace("generated query: " + query); service.query(query.toString()); } catch (PatchException ex) { TRACE.error("Failed to modify object", ex); throw new SystemException("Failed to modify object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } } @Override public void deleteObject(String oid, OperationResult parentResult) throws ObjectNotFoundException { validateOid(oid); try { ObjectType retrievedObject = getObject(oid, null, null); } catch (SchemaException ex) { TRACE.error("Schema validation problem occured while checking existence of the object before its deletion", ex); throw new SystemException("Schema validation problem occured while checking existence of the object before its deletion", ex); } ByteArrayInputStream in = null; ObjectContainerType out = null; try { // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder QUERY = new StringBuilder( DECLARE_NAMESPACE_C); QUERY.append("delete nodes //c:object[@oid=\"").append(oid).append("\"]"); service.query(QUERY.toString()); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database"); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } } @Override public PropertyAvailableValuesListType getPropertyAvailableValues(String oid, PropertyReferenceListType properties, OperationResult parentResult) throws ObjectNotFoundException { throw new UnsupportedOperationException("Not implemented yet."); } @Override public UserType listAccountShadowOwner(String accountOid, OperationResult parentResult) throws ObjectNotFoundException { Map<String, String> filters = new HashMap<String, String>(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); filters.put("c:accountRef", accountOid); ObjectListType retrievedObjects = searchObjects(ObjectTypes.USER.getObjectTypeUri(), null, filters, namespaces); List<ObjectType> objects = retrievedObjects.getObject(); if (null == retrievedObjects || objects == null || objects.size() == 0) { return null; } if (objects.size() > 1) { throw new SystemException("Found incorrect number of objects " + objects.size()); } UserType userType = (UserType) objects.get(0); return userType; } @Override public List<ResourceObjectShadowType> listResourceObjectShadows(String resourceOid, Class resourceObjectShadowType, OperationResult parentResult) throws ObjectNotFoundException { Map<String, String> filters = new HashMap<String, String>(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); filters.put("c:resourceRef", resourceOid); ObjectListType retrievedObjects = searchObjects(ObjectTypes.ACCOUNT.getObjectTypeUri(), null, filters, namespaces); @SuppressWarnings("unchecked") List<ResourceObjectShadowType> objects = (List<ResourceObjectShadowType>) CollectionUtils.collect( retrievedObjects.getObject(), new Transformer() { @Override public Object transform(final Object input) { return (ResourceObjectShadowType) input; } }); List<ResourceObjectShadowType> ros = new ArrayList<ResourceObjectShadowType>(); ros.addAll(objects); return ros; } private void checkAndFailIfObjectAlreadyExists(String oid) throws ObjectAlreadyExistsException, SchemaException { // check if object with the same oid already exists, if yes, then fail if (StringUtils.isNotEmpty(oid)) { try { ObjectType retrievedObject = getObject(oid, null, null); if (null != retrievedObject) { throw new ObjectAlreadyExistsException("Object with oid " + oid + " already exists"); } } catch (ObjectNotFoundException e) { //ignore } } } private ObjectListType searchObjects(String objectType, PagingType paging, Map<String, String> filters, Map<String, String> namespaces) { ByteArrayInputStream in = null; ObjectListType objectList = new ObjectListType(); // FIXME: objectList.count has to contain all elements that match search // criteria, but not only from paging interval objectList.setCount(0); try { XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder(); if (namespaces != null) { for (Entry<String, String> namespaceEntry: namespaces.entrySet()) { query.append("declare namespace ").append(namespaceEntry.getKey()).append("='").append(namespaceEntry.getValue()).append("';\n"); } } // FIXME: possible problems with object type checking. Now it is // simple string checking, because import schema is not supported by basex database query.append("for $x in //c:object where $x/@xsi:type=\"") .append(objectType.substring(objectType.lastIndexOf("#") + 1)).append("\""); if (null != paging && null != paging.getOffset() && null != paging.getMaxSize()) { query.append("[fn:position() = ( ").append(paging.getOffset() * paging.getMaxSize()) .append(" to ").append(((paging.getOffset() + 1) * paging.getMaxSize()) - 1) .append(") ] "); } if (filters != null) { for (Map.Entry<String, String> filterEntry : filters.entrySet()) { // FIXME: now only refs are searched by attributes values if (StringUtils.contains(filterEntry.getKey(), "Ref")) { // search based on attribute value query.append(" and $x/").append(filterEntry.getKey()).append("/@oid='") .append(filterEntry.getValue()).append("'"); } else { // search based on element value query.append(" and $x/").append(filterEntry.getKey()).append("='") .append(filterEntry.getValue()).append("'"); } } } if (null != paging && null != paging.getOrderBy()) { XPathType xpath = new XPathType(paging.getOrderBy().getProperty()); String orderBy = xpath.getXPath(); query.append(" order by $x/").append(orderBy); if (null != paging.getOrderDirection()) { query.append(" "); query.append(StringUtils.lowerCase(paging.getOrderDirection().toString())); } } query.append(" return $x "); TRACE.trace("generated query: " + query); ResourceSet set = service.query(query.toString()); ResourceIterator iter = set.getIterator(); while (iter.hasMoreResources()) { Resource res = iter.nextResource(); Object c = res.getContent(); if (c instanceof String) { in = new ByteArrayInputStream(((String) c).getBytes("UTF-8")); JAXBElement<ObjectType> o = (JAXBElement<ObjectType>) JAXBUtil.unmarshal(in); if (o != null) { objectList.getObject().add(o.getValue()); } } } } catch (UnsupportedEncodingException ex) { TRACE.error("UTF-8 is unsupported encoding", ex); throw new SystemException("UTF-8 is unsupported encoding", ex); } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } return objectList; } private void processValueNode(Node criteriaValueNode, Map<String, String> filters, Map<String, String> namespaces, String parentPath) { if (null == criteriaValueNode) { throw new IllegalArgumentException("Query filter does not contain any values to search by"); } if (validateFilterElement(SchemaConstants.NS_C, "value", criteriaValueNode)) { Node firstChild = DOMUtil.getFirstChildElement(criteriaValueNode); if (null == firstChild) { throw new IllegalArgumentException("Query filter contains empty list of values to search by"); } String lastPathSegment; String prefix; String namespace; if (!StringUtils.isEmpty(firstChild.getPrefix())) { prefix = firstChild.getPrefix(); namespace = firstChild.getNamespaceURI(); lastPathSegment = prefix + ":" + firstChild.getLocalName(); } else { prefix = "c:"; namespace = SchemaConstants.NS_C; lastPathSegment = "c:" + firstChild.getLocalName(); } // some search filters does not contain element's text value, for // these filters the value is stored in attribute String criteriaValue = StringUtils.trim(firstChild.getTextContent()); if (StringUtils.isEmpty(criteriaValue)) { // FIXME: for now it is ok to get value of the first attribute if (firstChild.getAttributes().getLength() == 1) { criteriaValue = StringUtils.trim(firstChild.getAttributes().item(0).getNodeValue()); } else { throw new IllegalArgumentException("Incorrect number of attributes in query filter " + firstChild + ", expected was 1, but actual size was " + criteriaValueNode.getAttributes().getLength()); } } if (StringUtils.isEmpty(criteriaValue)) { throw new IllegalArgumentException("Could not extract filter value from search query filter " + criteriaValueNode); } if (parentPath != null) { filters.put(parentPath + "/" + lastPathSegment, criteriaValue); } else { filters.put(lastPathSegment, criteriaValue); } namespaces.put(prefix, namespace); } else { throw new IllegalArgumentException("Found unexpected element in query filter " + criteriaValueNode); } } private boolean validateFilterElement(String elementNamespace, String elementName, Node criteria) { if (StringUtils.equals(elementName, criteria.getLocalName()) && StringUtils.equalsIgnoreCase(elementNamespace, criteria.getNamespaceURI())) { return true; } return false; } private void validateOid(String oid) { if (StringUtils.isEmpty(oid)) { throw new IllegalArgumentException("Invalid OID"); } try { UUID.fromString(oid); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid OID format " + oid); } } private void validateObjectChange(ObjectModificationType objectChange) { if (null == objectChange) { throw new IllegalArgumentException("Provided null object modifications"); } validateOid(objectChange.getOid()); if (null == objectChange.getPropertyModification() || objectChange.getPropertyModification().size() == 0) { throw new IllegalArgumentException("No property modifications provided"); } } private void validateQuery(QueryType query) { if (null == query) { throw new IllegalArgumentException("Provided null query"); } if (null == query.getFilter()) { throw new IllegalArgumentException("No filter in query"); } } }
repo/repo-basex-impl/src/main/java/com/evolveum/midpoint/repo/xml/XmlRepositoryService.java
/* * Copyright (c) 2011 Evolveum * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the License). You may not use this file except in * compliance with the License. * * You can obtain a copy of the License at * http://www.opensource.org/licenses/cddl1 or * CDDLv1.0.txt file in the source code distribution. * See the License for the specific language governing * permission and limitations under the License. * * If applicable, add the following below the CDDL Header, * with the fields enclosed by brackets [] replaced by * your own identifying information: * * Portions Copyrighted 2011 [name of copyright owner] * Portions Copyrighted 2011 Igor Farinic */ package com.evolveum.midpoint.repo.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceIterator; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XPathQueryService; import com.evolveum.midpoint.api.logging.Trace; import com.evolveum.midpoint.common.jaxb.JAXBUtil; import com.evolveum.midpoint.common.patch.PatchXml; import com.evolveum.midpoint.common.result.OperationResult; import com.evolveum.midpoint.logging.TraceManager; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.ObjectTypes; import com.evolveum.midpoint.schema.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.schema.exception.ObjectNotFoundException; import com.evolveum.midpoint.schema.exception.SchemaException; import com.evolveum.midpoint.schema.exception.SystemException; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.patch.PatchException; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectContainerType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PagingType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PropertyAvailableValuesListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_1.UserType; import com.evolveum.midpoint.xml.schema.SchemaConstants; import com.evolveum.midpoint.xml.schema.XPathType; public class XmlRepositoryService implements RepositoryService { private static final String DECLARE_NAMESPACE_C = "declare namespace c='"+SchemaConstants.NS_C+"';\n"; private static final Trace TRACE = TraceManager.getTrace(XmlRepositoryService.class); private Collection collection; XmlRepositoryService(Collection collection) { super(); this.collection = collection; } @Override public String addObject(ObjectType object, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException { String oid = null; try { checkAndFailIfObjectAlreadyExists(object.getOid()); // generate new oid, if necessary oid = (null != object.getOid() ? object.getOid() : UUID.randomUUID().toString()); object.setOid(oid); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); String serializedObject = JAXBUtil.marshalWrap(properties, object, SchemaConstants.C_OBJECT); // FIXME: try to find another solution how to escape XQuery special // characters in XMLs serializedObject = StringUtils.replace(serializedObject, "{", "{{"); serializedObject = StringUtils.replace(serializedObject, "}", "}}"); XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( DECLARE_NAMESPACE_C) .append("let $x := ").append(serializedObject).append("\n") .append("return insert node $x into //c:objects"); TRACE.trace("generated query: " + query); service.query(query.toString()); return oid; } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } } @Override public ObjectType getObject(String oid, PropertyReferenceListType resolve, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { validateOid(oid); ByteArrayInputStream in = null; ObjectType object = null; try { XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( DECLARE_NAMESPACE_C); query.append("for $x in //c:object where $x/@oid=\"").append(oid).append("\" return $x"); TRACE.trace("generated query: " + query); ResourceSet set = service.query(query.toString()); ResourceIterator iter = set.getIterator(); // Loop through all result items. while (iter.hasMoreResources()) { Resource res = iter.nextResource(); if (null != object) { TRACE.error("More than one object with oid {} found", oid); throw new SystemException("More than one object with oid " + oid + " found"); } Object c = res.getContent(); if (c instanceof String) { in = new ByteArrayInputStream(((String) c).getBytes("UTF-8")); JAXBElement<ObjectType> o = (JAXBElement<ObjectType>) JAXBUtil.unmarshal(in); if (o != null) { object = o.getValue(); } } } } catch (UnsupportedEncodingException ex) { TRACE.error("UTF-8 is unsupported encoding", ex); throw new SystemException("UTF-8 is unsupported encoding", ex); } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } if (object == null) { throw new ObjectNotFoundException("Object not found. OID: " + oid); } return object; } @Override public ObjectListType listObjects(Class objectType, PagingType paging, OperationResult parentResult) { if (null == objectType) { TRACE.error("objectType is null"); throw new IllegalArgumentException("objectType is null"); } //validation if object type is supported ObjectTypes objType = ObjectTypes.getObjectType(objectType); String oType = objType.getValue(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); namespaces.put("idmdn", SchemaConstants.NS_C); return searchObjects(oType, paging, null, namespaces); } @Override public ObjectListType searchObjects(QueryType query, PagingType paging, OperationResult parentResult) throws SchemaException { validateQuery(query); NodeList children = query.getFilter().getChildNodes(); String objectType = null; Map<String, String> filters = new HashMap<String, String>(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); namespaces.put("idmdn", SchemaConstants.NS_C); for (int index = 0; index < children.getLength(); index++) { Node child = children.item(index); if (child.getNodeType() != Node.ELEMENT_NODE) { // Skipping all non-element nodes continue; } if (!StringUtils.equals(SchemaConstants.NS_C, child.getNamespaceURI())) { TRACE.warn("Found query's filter element from unsupported namespace. Ignoring filter {}", child); continue; } if (validateFilterElement(SchemaConstants.NS_C, "type", child)) { objectType = child.getAttributes().getNamedItem("uri").getTextContent(); } else if (validateFilterElement(SchemaConstants.NS_C, "equal", child)) { Node criteria = DOMUtil.getFirstChildElement(child); if (validateFilterElement(SchemaConstants.NS_C, "path", criteria)) { XPathType xpathType = new XPathType((Element) criteria); String parentPath = xpathType.getXPath(); Node criteriaValueNode = DOMUtil.getNextSiblingElement(criteria); processValueNode(criteriaValueNode, filters, namespaces, parentPath); } if (validateFilterElement(SchemaConstants.NS_C, "value", criteria)) { processValueNode(criteria, filters, namespaces, null); } } } return searchObjects(objectType, paging, filters, namespaces); } @Override public void modifyObject(ObjectModificationType objectChange, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { validateObjectChange(objectChange); try { // get object from repo // FIXME: possible problems with resolving property reference before // xml patching ObjectType objectType = this.getObject(objectChange.getOid(), new PropertyReferenceListType(), null); // modify the object PatchXml xmlPatchTool = new PatchXml(); String serializedObject = xmlPatchTool.applyDifferences(objectChange, objectType); // store modified object in repo // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( DECLARE_NAMESPACE_C) .append("replace node //c:object[@oid=\"").append(objectChange.getOid()) .append("\"] with ").append(serializedObject); TRACE.trace("generated query: " + query); service.query(query.toString()); } catch (PatchException ex) { TRACE.error("Failed to modify object", ex); throw new SystemException("Failed to modify object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } } @Override public void deleteObject(String oid, OperationResult parentResult) throws ObjectNotFoundException { validateOid(oid); try { ObjectType retrievedObject = getObject(oid, null, null); } catch (SchemaException ex) { TRACE.error("Schema validation problem occured while checking existence of the object before its deletion", ex); throw new SystemException("Schema validation problem occured while checking existence of the object before its deletion", ex); } ByteArrayInputStream in = null; ObjectContainerType out = null; try { // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder QUERY = new StringBuilder( DECLARE_NAMESPACE_C); QUERY.append("delete nodes //c:object[@oid=\"").append(oid).append("\"]"); service.query(QUERY.toString()); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database"); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } } @Override public PropertyAvailableValuesListType getPropertyAvailableValues(String oid, PropertyReferenceListType properties, OperationResult parentResult) throws ObjectNotFoundException { throw new UnsupportedOperationException("Not implemented yet."); } @Override public UserType listAccountShadowOwner(String accountOid, OperationResult parentResult) throws ObjectNotFoundException { Map<String, String> filters = new HashMap<String, String>(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); filters.put("c:accountRef", accountOid); ObjectListType retrievedObjects = searchObjects(ObjectTypes.USER.getObjectTypeUri(), null, filters, namespaces); List<ObjectType> objects = retrievedObjects.getObject(); if (null == retrievedObjects || objects == null || objects.size() == 0) { return null; } if (objects.size() > 1) { throw new SystemException("Found incorrect number of objects " + objects.size()); } UserType userType = (UserType) objects.get(0); return userType; } @Override public List<ResourceObjectShadowType> listResourceObjectShadows(String resourceOid, Class resourceObjectShadowType, OperationResult parentResult) throws ObjectNotFoundException { Map<String, String> filters = new HashMap<String, String>(); Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("c", SchemaConstants.NS_C); filters.put("c:resourceRef", resourceOid); ObjectListType retrievedObjects = searchObjects(ObjectTypes.ACCOUNT.getObjectTypeUri(), null, filters, namespaces); @SuppressWarnings("unchecked") List<ResourceObjectShadowType> objects = (List<ResourceObjectShadowType>) CollectionUtils.collect( retrievedObjects.getObject(), new Transformer() { @Override public Object transform(final Object input) { return (ResourceObjectShadowType) input; } }); List<ResourceObjectShadowType> ros = new ArrayList<ResourceObjectShadowType>(); ros.addAll(objects); return ros; } private void checkAndFailIfObjectAlreadyExists(String oid) throws ObjectAlreadyExistsException, SchemaException { // check if object with the same oid already exists, if yes, then fail if (StringUtils.isNotEmpty(oid)) { try { ObjectType retrievedObject = getObject(oid, null, null); if (null != retrievedObject) { throw new ObjectAlreadyExistsException("Object with oid " + oid + " already exists"); } } catch (ObjectNotFoundException e) { //ignore } } } private ObjectListType searchObjects(String objectType, PagingType paging, Map<String, String> filters, Map<String, String> namespaces) { ByteArrayInputStream in = null; ObjectListType objectList = new ObjectListType(); // FIXME: objectList.count has to contain all elements that match search // criteria, but not only from paging interval objectList.setCount(0); try { XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder(); if (namespaces != null) { for (Entry<String, String> namespaceEntry: namespaces.entrySet()) { query.append("declare namespace ").append(namespaceEntry.getKey()).append("='").append(namespaceEntry.getValue()).append("';\n"); } } // FIXME: possible problems with object type checking. Now it is // simple string checking, because import schema is not supported by basex database query.append("for $x in //c:object where $x/@xsi:type=\"") .append(objectType.substring(objectType.lastIndexOf("#") + 1)).append("\""); if (null != paging && null != paging.getOffset() && null != paging.getMaxSize()) { query.append("[fn:position() = ( ").append(paging.getOffset() * paging.getMaxSize()) .append(" to ").append(((paging.getOffset() + 1) * paging.getMaxSize()) - 1) .append(") ] "); } if (filters != null) { for (Map.Entry<String, String> filterEntry : filters.entrySet()) { // FIXME: now only refs are searched by attributes values if (StringUtils.contains(filterEntry.getKey(), "Ref")) { // search based on attribute value query.append(" and $x/").append(filterEntry.getKey()).append("/@oid='") .append(filterEntry.getValue()).append("'"); } else { // search based on element value query.append(" and $x/").append(filterEntry.getKey()).append("='") .append(filterEntry.getValue()).append("'"); } } } if (null != paging && null != paging.getOrderBy()) { XPathType xpath = new XPathType(paging.getOrderBy().getProperty()); String orderBy = xpath.getXPath(); query.append(" order by $x/").append(orderBy); if (null != paging.getOrderDirection()) { query.append(" "); query.append(StringUtils.lowerCase(paging.getOrderDirection().toString())); } } query.append(" return $x "); TRACE.trace("generated query: " + query); ResourceSet set = service.query(query.toString()); ResourceIterator iter = set.getIterator(); while (iter.hasMoreResources()) { Resource res = iter.nextResource(); Object c = res.getContent(); if (c instanceof String) { in = new ByteArrayInputStream(((String) c).getBytes("UTF-8")); JAXBElement<ObjectType> o = (JAXBElement<ObjectType>) JAXBUtil.unmarshal(in); if (o != null) { objectList.getObject().add(o.getValue()); } } } } catch (UnsupportedEncodingException ex) { TRACE.error("UTF-8 is unsupported encoding", ex); throw new SystemException("UTF-8 is unsupported encoding", ex); } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } return objectList; } private void processValueNode(Node criteriaValueNode, Map<String, String> filters, Map<String, String> namespaces, String parentPath) { if (null == criteriaValueNode) { throw new IllegalArgumentException("Query filter does not contain any values to search by"); } if (validateFilterElement(SchemaConstants.NS_C, "value", criteriaValueNode)) { Node firstChild = DOMUtil.getFirstChildElement(criteriaValueNode); if (null == firstChild) { throw new IllegalArgumentException("Query filter contains empty list of values to search by"); } // FIXME: possible problem with prefixes String lastPathSegment; String prefix; String namespace; if (!StringUtils.isEmpty(firstChild.getPrefix())) { prefix = firstChild.getPrefix(); namespace = firstChild.getNamespaceURI(); lastPathSegment = prefix + ":" + firstChild.getLocalName(); } else { prefix = "c:"; namespace = SchemaConstants.NS_C; lastPathSegment = "c:" + firstChild.getLocalName(); } // some search filters does not contain element's text value, for // these filters the value is stored in attribute String criteriaValue = StringUtils.trim(firstChild.getTextContent()); if (StringUtils.isEmpty(criteriaValue)) { // FIXME: for now it is ok to get value of the first attribute if (firstChild.getAttributes().getLength() == 1) { criteriaValue = StringUtils.trim(firstChild.getAttributes().item(0).getNodeValue()); } else { throw new IllegalArgumentException("Incorrect number of attributes in query filter " + firstChild + ", expected was 1, but actual size was " + criteriaValueNode.getAttributes().getLength()); } } if (StringUtils.isEmpty(criteriaValue)) { throw new IllegalArgumentException("Could not extract filter value from search query filter " + criteriaValueNode); } if (parentPath != null) { filters.put(parentPath + "/" + lastPathSegment, criteriaValue); } else { filters.put(lastPathSegment, criteriaValue); } namespaces.put(prefix, namespace); } else { throw new IllegalArgumentException("Found unexpected element in query filter " + criteriaValueNode); } } private boolean validateFilterElement(String elementNamespace, String elementName, Node criteria) { if (StringUtils.equals(elementName, criteria.getLocalName()) && StringUtils.equalsIgnoreCase(elementNamespace, criteria.getNamespaceURI())) { return true; } return false; } private void validateOid(String oid) { if (StringUtils.isEmpty(oid)) { throw new IllegalArgumentException("Invalid OID"); } try { UUID.fromString(oid); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid OID format " + oid); } } private void validateObjectChange(ObjectModificationType objectChange) { if (null == objectChange) { throw new IllegalArgumentException("Provided null object modifications"); } validateOid(objectChange.getOid()); if (null == objectChange.getPropertyModification() || objectChange.getPropertyModification().size() == 0) { throw new IllegalArgumentException("No property modifications provided"); } } private void validateQuery(QueryType query) { if (null == query) { throw new IllegalArgumentException("Provided null query"); } if (null == query.getFilter()) { throw new IllegalArgumentException("No filter in query"); } } }
removed implemented FIXME
repo/repo-basex-impl/src/main/java/com/evolveum/midpoint/repo/xml/XmlRepositoryService.java
removed implemented FIXME
<ide><path>epo/repo-basex-impl/src/main/java/com/evolveum/midpoint/repo/xml/XmlRepositoryService.java <ide> if (null == firstChild) { <ide> throw new IllegalArgumentException("Query filter contains empty list of values to search by"); <ide> } <del> // FIXME: possible problem with prefixes <ide> String lastPathSegment; <ide> String prefix; <ide> String namespace;
Java
apache-2.0
a52d49c1e31534b6a9958961336232212d07dcf4
0
santhosh-tekuri/jlibs,santhosh-tekuri/jlibs
/** * JLibs: Common Utilities for Java * Copyright (C) 2009 Santhosh Kumar T <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package jlibs.xml.sax.async; import jlibs.core.io.BOM; import jlibs.core.io.IOUtil; import jlibs.core.io.UnicodeInputStream; import jlibs.core.net.URLUtil; import jlibs.nbp.Chars; import jlibs.nbp.NBHandler; import jlibs.xml.ClarkName; import jlibs.xml.NamespaceMap; import jlibs.xml.sax.AbstractXMLReader; import jlibs.xml.sax.SAXUtil; import jlibs.xml.xsl.TransformerUtil; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXParseException; import org.xml.sax.ext.Locator2; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; import javax.xml.XMLConstants; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.*; /** * @author Santhosh Kumar T */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) public class AsyncXMLReader extends AbstractXMLReader implements NBHandler<SAXException>, Locator2{ private static Map<String, char[]> defaultEntities = new HashMap<String, char[]>(); static{ defaultEntities.put("amp", new char[]{ '&' }); defaultEntities.put("lt", new char[]{ '<' }); defaultEntities.put("gt", new char[]{ '>' }); defaultEntities.put("apos", new char[]{ '\'' }); defaultEntities.put("quot", new char[]{ '"' }); } private int iProlog = -1; private XMLScanner scanner = new XMLScanner(this, XMLScanner.RULE_DOCUMENT){ protected void consumed(int ch){ consumed = true; int line = location.getLineNumber(); boolean addToBuffer = location.consume(ch); if(addToBuffer && buffer.isBufferring()) buffer.append(location.getLineNumber()>line ? '\n' : ch); } @Override public void write(ByteBuffer in, boolean eof) throws IOException{ if(iProlog==-1){ if(in.remaining()>=4){ byte marker[] = new byte[]{ in.get(0), in.get(1), in.get(2), in.get(3) }; BOM bom = BOM.get(marker, true); String encoding; if(bom!=null){ in.position(bom.with().length); encoding = bom.encoding(); }else{ bom = BOM.get(marker, false); encoding = bom!=null ? bom.encoding() : "UTF-8"; } decoder = Charset.forName(encoding).newDecoder(); if(!encoding.equals("UTF-8")){ decoder.onMalformedInput(CodingErrorAction.REPLACE) .onMalformedInput(CodingErrorAction.REPLACE); } iProlog = 0; }else{ if(eof) super.write(in, true); return; } } while(iProlog<6){ if(eof){ String str = "<?xml "; for(int i=0; i<iProlog; i++) consume(str.charAt(i)); super.write(in, true); return; } CharBuffer charBuffer = CharBuffer.allocate(1); CoderResult coderResult = decoder.decode(in, charBuffer, eof); if(coderResult.isUnderflow() || coderResult.isOverflow()){ char ch = charBuffer.array()[0]; if(isPrologStart(ch)){ iProlog++; if(iProlog==6){ consume('<'); consume('?'); consume('x'); consume('m'); consume('l'); consume(' '); } if(coderResult.isOverflow()) continue; else return; }else{ String str = "<?xml "; for(int i=0; i<iProlog; i++) consume(str.charAt(i)); consume(ch); iProlog = 7; } }else encodingError(coderResult); } if(iProlog==6 && !eof){ while(!xdeclEnd){ CharBuffer charBuffer = CharBuffer.allocate(1); CoderResult coderResult = decoder.decode(in, charBuffer, eof); if(coderResult.isUnderflow() || coderResult.isOverflow()){ char ch = charBuffer.array()[0]; consume(ch); if(coderResult.isUnderflow()) return; }else encodingError(coderResult); } String detectedEncoding = decoder.charset().name().toUpperCase(Locale.ENGLISH); String declaredEncoding = encoding.toUpperCase(Locale.ENGLISH); if(!detectedEncoding.equals(declaredEncoding)){ if(detectedEncoding.startsWith("UTF-16") && declaredEncoding.equals("UTF-16")) ; //donothing else if(!detectedEncoding.equals(encoding)){ decoder = Charset.forName(encoding).newDecoder(); if(!encoding.equals("UTF-8")){ decoder.onMalformedInput(CodingErrorAction.REPLACE) .onMalformedInput(CodingErrorAction.REPLACE); } } } iProlog = 7; } super.write(in, eof); } private boolean isPrologStart(char ch){ switch(iProlog){ case 0: return ch=='<'; case 1: return ch=='?'; case 2: return ch=='x'; case 3: return ch=='m'; case 4: return ch=='l'; case 5: return ch==0x20 || ch==0x9 || ch==0xa || ch==0xd; default: throw new Error("impossible"); } } }; @Override public void setFeature(String name, boolean value) throws SAXNotRecognizedException{ try{ super.setFeature(name, value); } catch(SAXNotRecognizedException e){ // ignore } } public Writer getWriter() throws SAXException{ scanner.reset(); documentStart(); return scanner.writer; } @Override public void parse(InputSource input) throws IOException, SAXException{ Reader charStream = input.getCharacterStream(); if(charStream !=null) IOUtil.pump(charStream, getWriter(), true, true); else{ InputStream inputStream = input.getByteStream(); if(inputStream!=null) parse(inputStream); else parse(input.getSystemId()); } } @Override public void parse(String systemId) throws IOException, SAXException{ // special handling for http url's like redirect, get encoding information from http headers URL url = URLUtil.toURL(systemId); if(url.getProtocol().equals("file")){ scanner.reset(); documentStart(); try{ FileChannel channel = new FileInputStream(new File(url.toURI())).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(100); while(channel.read(buffer)!=-1){ buffer.flip(); scanner.write(buffer, false); buffer.compact(); } buffer.flip(); scanner.write(buffer, true); }catch(URISyntaxException ex){ throw new IOException(ex); } }else parse(url.openStream()); } private void parse(InputStream in) throws IOException, SAXException{ UnicodeInputStream input = new UnicodeInputStream(in); String encoding = input.bom!=null ? input.bom.encoding() : IOUtil.UTF_8.name(); IOUtil.pump(new InputStreamReader(input, encoding), getWriter(), true, true); } /*-------------------------------------------------[ Locator ]---------------------------------------------------*/ @Override public String getPublicId(){ return null; } @Override public String getSystemId(){ return null; } @Override public int getLineNumber(){ return scanner.location.getLineNumber(); } @Override public int getColumnNumber(){ return scanner.location.getColumnNumber(); } @Override public String getXMLVersion(){ return "1.0"; } @Override public String getEncoding(){ return encoding; } /*-------------------------------------------------[ Document ]---------------------------------------------------*/ private void documentStart() throws SAXException{ iProlog = -1; encoding = "UTF-8"; xdeclEnd = false; clearQName(); value.setLength(0); valueStarted = false; entityValue = false; namespaces = new NamespaceMap(); attributes.clear(); elementsPrefixes.clear(); elementsLocalNames.clear(); elementsQNames.clear(); piTarget = null; dtdRoot = null; systemID = null; publicID = null; notationName = null; entityName = null; entities.clear(); entityStack.clear(); dtdAttributes.clear(); dtdElementName = null; attributeList = null; dtdAttribute = null; handler.setDocumentLocator(this); handler.startDocument(); } /*-------------------------------------------------[ XML Decleration ]---------------------------------------------------*/ void version(Chars data) throws SAXException{ if(!"1.0".contentEquals(data)) fatalError("Unsupported XML Version: "+data); } private String encoding; void encoding(Chars data) throws SAXException{ encoding = data.toString(); } void standalone(Chars data){ System.out.println("standalone: "+data); } private boolean xdeclEnd; void xdeclEnd(){ xdeclEnd = true; } /*-------------------------------------------------[ QName ]---------------------------------------------------*/ private String prefix = ""; void prefix(Chars data){ prefix = data.toString(); } private String localName; void localName(Chars data){ localName = data.toString(); } private String qname; void qname(Chars data){ qname = data.toString(); } private void clearQName(){ prefix = ""; localName = null; qname = null; } /*-------------------------------------------------[ Value ]---------------------------------------------------*/ private StringBuilder value = new StringBuilder(); private boolean valueStarted = true; private boolean entityValue = false; void valueStart(){ value.setLength(0); valueStarted = true; entityValue = false; } void entityValue(){ entityValue = true; } void rawValue(Chars data){ char[] chars = data.array(); int end = data.offset() + data.length(); for(int i=data.offset(); i<end; i++){ char ch = chars[i]; if(ch=='\n' || ch=='\r' || ch=='\t') ch = ' '; value.append(ch); } } private boolean isValid(int ch){ return (ch==0x9 || ch==0xa || ch==0xd) || (ch>=0x20 && ch<=0xd7ff) || (ch>=0xe000 && ch<=0xfffd) || (ch>=0x10000 && ch<=0x10ffff); } void hexCode(Chars data) throws SAXException{ int codePoint = Integer.parseInt(data.toString(), 16); if(!isValid(codePoint)) fatalError("invalid xml character"); if(valueStarted) value.appendCodePoint(codePoint); else{ char chars[] = Character.toChars(codePoint); handler.characters(chars, 0, chars.length); } } void asciiCode(Chars data) throws SAXException{ int codePoint = Integer.parseInt(data.toString(), 10); if(!isValid(codePoint)) fatalError("invalid xml character"); if(valueStarted) value.appendCodePoint(codePoint); else{ char chars[] = Character.toChars(codePoint); handler.characters(chars, 0, chars.length); } } private ArrayDeque<String> entityStack = new ArrayDeque<String>(); @SuppressWarnings({"ConstantConditions"}) void entityReference(Chars data) throws SAXException{ if(entityValue){ value.append('&').append(data).append(';'); return; } String entity = data.toString(); char[] entityValue = defaultEntities.get(entity); if(entityValue!=null){ if(valueStarted) value.append(entityValue); else handler.characters(entityValue, 0, entityValue.length); }else{ entityValue = entities.get(entity); if(entityValue==null) fatalError("Undefined entityReference: "+entity); int rule; if(valueStarted){ char chars[] = new char[entityValue.length]; for(int i=chars.length-1; i>=0; i--){ char ch = entityValue[i]; if(ch=='\n' || ch=='\r' || ch=='\t') ch = ' '; chars[i] = ch; } entityValue = chars; rule = XMLScanner.RULE_VALUE_ENTITY; }else rule = XMLScanner.RULE_ELEM_ENTITY; if(entityStack.contains(entity)) fatalError("found recursion in entity expansion :"+entity); entityStack.push(entity); try{ XMLScanner entityValueScanner = new XMLScanner(this, rule); entityValueScanner.writer.write(entityValue); entityValueScanner.writer.close(); }catch(IOException ex){ throw new RuntimeException(ex); }finally{ entityStack.pop(); } } } void valueEnd(){ valueStarted = false; entityValue = false; } /*-------------------------------------------------[ Start Element ]---------------------------------------------------*/ private NamespaceMap namespaces = new NamespaceMap(); private AttributesImpl attributes = new AttributesImpl(); private Deque<String> elementsPrefixes = new ArrayDeque<String>(); private Deque<String> elementsLocalNames = new ArrayDeque<String>(); private Deque<String> elementsQNames = new ArrayDeque<String>(); void attributesStart(){ elementsPrefixes.push(prefix); elementsLocalNames.push(localName); elementsQNames.push(qname); clearQName(); namespaces = new NamespaceMap(namespaces); attributes.clear(); } void attributeEnd() throws SAXException{ String type = "CDATA"; Map<String, DTDAttribute> attrList = dtdAttributes.get(elementsQNames.peek()); if(attrList!=null){ DTDAttribute dtdAttr = attrList.get(qname); if(dtdAttr!=null){ if(dtdAttr.type==AttributeType.ENUMERATION) type = "NMTOKEN"; else type = dtdAttr.type.name(); } } String value = this.value.toString(); if(type.equals("NMTOKEN")) value = value.trim(); else if(type.equals("NMTOKENS")){ char[] buffer = value.toCharArray(); int write = 0; int lastWrite = 0; boolean wroteOne = false; int read = 0; while(read<buffer.length && buffer[read]==' '){ read++; } int len = buffer.length; while(len<read && buffer[len-1]==' ') len--; while(read<len){ if (buffer[read]==' '){ if (wroteOne) buffer[write++] = ' '; do{ read++; }while(read<len && buffer[read]==' '); }else{ buffer[write++] = buffer[read++]; wroteOne = true; lastWrite = write; } } value = new String(buffer, 0, lastWrite); } if(qname.equals("xmlns")){ namespaces.put("", value); handler.startPrefixMapping("", value); }else if(prefix.equals("xmlns")){ if(localName.equals(XMLConstants.XML_NS_PREFIX)){ if(!value.equals(XMLConstants.XML_NS_URI)){ clearQName(); fatalError("prefix "+XMLConstants.XML_NS_PREFIX+" must refer to "+XMLConstants.XML_NS_URI); } }else if(localName.equals(XMLConstants.XMLNS_ATTRIBUTE)){ clearQName(); fatalError("prefix "+XMLConstants.XMLNS_ATTRIBUTE+" must not be declared"); }else{ if(value.equals(XMLConstants.XML_NS_URI)){ clearQName(); fatalError(XMLConstants.XML_NS_URI+" must be bound to "+XMLConstants.XML_NS_PREFIX); }else if(value.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)){ clearQName(); fatalError(XMLConstants.XMLNS_ATTRIBUTE_NS_URI+" must be bound to "+XMLConstants.XMLNS_ATTRIBUTE); }else{ if(value.length()==0) fatalError("No Prefix Undeclaring: "+localName); namespaces.put(localName, value); handler.startPrefixMapping(localName, value); } } }else{ attributes.addAttribute(prefix, localName, qname, type, value); } clearQName(); } private Set<String> attributeNames = new HashSet<String>(); void attributesEnd() throws SAXException{ attributeNames.clear(); int attrCount = attributes.getLength(); for(int i=0; i<attrCount; i++){ String prefix = attributes.getURI(i); String uri = ""; if(prefix.length()>0){ uri = namespaces.getNamespaceURI(prefix); if(uri==null) fatalError("Unbound prefix: "+prefix); attributes.setURI(i, uri); } String clarkName = ClarkName.valueOf(uri, attributes.getLocalName(i)); if(!attributeNames.add(clarkName)) fatalError("Attribute "+clarkName+" appears more than once in element"); } String elemQName = elementsQNames.peek(); Map<String, DTDAttribute> attList = dtdAttributes.get(elemQName); if(attList!=null){ for(DTDAttribute dtdAttr: attList.values()){ if(dtdAttr.valueType==AttributeValueType.DEFAULT || dtdAttr.valueType==AttributeValueType.FIXED){ int index = attributes.getIndex(dtdAttr.name); if(index==-1){ if(!dtdAttr.name.equals("xmlns") && !dtdAttr.name.startsWith("xmlns:")) attributes.addAttribute("", dtdAttr.name, dtdAttr.name, dtdAttr.type.name(), dtdAttr.value); } } } } String prefix = elementsPrefixes.peek(); String namespaceURI = namespaces.getNamespaceURI(prefix); if(namespaceURI==null) fatalError("Unbound prefix: "+prefix); handler.startElement(namespaceURI, elementsLocalNames.peek(), elementsQNames.peek(), attributes); } void emptyElementEnd() throws SAXException{ elementEnd(elementsQNames.pop()); } void elementEnd() throws SAXException{ String startQName = elementsQNames.pop(); if(!startQName.equals(qname)) fatalError("expected </"+startQName+">"); elementEnd(qname); } private void elementEnd(String qname) throws SAXException{ String prefix = elementsPrefixes.pop(); String namespaceURI = namespaces.getNamespaceURI(prefix); if(namespaceURI==null) fatalError("Unbound prefix: "+prefix); handler.endElement(namespaceURI, elementsLocalNames.pop(), qname); if(namespaces.map()!=null){ for(String nsPrefix: namespaces.map().keySet()) handler.endPrefixMapping(nsPrefix); } namespaces = namespaces.parent(); clearQName(); } /*-------------------------------------------------[ PI ]---------------------------------------------------*/ private String piTarget; void piTarget(Chars data){ piTarget = data.toString(); } void piData(Chars piData) throws SAXException{ handler.processingInstruction(piTarget, piData.length()>0 ? piData.toString() : ""); } void piData() throws SAXException{ handler.processingInstruction(piTarget, ""); } /*-------------------------------------------------[ Misc ]---------------------------------------------------*/ void characters(Chars data) throws SAXException{ handler.characters(data.array(), data.offset(), data.length()); } void cdata(Chars data) throws SAXException{ handler.startCDATA(); handler.characters(data.array(), data.offset(), data.length()); handler.endCDATA(); } void comment(Chars data) throws SAXException{ handler.comment(data.array(), data.offset(), data.length()); } @Override public void fatalError(String message) throws SAXException{ fatalError(new SAXParseException(message, this)); } public void fatalError(SAXParseException ex) throws SAXException{ try{ handler.fatalError(ex); throw ex; }finally{ handler.endDocument(); } } @Override public void onSuccessful() throws SAXException{ if(entityStack.isEmpty()) handler.endDocument(); } /*-------------------------------------------------[ DTD ]---------------------------------------------------*/ private String dtdRoot; void dtdRoot(Chars data){ dtdRoot = data.toString(); } private String systemID; void systemID(Chars data){ systemID = data.toString(); } private String publicID; void publicID(Chars data){ publicID = data.toString(); } void dtdStart() throws SAXException{ handler.startDTD(dtdRoot, publicID, systemID); publicID = systemID = null; } private String notationName; void notationName(Chars data){ notationName = data.toString(); } void notationEnd() throws SAXException{ handler.notationDecl(notationName, publicID, systemID); } void dtdElement(Chars data){ System.out.println("dtdElement: "+data); } private String entityName; void entityName(Chars data){ entityName = data.toString(); } private Map<String, char[]> entities = new HashMap<String, char[]>(); void entityEnd(){ if(value!=null){ entities.put(entityName, value.toString().toCharArray()); value.setLength(0); } } public void dtdEnd() throws SAXException{ handler.endDTD(); dtdRoot = null; } /*-------------------------------------------------[ DTD Attributes ]---------------------------------------------------*/ private Map<String, Map<String, DTDAttribute>> dtdAttributes = new HashMap<String, Map<String, DTDAttribute>>(); private String dtdElementName; private Map<String, DTDAttribute> attributeList; private DTDAttribute dtdAttribute; void dtdAttributesStart(Chars data){ dtdElementName = data.toString(); attributeList = dtdAttributes.get(dtdElementName); if(attributeList==null) dtdAttributes.put(dtdElementName, attributeList=new HashMap<String, DTDAttribute>()); } void dtdAttribute(Chars data){ String attributeName = data.toString(); if(attributeList.get(attributeName)==null){ dtdAttribute = new DTDAttribute(); dtdAttribute.name = attributeName; attributeList.put(attributeName, dtdAttribute); }else dtdAttribute = null; } void cdataAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.CDATA; } void idAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.ID; } void idRefAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.IDREF; } void idRefsAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.IDREFS; } void nmtokenAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.NMTOKEN; } void nmtokensAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.NMTOKENS; } void entityAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.ENTITY; } void entitiesAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.ENTITIES; } void enumerationAttribute(){ if(dtdAttribute!=null){ dtdAttribute.type = AttributeType.ENUMERATION; dtdAttribute.validValues = new ArrayList<String>(); } } void notationAttribute(){ if(dtdAttribute!=null){ dtdAttribute.type = AttributeType.NOTATION; dtdAttribute.validValues = new ArrayList<String>(); } } void attributeEnumValue(Chars data){ if(dtdAttribute!=null) dtdAttribute.validValues.add(data.toString()); } void attributeNotationValue(Chars data){ if(dtdAttribute!=null) dtdAttribute.validValues.add(data.toString()); } void attributeDefaultValue() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.DEFAULT; dtdAttribute.value = value.toString(); fireDTDAttributeEvent(); } value.setLength(0); } void attributeRequired() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.REQUIRED; fireDTDAttributeEvent(); } } void attributeImplied() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.IMPLIED; fireDTDAttributeEvent(); } } void attributeFixedValue() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.FIXED; dtdAttribute.value = value.toString(); fireDTDAttributeEvent(); } value.setLength(0); } private void fireDTDAttributeEvent() throws SAXException{ handler.attributeDecl(dtdElementName, dtdAttribute.name, dtdAttribute.type.toString(dtdAttribute.validValues), dtdAttribute.valueType.mode, dtdAttribute.value); } void dtdAttributesEnd(){ System.out.println("dtdAttributesEnd"); } /*-------------------------------------------------[ Test ]---------------------------------------------------*/ public static void main(String[] args) throws Exception{ AsyncXMLReader parser = new AsyncXMLReader(); TransformerHandler handler = TransformerUtil.newTransformerHandler(null, true, -1, null); handler.setResult(new StreamResult(System.out)); SAXUtil.setHandler(parser, handler); // String xml = "<root attr1='value1'/>"; // parser.parse(new InputSource(new StringReader(xml))); // String file = "/Users/santhosh/projects/SAXTest/xmlconf/xmltest/valid/sa/049.xml"; // with BOM // String file = "/Users/santhosh/projects/SAXTest/xmlconf/ibm/valid/P59/ibm59v01.xml"; String file = "/Users/santhosh/projects/jlibs/examples/resources/xmlFiles/test.xml"; SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); try{ factory.newSAXParser().parse(file, new DefaultHandler(){ @Override public void characters(char[] ch, int start, int length) throws SAXException{ super.characters(ch, start, length); //To change body of overridden methods use File | Settings | File Templates. } }); }catch(Exception ex){ ex.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. System.out.println("=========================="); } IOUtil.pump(new InputStreamReader(new FileInputStream(file), "UTF-8"), new StringWriter(), true, true); // IOUtil.pump(new UTF8Reader(new FileInputStream(file)), new StringWriter(), true, true); parser.parse(new InputSource(file)); // parser.scanner.write("<root attr1='value1'/>"); // parser.scanner.close(); } }
xml/src/main/java/jlibs/xml/sax/async/AsyncXMLReader.java
/** * JLibs: Common Utilities for Java * Copyright (C) 2009 Santhosh Kumar T <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package jlibs.xml.sax.async; import jlibs.core.io.BOM; import jlibs.core.io.IOUtil; import jlibs.core.io.UnicodeInputStream; import jlibs.core.net.URLUtil; import jlibs.nbp.Chars; import jlibs.nbp.NBHandler; import jlibs.xml.ClarkName; import jlibs.xml.NamespaceMap; import jlibs.xml.sax.AbstractXMLReader; import jlibs.xml.sax.SAXUtil; import jlibs.xml.xsl.TransformerUtil; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXParseException; import org.xml.sax.ext.Locator2; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; import javax.xml.XMLConstants; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.*; /** * @author Santhosh Kumar T */ @SuppressWarnings({"ThrowableInstanceNeverThrown"}) public class AsyncXMLReader extends AbstractXMLReader implements NBHandler<SAXException>, Locator2{ private static Map<String, char[]> defaultEntities = new HashMap<String, char[]>(); static{ defaultEntities.put("amp", new char[]{ '&' }); defaultEntities.put("lt", new char[]{ '<' }); defaultEntities.put("gt", new char[]{ '>' }); defaultEntities.put("apos", new char[]{ '\'' }); defaultEntities.put("quot", new char[]{ '"' }); } private int iProlog = -1; private XMLScanner scanner = new XMLScanner(this, XMLScanner.RULE_DOCUMENT){ protected void consumed(int ch){ consumed = true; int line = location.getLineNumber(); boolean addToBuffer = location.consume(ch); if(addToBuffer && buffer.isBufferring()) buffer.append(location.getLineNumber()>line ? '\n' : ch); } @Override public void write(ByteBuffer in, boolean eof) throws IOException{ if(iProlog==-1){ if(in.remaining()>=4){ byte marker[] = new byte[]{ in.get(0), in.get(1), in.get(2), in.get(3) }; BOM bom = BOM.get(marker, true); String encoding; if(bom!=null){ in.position(bom.with().length); encoding = bom.encoding(); }else{ bom = BOM.get(marker, false); encoding = bom!=null ? bom.encoding() : "UTF-8"; } decoder = Charset.forName(encoding).newDecoder(); if(!encoding.equals("UTF-8")){ decoder.onMalformedInput(CodingErrorAction.REPLACE) .onMalformedInput(CodingErrorAction.REPLACE); } iProlog = 0; }else{ if(eof) super.write(in, true); return; } } while(iProlog<6){ if(eof){ String str = "<?xml "; for(int i=0; i<iProlog; i++) consume(str.charAt(i)); super.write(in, true); return; } CharBuffer charBuffer = CharBuffer.allocate(1); CoderResult coderResult = decoder.decode(in, charBuffer, eof); if(coderResult.isUnderflow() || coderResult.isOverflow()){ char ch = charBuffer.array()[0]; if(isPrologStart(ch)){ iProlog++; if(iProlog==6){ consume('<'); consume('?'); consume('x'); consume('m'); consume('l'); consume(' '); } if(coderResult.isOverflow()) continue; else return; }else{ String str = "<?xml "; for(int i=0; i<iProlog; i++) consume(str.charAt(i)); consume(ch); iProlog = 7; } }else encodingError(coderResult); } if(iProlog==6 && !eof){ while(!xdeclEnd){ CharBuffer charBuffer = CharBuffer.allocate(1); CoderResult coderResult = decoder.decode(in, charBuffer, eof); if(coderResult.isUnderflow() || coderResult.isOverflow()){ char ch = charBuffer.array()[0]; consume(ch); if(coderResult.isUnderflow()) return; }else encodingError(coderResult); } String detectedEncoding = decoder.charset().name().toUpperCase(Locale.ENGLISH); String declaredEncoding = encoding.toUpperCase(Locale.ENGLISH); if(!detectedEncoding.equals(declaredEncoding)){ if(detectedEncoding.startsWith("UTF-16") && declaredEncoding.equals("UTF-16")) ; //donothing else if(!detectedEncoding.equals(encoding)){ decoder = Charset.forName(encoding).newDecoder(); if(!encoding.equals("UTF-8")){ decoder.onMalformedInput(CodingErrorAction.REPLACE) .onMalformedInput(CodingErrorAction.REPLACE); } } } iProlog = 7; } super.write(in, eof); } private boolean isPrologStart(char ch){ switch(iProlog){ case 0: return ch=='<'; case 1: return ch=='?'; case 2: return ch=='x'; case 3: return ch=='m'; case 4: return ch=='l'; case 5: return ch==0x20 || ch==0x9 || ch==0xa || ch==0xd; default: throw new Error("impossible"); } } }; @Override public void setFeature(String name, boolean value) throws SAXNotRecognizedException{ try{ super.setFeature(name, value); } catch(SAXNotRecognizedException e){ // ignore } } public Writer getWriter() throws SAXException{ scanner.reset(); documentStart(); return scanner.writer; } @Override public void parse(InputSource input) throws IOException, SAXException{ Reader charStream = input.getCharacterStream(); if(charStream !=null) IOUtil.pump(charStream, getWriter(), true, true); else{ InputStream inputStream = input.getByteStream(); if(inputStream!=null) parse(inputStream); else parse(input.getSystemId()); } } @Override public void parse(String systemId) throws IOException, SAXException{ // special handling for http url's like redirect, get encoding information from http headers URL url = URLUtil.toURL(systemId); if(url.getProtocol().equals("file")){ scanner.reset(); documentStart(); try{ FileChannel channel = new FileInputStream(new File(url.toURI())).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(100); while(channel.read(buffer)!=-1){ buffer.flip(); scanner.write(buffer, false); buffer.compact(); } buffer.flip(); scanner.write(buffer, true); }catch(URISyntaxException ex){ throw new IOException(ex); } }else parse(url.openStream()); } private void parse(InputStream in) throws IOException, SAXException{ UnicodeInputStream input = new UnicodeInputStream(in); String encoding = input.bom!=null ? input.bom.encoding() : IOUtil.UTF_8.name(); IOUtil.pump(new InputStreamReader(input, encoding), getWriter(), true, true); } /*-------------------------------------------------[ Locator ]---------------------------------------------------*/ @Override public String getPublicId(){ return null; } @Override public String getSystemId(){ return null; } @Override public int getLineNumber(){ return scanner.location.getLineNumber(); } @Override public int getColumnNumber(){ return scanner.location.getColumnNumber(); } @Override public String getXMLVersion(){ return "1.0"; } @Override public String getEncoding(){ return encoding; } /*-------------------------------------------------[ Document ]---------------------------------------------------*/ private void documentStart() throws SAXException{ iProlog = -1; encoding = "UTF-8"; xdeclEnd = false; clearQName(); value.setLength(0); valueStarted = false; entityValue = false; namespaces = new NamespaceMap(); attributes.clear(); elementsPrefixes.clear(); elementsLocalNames.clear(); elementsQNames.clear(); piTarget = null; dtdRoot = null; systemID = null; publicID = null; notationName = null; entityName = null; entities.clear(); entityStack.clear(); dtdAttributes.clear(); dtdElementName = null; attributeList = null; dtdAttribute = null; handler.setDocumentLocator(this); handler.startDocument(); } /*-------------------------------------------------[ XML Decleration ]---------------------------------------------------*/ void version(Chars data) throws SAXException{ if(!"1.0".contentEquals(data)) fatalError("Unsupported XML Version: "+data); } private String encoding; void encoding(Chars data) throws SAXException{ encoding = data.toString(); } void standalone(Chars data){ System.out.println("standalone: "+data); } private boolean xdeclEnd; void xdeclEnd(){ xdeclEnd = true; } /*-------------------------------------------------[ QName ]---------------------------------------------------*/ private String prefix = ""; void prefix(Chars data){ prefix = data.toString(); } private String localName; void localName(Chars data){ localName = data.toString(); } private String qname; void qname(Chars data){ qname = data.toString(); } private void clearQName(){ prefix = ""; localName = null; qname = null; } /*-------------------------------------------------[ Value ]---------------------------------------------------*/ private StringBuilder value = new StringBuilder(); private boolean valueStarted = true; private boolean entityValue = false; void valueStart(){ value.setLength(0); valueStarted = true; entityValue = false; } void entityValue(){ entityValue = true; } void rawValue(Chars data){ char[] chars = data.array(); int end = data.offset() + data.length(); for(int i=data.offset(); i<end; i++){ char ch = chars[i]; if(ch=='\n' || ch=='\r' || ch=='\t') ch = ' '; value.append(ch); } } private boolean isValid(int ch){ return (ch==0x9 || ch==0xa || ch==0xd) || (ch>=0x20 && ch<=0xd7ff) || (ch>=0xe000 && ch<=0xfffd) || (ch>=0x10000 && ch<=0x10ffff); } void hexCode(Chars data) throws SAXException{ int codePoint = Integer.parseInt(data.toString(), 16); if(!isValid(codePoint)) fatalError("invalid xml character"); if(valueStarted) value.appendCodePoint(codePoint); else{ char chars[] = Character.toChars(codePoint); handler.characters(chars, 0, chars.length); } } void asciiCode(Chars data) throws SAXException{ int codePoint = Integer.parseInt(data.toString(), 10); if(!isValid(codePoint)) fatalError("invalid xml character"); if(valueStarted) value.appendCodePoint(codePoint); else{ char chars[] = Character.toChars(codePoint); handler.characters(chars, 0, chars.length); } } private ArrayDeque<String> entityStack = new ArrayDeque<String>(); @SuppressWarnings({"ConstantConditions"}) void entityReference(Chars data) throws SAXException{ if(entityValue){ value.append('&').append(data).append(';'); return; } String entity = data.toString(); char[] entityValue = defaultEntities.get(entity); if(entityValue!=null){ if(valueStarted) value.append(entityValue); else handler.characters(entityValue, 0, entityValue.length); }else{ entityValue = entities.get(entity); if(entityValue==null) fatalError("Undefined entityReference: "+entity); int rule; if(valueStarted){ char chars[] = new char[entityValue.length]; for(int i=chars.length-1; i>=0; i--){ char ch = entityValue[i]; if(ch=='\n' || ch=='\r' || ch=='\t') ch = ' '; chars[i] = ch; } entityValue = chars; rule = XMLScanner.RULE_VALUE_ENTITY; }else rule = XMLScanner.RULE_ELEM_ENTITY; if(entityStack.contains(entity)) fatalError("found recursion in entity expansion :"+entity); entityStack.push(entity); try{ XMLScanner entityValueScanner = new XMLScanner(this, rule); entityValueScanner.writer.write(entityValue); entityValueScanner.writer.close(); }catch(IOException ex){ throw new RuntimeException(ex); }finally{ entityStack.pop(); } } } void valueEnd(){ valueStarted = false; entityValue = false; } /*-------------------------------------------------[ Start Element ]---------------------------------------------------*/ private NamespaceMap namespaces = new NamespaceMap(); private AttributesImpl attributes = new AttributesImpl(); private Deque<String> elementsPrefixes = new ArrayDeque<String>(); private Deque<String> elementsLocalNames = new ArrayDeque<String>(); private Deque<String> elementsQNames = new ArrayDeque<String>(); void attributesStart(){ elementsPrefixes.push(prefix); elementsLocalNames.push(localName); elementsQNames.push(qname); clearQName(); namespaces = new NamespaceMap(namespaces); attributes.clear(); } void attributeEnd() throws SAXException{ String type = "CDATA"; Map<String, DTDAttribute> attrList = dtdAttributes.get(elementsQNames.peek()); if(attrList!=null){ DTDAttribute dtdAttr = attrList.get(qname); if(dtdAttr!=null){ if(dtdAttr.type==AttributeType.ENUMERATION) type = "NMTOKEN"; else type = dtdAttr.type.name(); } } String value = this.value.toString(); if(type.equals("NMTOKEN")) value = value.trim(); else if(type.equals("NMTOKENS")){ char[] buffer = value.toCharArray(); int write = 0; int lastWrite = 0; boolean wroteOne = false; int read = 0; while(read<buffer.length && buffer[read]==' '){ read++; } int len = buffer.length; while(len<read && buffer[len-1]==' ') len--; while(read<len){ if (buffer[read]==' '){ if (wroteOne) buffer[write++] = ' '; do{ read++; }while(read<len && buffer[read]==' '); }else{ buffer[write++] = buffer[read++]; wroteOne = true; lastWrite = write; } } value = new String(buffer, 0, lastWrite); } if(qname.equals("xmlns")){ namespaces.put("", value); handler.startPrefixMapping("", value); }else if(prefix.equals("xmlns")){ if(localName.equals(XMLConstants.XML_NS_PREFIX)){ if(!value.equals(XMLConstants.XML_NS_URI)){ clearQName(); fatalError("prefix "+XMLConstants.XML_NS_PREFIX+" must refer to "+XMLConstants.XML_NS_URI); } }else if(localName.equals(XMLConstants.XMLNS_ATTRIBUTE)){ clearQName(); fatalError("prefix "+XMLConstants.XMLNS_ATTRIBUTE+" must not be declared"); }else{ if(value.equals(XMLConstants.XML_NS_URI)){ clearQName(); fatalError(XMLConstants.XML_NS_URI+" must be bound to "+XMLConstants.XML_NS_PREFIX); }else if(value.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)){ clearQName(); fatalError(XMLConstants.XMLNS_ATTRIBUTE_NS_URI+" must be bound to "+XMLConstants.XMLNS_ATTRIBUTE); }else{ if(value.length()==0) fatalError("No Prefix Undeclaring: "+localName); namespaces.put(localName, value); handler.startPrefixMapping(localName, value); } } }else{ attributes.addAttribute(prefix, localName, qname, type, value); } clearQName(); } private Set<String> attributeNames = new HashSet<String>(); void attributesEnd() throws SAXException{ attributeNames.clear(); int attrCount = attributes.getLength(); for(int i=0; i<attrCount; i++){ String prefix = attributes.getURI(i); String uri = ""; if(prefix.length()>0){ uri = namespaces.getNamespaceURI(prefix); if(uri==null) fatalError("Unbound prefix: "+prefix); attributes.setURI(i, uri); } String clarkName = ClarkName.valueOf(uri, attributes.getLocalName(i)); if(!attributeNames.add(clarkName)) fatalError("Attribute "+clarkName+" appears more than once in element"); } String elemQName = elementsQNames.peek(); Map<String, DTDAttribute> attList = dtdAttributes.get(elemQName); if(attList!=null){ for(DTDAttribute dtdAttr: attList.values()){ if(dtdAttr.valueType== AttributeValueType.DEFAULT){ int index = attributes.getIndex(dtdAttr.name); if(index==-1) attributes.addAttribute("", dtdAttr.name, dtdAttr.name, dtdAttr.type.name(), dtdAttr.value); } } } String prefix = elementsPrefixes.peek(); String namespaceURI = namespaces.getNamespaceURI(prefix); if(namespaceURI==null) fatalError("Unbound prefix: "+prefix); handler.startElement(namespaceURI, elementsLocalNames.peek(), elementsQNames.peek(), attributes); } void emptyElementEnd() throws SAXException{ elementEnd(elementsQNames.pop()); } void elementEnd() throws SAXException{ String startQName = elementsQNames.pop(); if(!startQName.equals(qname)) fatalError("expected </"+startQName+">"); elementEnd(qname); } private void elementEnd(String qname) throws SAXException{ String prefix = elementsPrefixes.pop(); String namespaceURI = namespaces.getNamespaceURI(prefix); if(namespaceURI==null) fatalError("Unbound prefix: "+prefix); handler.endElement(namespaceURI, elementsLocalNames.pop(), qname); if(namespaces.map()!=null){ for(String nsPrefix: namespaces.map().keySet()) handler.endPrefixMapping(nsPrefix); } namespaces = namespaces.parent(); clearQName(); } /*-------------------------------------------------[ PI ]---------------------------------------------------*/ private String piTarget; void piTarget(Chars data){ piTarget = data.toString(); } void piData(Chars piData) throws SAXException{ handler.processingInstruction(piTarget, piData.length()>0 ? piData.toString() : ""); } void piData() throws SAXException{ handler.processingInstruction(piTarget, ""); } /*-------------------------------------------------[ Misc ]---------------------------------------------------*/ void characters(Chars data) throws SAXException{ handler.characters(data.array(), data.offset(), data.length()); } void cdata(Chars data) throws SAXException{ handler.startCDATA(); handler.characters(data.array(), data.offset(), data.length()); handler.endCDATA(); } void comment(Chars data) throws SAXException{ handler.comment(data.array(), data.offset(), data.length()); } @Override public void fatalError(String message) throws SAXException{ fatalError(new SAXParseException(message, this)); } public void fatalError(SAXParseException ex) throws SAXException{ try{ handler.fatalError(ex); throw ex; }finally{ handler.endDocument(); } } @Override public void onSuccessful() throws SAXException{ if(entityStack.isEmpty()) handler.endDocument(); } /*-------------------------------------------------[ DTD ]---------------------------------------------------*/ private String dtdRoot; void dtdRoot(Chars data){ dtdRoot = data.toString(); } private String systemID; void systemID(Chars data){ systemID = data.toString(); } private String publicID; void publicID(Chars data){ publicID = data.toString(); } void dtdStart() throws SAXException{ handler.startDTD(dtdRoot, publicID, systemID); publicID = systemID = null; } private String notationName; void notationName(Chars data){ notationName = data.toString(); } void notationEnd() throws SAXException{ handler.notationDecl(notationName, publicID, systemID); } void dtdElement(Chars data){ System.out.println("dtdElement: "+data); } private String entityName; void entityName(Chars data){ entityName = data.toString(); } private Map<String, char[]> entities = new HashMap<String, char[]>(); void entityEnd(){ if(value!=null){ entities.put(entityName, value.toString().toCharArray()); value.setLength(0); } } public void dtdEnd() throws SAXException{ handler.endDTD(); dtdRoot = null; } /*-------------------------------------------------[ DTD Attributes ]---------------------------------------------------*/ private Map<String, Map<String, DTDAttribute>> dtdAttributes = new HashMap<String, Map<String, DTDAttribute>>(); private String dtdElementName; private Map<String, DTDAttribute> attributeList; private DTDAttribute dtdAttribute; void dtdAttributesStart(Chars data){ dtdElementName = data.toString(); attributeList = dtdAttributes.get(dtdElementName); if(attributeList==null) dtdAttributes.put(dtdElementName, attributeList=new HashMap<String, DTDAttribute>()); } void dtdAttribute(Chars data){ String attributeName = data.toString(); if(attributeList.get(attributeName)==null){ dtdAttribute = new DTDAttribute(); dtdAttribute.name = attributeName; attributeList.put(attributeName, dtdAttribute); }else dtdAttribute = null; } void cdataAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.CDATA; } void idAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.ID; } void idRefAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.IDREF; } void idRefsAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.IDREFS; } void nmtokenAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.NMTOKEN; } void nmtokensAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.NMTOKENS; } void entityAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.ENTITY; } void entitiesAttribute(){ if(dtdAttribute!=null) dtdAttribute.type = AttributeType.ENTITIES; } void enumerationAttribute(){ if(dtdAttribute!=null){ dtdAttribute.type = AttributeType.ENUMERATION; dtdAttribute.validValues = new ArrayList<String>(); } } void notationAttribute(){ if(dtdAttribute!=null){ dtdAttribute.type = AttributeType.NOTATION; dtdAttribute.validValues = new ArrayList<String>(); } } void attributeEnumValue(Chars data){ if(dtdAttribute!=null) dtdAttribute.validValues.add(data.toString()); } void attributeNotationValue(Chars data){ if(dtdAttribute!=null) dtdAttribute.validValues.add(data.toString()); } void attributeDefaultValue() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.DEFAULT; dtdAttribute.value = value.toString(); fireDTDAttributeEvent(); } value.setLength(0); } void attributeRequired() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.REQUIRED; fireDTDAttributeEvent(); } } void attributeImplied() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.IMPLIED; fireDTDAttributeEvent(); } } void attributeFixedValue() throws SAXException{ if(dtdAttribute!=null){ dtdAttribute.valueType = AttributeValueType.FIXED; dtdAttribute.value = value.toString(); fireDTDAttributeEvent(); } value.setLength(0); } private void fireDTDAttributeEvent() throws SAXException{ handler.attributeDecl(dtdElementName, dtdAttribute.name, dtdAttribute.type.toString(dtdAttribute.validValues), dtdAttribute.valueType.mode, dtdAttribute.value); } void dtdAttributesEnd(){ System.out.println("dtdAttributesEnd"); } /*-------------------------------------------------[ Test ]---------------------------------------------------*/ public static void main(String[] args) throws Exception{ AsyncXMLReader parser = new AsyncXMLReader(); TransformerHandler handler = TransformerUtil.newTransformerHandler(null, true, -1, null); handler.setResult(new StreamResult(System.out)); SAXUtil.setHandler(parser, handler); // String xml = "<root attr1='value1'/>"; // parser.parse(new InputSource(new StringReader(xml))); // String file = "/Users/santhosh/projects/SAXTest/xmlconf/xmltest/valid/sa/049.xml"; // with BOM String file = "/Users/santhosh/projects/SAXTest/xmlconf/eduni/errata-2e/E27.xml"; // String file = "/Users/santhosh/projects/jlibs/examples/resources/xmlFiles/test.xml"; SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); try{ factory.newSAXParser().parse(file, new DefaultHandler(){ @Override public void characters(char[] ch, int start, int length) throws SAXException{ super.characters(ch, start, length); //To change body of overridden methods use File | Settings | File Templates. } }); }catch(Exception ex){ ex.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. System.out.println("=========================="); } IOUtil.pump(new InputStreamReader(new FileInputStream(file), "UTF-8"), new StringWriter(), true, true); // IOUtil.pump(new UTF8Reader(new FileInputStream(file)), new StringWriter(), true, true); parser.parse(new InputSource(file)); // parser.scanner.write("<root attr1='value1'/>"); // parser.scanner.close(); } }
fixed attributes should be added to attributes
xml/src/main/java/jlibs/xml/sax/async/AsyncXMLReader.java
fixed attributes should be added to attributes
<ide><path>ml/src/main/java/jlibs/xml/sax/async/AsyncXMLReader.java <ide> Map<String, DTDAttribute> attList = dtdAttributes.get(elemQName); <ide> if(attList!=null){ <ide> for(DTDAttribute dtdAttr: attList.values()){ <del> if(dtdAttr.valueType== AttributeValueType.DEFAULT){ <add> if(dtdAttr.valueType==AttributeValueType.DEFAULT || dtdAttr.valueType==AttributeValueType.FIXED){ <ide> int index = attributes.getIndex(dtdAttr.name); <del> if(index==-1) <del> attributes.addAttribute("", dtdAttr.name, dtdAttr.name, dtdAttr.type.name(), dtdAttr.value); <add> if(index==-1){ <add> if(!dtdAttr.name.equals("xmlns") && !dtdAttr.name.startsWith("xmlns:")) <add> attributes.addAttribute("", dtdAttr.name, dtdAttr.name, dtdAttr.type.name(), dtdAttr.value); <add> } <ide> } <ide> } <ide> } <ide> // parser.parse(new InputSource(new StringReader(xml))); <ide> <ide> // String file = "/Users/santhosh/projects/SAXTest/xmlconf/xmltest/valid/sa/049.xml"; // with BOM <del> String file = "/Users/santhosh/projects/SAXTest/xmlconf/eduni/errata-2e/E27.xml"; <del>// String file = "/Users/santhosh/projects/jlibs/examples/resources/xmlFiles/test.xml"; <add>// String file = "/Users/santhosh/projects/SAXTest/xmlconf/ibm/valid/P59/ibm59v01.xml"; <add> String file = "/Users/santhosh/projects/jlibs/examples/resources/xmlFiles/test.xml"; <ide> SAXParserFactory factory = SAXParserFactory.newInstance(); <ide> factory.setNamespaceAware(true); <ide> try{
Java
apache-2.0
fb11db199743232204722cbe403ba78ff9f24078
0
sgroschupf/katta,sgroschupf/katta
package net.sf.katta.index.indexer.merge; import java.io.InputStream; import net.sf.katta.index.indexer.IndexJobConf; import net.sf.katta.index.indexer.ShardSelectionMapper; import net.sf.katta.util.Logger; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.SequenceFileInputFormat; public class SequenceFileToIndexJob implements Configurable { private Configuration _configuration; public void sequenceFileToIndex(Path sequenceFilePath, Path outputFolder) throws Exception { InputStream resourceAsStream = SequenceFileToIndexJob.class.getResourceAsStream("/katta.index.properties"); JobConf jobConf = new IndexJobConf().create(_configuration, resourceAsStream); jobConf.setJobName("SequenceFileToIndex"); // input and output format jobConf.setInputFormat(SequenceFileInputFormat.class); // no output format will be reduced because the index will be creat local and will be copied into the hds // input and output path //overwrite the settet input path which is set via IndexJobConf.create jobConf.set("mapred.input.dir", ""); Logger.info("read document informations from sequence file: " + sequenceFilePath); jobConf.addInputPath(sequenceFilePath); //configure the mapper jobConf.setMapOutputKeyClass(Text.class); jobConf.setMapOutputValueClass(BytesWritable.class); jobConf.setMapperClass(ShardSelectionMapper.class); //the input key and input value class which is saved in the sequence file will be mapped out as value: BytesWritable jobConf.set("index.input.key.class", Text.class.getName()); jobConf.set("index.input.value.class", DocumentInformation.class.getName()); String indexFolder = "" + System.currentTimeMillis() + "-merge"; Path newOutputPath = new Path(jobConf.getOutputPath(), indexFolder); Logger.info("set mapred folder to: " + newOutputPath); jobConf.setOutputPath(newOutputPath); String uploadPath = outputFolder.toString() +"/" + indexFolder; Logger.info("set index upload folder: '" + uploadPath + "'"); jobConf.set(IndexJobConf.INDEX_UPLOAD_PATH, uploadPath); jobConf.set("document.factory.class", DfsIndexDocumentFactory.class.getName()); // run the job JobClient.runJob(jobConf); } public void setConf(Configuration configuration) { _configuration = configuration; } public Configuration getConf() { return _configuration; } public static void main(String[] args) throws Exception { SequenceFileToIndexJob mergeJob = new SequenceFileToIndexJob(); JobConf jobConf = new JobConf(); jobConf.setJarByClass(SequenceFileToIndexJob.class); mergeJob.setConf(jobConf); mergeJob.sequenceFileToIndex(new Path(args[0]), new Path("/tmp/" + System.currentTimeMillis())); } }
src/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java
package net.sf.katta.index.indexer.merge; import java.io.InputStream; import net.sf.katta.index.indexer.IndexJobConf; import net.sf.katta.index.indexer.ShardSelectionMapper; import net.sf.katta.util.Logger; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.SequenceFileInputFormat; public class SequenceFileToIndexJob implements Configurable { private Configuration _configuration; public void sequenceFileToIndex(Path sequenceFilePath, Path outputFolder) throws Exception { InputStream resourceAsStream = SequenceFileToIndexJob.class.getResourceAsStream("/katta.index.properties"); JobConf jobConf = new IndexJobConf().create(_configuration, resourceAsStream); jobConf.setJobName("SequenceFileToIndex"); // input and output format jobConf.setInputFormat(SequenceFileInputFormat.class); // no output format will be reduced because the index will be creat local and will be copied into the hds // input and output path //overwrite the settet input path which is set via IndexJobConf.create jobConf.set("mapred.input.dir", ""); Logger.info("read document informations from sequence file: " + sequenceFilePath); jobConf.addInputPath(sequenceFilePath); //configure the mapper jobConf.setMapOutputKeyClass(Text.class); jobConf.setMapOutputValueClass(BytesWritable.class); jobConf.setMapperClass(ShardSelectionMapper.class); //the input key and input value class which is saved in the sequence file will be mapped out as value: BytesWritable jobConf.set("index.input.key.class", Text.class.getName()); jobConf.set("index.input.value.class", DocumentInformation.class.getName()); String indexFolder = outputFolder.toString() + "/" + System.currentTimeMillis() + "-merge"; Path newOutputPath = new Path(jobConf.getOutputPath(), indexFolder); Logger.info("set mapred folder to: " + newOutputPath); jobConf.setOutputPath(newOutputPath); String uploadPath = jobConf.get(IndexJobConf.INDEX_UPLOAD_PATH) + "/" + indexFolder; Logger.info("set index upload folder: '" + uploadPath + "'"); jobConf.set(IndexJobConf.INDEX_UPLOAD_PATH, uploadPath); jobConf.set("document.factory.class", DfsIndexDocumentFactory.class.getName()); // run the job JobClient.runJob(jobConf); } public void setConf(Configuration configuration) { _configuration = configuration; } public Configuration getConf() { return _configuration; } public static void main(String[] args) throws Exception { SequenceFileToIndexJob mergeJob = new SequenceFileToIndexJob(); JobConf jobConf = new JobConf(); jobConf.setJarByClass(SequenceFileToIndexJob.class); mergeJob.setConf(jobConf); mergeJob.sequenceFileToIndex(new Path(args[0]), new Path("/tmp/" + System.currentTimeMillis())); } }
improve merge ouputfolder
src/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java
improve merge ouputfolder
<ide><path>rc/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java <ide> //the input key and input value class which is saved in the sequence file will be mapped out as value: BytesWritable <ide> jobConf.set("index.input.key.class", Text.class.getName()); <ide> jobConf.set("index.input.value.class", DocumentInformation.class.getName()); <del> String indexFolder = outputFolder.toString() + "/" + System.currentTimeMillis() + "-merge"; <add> String indexFolder = "" + System.currentTimeMillis() + "-merge"; <ide> <ide> Path newOutputPath = new Path(jobConf.getOutputPath(), indexFolder); <ide> Logger.info("set mapred folder to: " + newOutputPath); <ide> jobConf.setOutputPath(newOutputPath); <ide> <del> String uploadPath = jobConf.get(IndexJobConf.INDEX_UPLOAD_PATH) + "/" + indexFolder; <add> String uploadPath = outputFolder.toString() +"/" + indexFolder; <ide> Logger.info("set index upload folder: '" + uploadPath + "'"); <ide> jobConf.set(IndexJobConf.INDEX_UPLOAD_PATH, uploadPath); <ide>
Java
mpl-2.0
353e4af84d32dd0990c57a68f6f298b81bbb2049
0
Breta01/openmrs-module-referenceapplication,Breta01/openmrs-module-referenceapplication,Breta01/openmrs-module-referenceapplication
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.referenceapplication.page.controller; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Location; import org.openmrs.api.LocationService; import org.openmrs.api.context.Context; import org.openmrs.api.context.ContextAuthenticationException; import org.openmrs.module.appframework.service.AppFrameworkService; import org.openmrs.module.appui.UiSessionContext; import org.openmrs.module.emrapi.EmrApiConstants; import org.openmrs.module.referenceapplication.ReferenceApplicationConstants; import org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants; import org.openmrs.ui.framework.UiUtils; import org.openmrs.ui.framework.annotation.SpringBean; import org.openmrs.ui.framework.page.PageModel; import org.openmrs.ui.framework.page.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.COOKIE_NAME_LAST_SESSION_LOCATION; import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.REQUEST_PARAMETER_NAME_REDIRECT_URL; import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_REDIRECT_URL; /** * Spring MVC controller that takes over /login.htm and processes requests to authenticate a user */ @Controller public class LoginPageController { //see TRUNK-4536 for details why we need this private static final String GET_LOCATIONS = "Get Locations"; // RA-592: don't use PrivilegeConstants.VIEW_LOCATIONS private static final String VIEW_LOCATIONS = "View Locations"; protected final Log log = LogFactory.getLog(getClass()); @RequestMapping("/login.htm") public String overrideLoginpage() { //TODO The referer should actually be captured from here since we are doing a redirect return "forward:/" + ReferenceApplicationConstants.MODULE_ID + "/login.page"; } /** * @should redirect the user to the home page if they are already authenticated * @should show the user the login page if they are not authenticated * @should set redirectUrl in the page model if any was specified in the request * @should set the referer as the redirectUrl in the page model if no redirect param exists * @should set redirectUrl in the page model if any was specified in the session */ public String get(PageModel model, UiUtils ui, PageRequest pageRequest, @CookieValue(value = COOKIE_NAME_LAST_SESSION_LOCATION, required = false) String lastSessionLocationId, @SpringBean("locationService") LocationService locationService, @SpringBean("appFrameworkService") AppFrameworkService appFrameworkService) { if (Context.isAuthenticated()) { return "redirect:" + ui.pageLink(ReferenceApplicationConstants.MODULE_ID, "home"); } String redirectUrl = getStringSessionAttribute(SESSION_ATTRIBUTE_REDIRECT_URL, pageRequest.getRequest()); if (StringUtils.isBlank(redirectUrl)) redirectUrl = pageRequest.getRequest().getParameter(REQUEST_PARAMETER_NAME_REDIRECT_URL); if (StringUtils.isBlank(redirectUrl)) redirectUrl = pageRequest.getRequest().getHeader("Referer"); if (redirectUrl == null) redirectUrl = ""; model.addAttribute(REQUEST_PARAMETER_NAME_REDIRECT_URL, redirectUrl); Location lastSessionLocation = null; try { Context.addProxyPrivilege(VIEW_LOCATIONS); Context.addProxyPrivilege(GET_LOCATIONS); model.addAttribute("locations", appFrameworkService.getLoginLocations()); lastSessionLocation = locationService.getLocation(Integer.valueOf(lastSessionLocationId)); } catch (NumberFormatException ex) { // pass } finally { Context.removeProxyPrivilege(VIEW_LOCATIONS); Context.removeProxyPrivilege(GET_LOCATIONS); } model.addAttribute("lastSessionLocation", lastSessionLocation); return null; } /** * Processes requests to authenticate a user * * @param username * @param password * @param sessionLocationId * @param locationService * @param ui {@link UiUtils} object * @param pageRequest {@link PageRequest} object * @param sessionContext * @return * @should redirect the user back to the redirectUrl if any * @should redirect the user to the home page if the redirectUrl is the login page * @should send the user back to the login page if an invalid location is selected * @should send the user back to the login page when authentication fails */ public String post(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password, @RequestParam(value = "sessionLocation", required = false) Integer sessionLocationId, @SpringBean("locationService") LocationService locationService, UiUtils ui, PageRequest pageRequest, UiSessionContext sessionContext) { String redirectUrl = pageRequest.getRequest().getParameter(REQUEST_PARAMETER_NAME_REDIRECT_URL); redirectUrl = getRelativeUrl(redirectUrl, pageRequest); Location sessionLocation = null; if (sessionLocationId != null) { try { // TODO as above, grant this privilege to Anonymous instead of using a proxy privilege Context.addProxyPrivilege(VIEW_LOCATIONS); Context.addProxyPrivilege(GET_LOCATIONS); sessionLocation = locationService.getLocation(sessionLocationId); } finally { Context.removeProxyPrivilege(VIEW_LOCATIONS); Context.removeProxyPrivilege(GET_LOCATIONS); } } //TODO uncomment this to replace the if clause after it if (sessionLocation != null && sessionLocation.hasTag(EmrApiConstants.LOCATION_TAG_SUPPORTS_LOGIN)) { // Set a cookie, so next time someone logs in on this machine, we can default to that same location pageRequest.setCookieValue(COOKIE_NAME_LAST_SESSION_LOCATION, sessionLocationId.toString()); try { Context.authenticate(username, password); if (Context.isAuthenticated()) { if (log.isDebugEnabled()) log.debug("User has successfully authenticated"); sessionContext.setSessionLocation(sessionLocation); if (StringUtils.isNotBlank(redirectUrl)) { //don't redirect back to the login page on success nor an external url if (!redirectUrl.contains("login.")) { if (log.isDebugEnabled()) log.debug("Redirecting user to " + redirectUrl); return "redirect:" + redirectUrl; } else { if (log.isDebugEnabled()) log.debug("Redirect contains 'login.', redirecting to home page"); } } return "redirect:" + ui.pageLink(ReferenceApplicationConstants.MODULE_ID, "home"); } } catch (ContextAuthenticationException ex) { if (log.isDebugEnabled()) log.debug("Failed to authenticate user"); pageRequest.getSession().setAttribute(ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, ui.message(ReferenceApplicationConstants.MODULE_ID + ".error.login.fail")); } } else if (sessionLocation == null) { pageRequest.getSession().setAttribute(ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, ui.message("referenceapplication.login.error.locationRequired")); } else { // the UI shouldn't allow this, but protect against it just in case pageRequest.getSession().setAttribute(ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, ui.message("referenceapplication.login.error.invalidLocation", sessionLocation.getName())); } if (log.isDebugEnabled()) log.debug("Sending user back to login page"); //TODO limit login attempts by IP Address pageRequest.getSession().setAttribute(SESSION_ATTRIBUTE_REDIRECT_URL, redirectUrl); return "redirect:" + ui.pageLink(ReferenceApplicationConstants.MODULE_ID, "login"); } private String getStringSessionAttribute(String attributeName, HttpServletRequest request) { String attributeValue = (String) request.getSession().getAttribute(attributeName); request.getSession().removeAttribute(attributeName); return attributeValue; } public String getRelativeUrl(String url, PageRequest pageRequest) { if (url == null) return null; if (url.startsWith("/") || (!url.startsWith("http://") && !url.startsWith("https://"))) { return url; } //This is an absolute url, discard the protocal, domain name/host and port section int indexOfContextPath = url.indexOf(pageRequest.getRequest().getContextPath()); if (indexOfContextPath >= 0) { url = url.substring(indexOfContextPath); log.debug("Relative redirect:" + url); return url; } return null; } }
omod/src/main/java/org/openmrs/module/referenceapplication/page/controller/LoginPageController.java
/** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.referenceapplication.page.controller; import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.COOKIE_NAME_LAST_SESSION_LOCATION; import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.REQUEST_PARAMETER_NAME_REDIRECT_URL; import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_REDIRECT_URL; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Location; import org.openmrs.api.LocationService; import org.openmrs.api.context.Context; import org.openmrs.api.context.ContextAuthenticationException; import org.openmrs.module.appframework.service.AppFrameworkService; import org.openmrs.module.appui.UiSessionContext; import org.openmrs.module.emrapi.EmrApiConstants; import org.openmrs.module.referenceapplication.ReferenceApplicationConstants; import org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants; import org.openmrs.ui.framework.UiUtils; import org.openmrs.ui.framework.annotation.SpringBean; import org.openmrs.ui.framework.page.PageModel; import org.openmrs.ui.framework.page.PageRequest; import org.openmrs.util.PrivilegeConstants; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * Spring MVC controller that takes over /login.htm and processes requests to authenticate a user */ @Controller public class LoginPageController { //see TRUNK-4536 for details why we need this private static final String GET_LOCATIONS = "Get Locations"; protected final Log log = LogFactory.getLog(getClass()); @RequestMapping("/login.htm") public String overrideLoginpage() { //TODO The referer should actually be captured from here since we are doing a redirect return "forward:/" + ReferenceApplicationConstants.MODULE_ID + "/login.page"; } /** * @should redirect the user to the home page if they are already authenticated * @should show the user the login page if they are not authenticated * @should set redirectUrl in the page model if any was specified in the request * @should set the referer as the redirectUrl in the page model if no redirect param exists * @should set redirectUrl in the page model if any was specified in the session */ public String get(PageModel model, UiUtils ui, PageRequest pageRequest, @CookieValue(value = COOKIE_NAME_LAST_SESSION_LOCATION, required = false) String lastSessionLocationId, @SpringBean("locationService") LocationService locationService, @SpringBean("appFrameworkService") AppFrameworkService appFrameworkService) { if (Context.isAuthenticated()) { return "redirect:" + ui.pageLink(ReferenceApplicationConstants.MODULE_ID, "home"); } String redirectUrl = getStringSessionAttribute(SESSION_ATTRIBUTE_REDIRECT_URL, pageRequest.getRequest()); if (StringUtils.isBlank(redirectUrl)) redirectUrl = pageRequest.getRequest().getParameter(REQUEST_PARAMETER_NAME_REDIRECT_URL); if (StringUtils.isBlank(redirectUrl)) redirectUrl = pageRequest.getRequest().getHeader("Referer"); if (redirectUrl == null) redirectUrl = ""; model.addAttribute(REQUEST_PARAMETER_NAME_REDIRECT_URL, redirectUrl); Location lastSessionLocation = null; try { Context.addProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); Context.addProxyPrivilege(GET_LOCATIONS); model.addAttribute("locations", appFrameworkService.getLoginLocations()); lastSessionLocation = locationService.getLocation(Integer.valueOf(lastSessionLocationId)); } catch (NumberFormatException ex) { // pass } finally { Context.removeProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); Context.removeProxyPrivilege(GET_LOCATIONS); } model.addAttribute("lastSessionLocation", lastSessionLocation); return null; } /** * Processes requests to authenticate a user * * @param username * @param password * @param sessionLocationId * @param locationService * @param ui {@link UiUtils} object * @param pageRequest {@link PageRequest} object * @param sessionContext * @return * @should redirect the user back to the redirectUrl if any * @should redirect the user to the home page if the redirectUrl is the login page * @should send the user back to the login page if an invalid location is selected * @should send the user back to the login page when authentication fails */ public String post(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password, @RequestParam(value = "sessionLocation", required = false) Integer sessionLocationId, @SpringBean("locationService") LocationService locationService, UiUtils ui, PageRequest pageRequest, UiSessionContext sessionContext) { String redirectUrl = pageRequest.getRequest().getParameter(REQUEST_PARAMETER_NAME_REDIRECT_URL); redirectUrl = getRelativeUrl(redirectUrl, pageRequest); Location sessionLocation = null; if (sessionLocationId != null) { try { // TODO as above, grant this privilege to Anonymous instead of using a proxy privilege Context.addProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); Context.addProxyPrivilege(GET_LOCATIONS); sessionLocation = locationService.getLocation(sessionLocationId); } finally { Context.removeProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); Context.removeProxyPrivilege(GET_LOCATIONS); } } //TODO uncomment this to replace the if clause after it if (sessionLocation != null && sessionLocation.hasTag(EmrApiConstants.LOCATION_TAG_SUPPORTS_LOGIN)) { // Set a cookie, so next time someone logs in on this machine, we can default to that same location pageRequest.setCookieValue(COOKIE_NAME_LAST_SESSION_LOCATION, sessionLocationId.toString()); try { Context.authenticate(username, password); if (Context.isAuthenticated()) { if (log.isDebugEnabled()) log.debug("User has successfully authenticated"); sessionContext.setSessionLocation(sessionLocation); if (StringUtils.isNotBlank(redirectUrl)) { //don't redirect back to the login page on success nor an external url if (!redirectUrl.contains("login.")) { if (log.isDebugEnabled()) log.debug("Redirecting user to " + redirectUrl); return "redirect:" + redirectUrl; } else { if (log.isDebugEnabled()) log.debug("Redirect contains 'login.', redirecting to home page"); } } return "redirect:" + ui.pageLink(ReferenceApplicationConstants.MODULE_ID, "home"); } } catch (ContextAuthenticationException ex) { if (log.isDebugEnabled()) log.debug("Failed to authenticate user"); pageRequest.getSession().setAttribute(ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, ui.message(ReferenceApplicationConstants.MODULE_ID + ".error.login.fail")); } } else if (sessionLocation == null) { pageRequest.getSession().setAttribute(ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, ui.message("referenceapplication.login.error.locationRequired")); } else { // the UI shouldn't allow this, but protect against it just in case pageRequest.getSession().setAttribute(ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE, ui.message("referenceapplication.login.error.invalidLocation", sessionLocation.getName())); } if (log.isDebugEnabled()) log.debug("Sending user back to login page"); //TODO limit login attempts by IP Address pageRequest.getSession().setAttribute(SESSION_ATTRIBUTE_REDIRECT_URL, redirectUrl); return "redirect:" + ui.pageLink(ReferenceApplicationConstants.MODULE_ID, "login"); } private String getStringSessionAttribute(String attributeName, HttpServletRequest request) { String attributeValue = (String) request.getSession().getAttribute(attributeName); request.getSession().removeAttribute(attributeName); return attributeValue; } public String getRelativeUrl(String url, PageRequest pageRequest) { if (url == null) return null; if (url.startsWith("/") || (!url.startsWith("http://") && !url.startsWith("https://"))) { return url; } //This is an absolute url, discard the protocal, domain name/host and port section int indexOfContextPath = url.indexOf(pageRequest.getRequest().getContextPath()); if (indexOfContextPath >= 0) { url = url.substring(indexOfContextPath); log.debug("Relative redirect:" + url); return url; } return null; } }
RA-592 - Redirect Loop when trying to visit homepage
omod/src/main/java/org/openmrs/module/referenceapplication/page/controller/LoginPageController.java
RA-592 - Redirect Loop when trying to visit homepage
<ide><path>mod/src/main/java/org/openmrs/module/referenceapplication/page/controller/LoginPageController.java <ide> * Copyright (C) OpenMRS, LLC. All Rights Reserved. <ide> */ <ide> package org.openmrs.module.referenceapplication.page.controller; <del> <del>import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.COOKIE_NAME_LAST_SESSION_LOCATION; <del>import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.REQUEST_PARAMETER_NAME_REDIRECT_URL; <del>import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_REDIRECT_URL; <del> <del>import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.apache.commons.lang.StringUtils; <ide> import org.apache.commons.logging.Log; <ide> import org.openmrs.ui.framework.annotation.SpringBean; <ide> import org.openmrs.ui.framework.page.PageModel; <ide> import org.openmrs.ui.framework.page.PageRequest; <del>import org.openmrs.util.PrivilegeConstants; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.CookieValue; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestParam; <add> <add>import javax.servlet.http.HttpServletRequest; <add> <add>import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.COOKIE_NAME_LAST_SESSION_LOCATION; <add>import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.REQUEST_PARAMETER_NAME_REDIRECT_URL; <add>import static org.openmrs.module.referenceapplication.ReferenceApplicationWebConstants.SESSION_ATTRIBUTE_REDIRECT_URL; <ide> <ide> /** <ide> * Spring MVC controller that takes over /login.htm and processes requests to authenticate a user <ide> <ide> //see TRUNK-4536 for details why we need this <ide> private static final String GET_LOCATIONS = "Get Locations"; <add> <add> // RA-592: don't use PrivilegeConstants.VIEW_LOCATIONS <add> private static final String VIEW_LOCATIONS = "View Locations"; <ide> <ide> protected final Log log = LogFactory.getLog(getClass()); <ide> <ide> model.addAttribute(REQUEST_PARAMETER_NAME_REDIRECT_URL, redirectUrl); <ide> Location lastSessionLocation = null; <ide> try { <del> Context.addProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); <add> Context.addProxyPrivilege(VIEW_LOCATIONS); <ide> Context.addProxyPrivilege(GET_LOCATIONS); <ide> model.addAttribute("locations", appFrameworkService.getLoginLocations()); <ide> lastSessionLocation = locationService.getLocation(Integer.valueOf(lastSessionLocationId)); <ide> // pass <ide> } <ide> finally { <del> Context.removeProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); <add> Context.removeProxyPrivilege(VIEW_LOCATIONS); <ide> Context.removeProxyPrivilege(GET_LOCATIONS); <ide> } <ide> <ide> if (sessionLocationId != null) { <ide> try { <ide> // TODO as above, grant this privilege to Anonymous instead of using a proxy privilege <del> Context.addProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); <add> Context.addProxyPrivilege(VIEW_LOCATIONS); <ide> Context.addProxyPrivilege(GET_LOCATIONS); <ide> sessionLocation = locationService.getLocation(sessionLocationId); <ide> } <ide> finally { <del> Context.removeProxyPrivilege(PrivilegeConstants.VIEW_LOCATIONS); <add> Context.removeProxyPrivilege(VIEW_LOCATIONS); <ide> Context.removeProxyPrivilege(GET_LOCATIONS); <ide> } <ide> }
Java
apache-2.0
error: pathspec 'src/main/java/com/shagaba/jacksync/service/SimpleDiffProcessor.java' did not match any file(s) known to git
c99e7aa990b0e87fff16d7ee0833df6a00c9e6b6
1
shagaba/jacksync,shagaba/jackson-patch-sync
package com.shagaba.jacksync.service; import java.util.Iterator; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Lists; import com.shagaba.jacksync.AddOperation; import com.shagaba.jacksync.PatchOperation; import com.shagaba.jacksync.RemoveOperation; import com.shagaba.jacksync.ReplaceOperation; import com.shagaba.jacksync.utils.JacksonUtils; public class SimpleDiffProcessor implements DiffProcessor { /** * * @param sourceJsonNode * @param targetJsonNode * @return */ @Override public List<PatchOperation> diff(JsonNode sourceJsonNode, JsonNode targetJsonNode) { List<PatchOperation> operations = Lists.newArrayList(); return diff(sourceJsonNode, targetJsonNode, operations, JsonPointer.compile("/")); } /** * * @param sourceJsonNode * @param targetJsonNode * @param patchOperations * @param path * @return */ protected List<PatchOperation> diff(JsonNode sourceJsonNode, JsonNode targetJsonNode, List<PatchOperation> patchOperations, JsonPointer path) { if (!Objects.equals(sourceJsonNode, targetJsonNode)) { if (sourceJsonNode.isArray() && targetJsonNode.isArray()) { List<JsonNode> commonNodes = Lists.newArrayList(sourceJsonNode); List<JsonNode> targetNodes = Lists.newArrayList(targetJsonNode); commonNodes.retainAll(targetNodes); int commonIndex = 0; int sourceIndex = 0; int targetIndex = 0; int maxIndex = Math.max(sourceJsonNode.size(), targetJsonNode.size()); for (int index = 0; index < maxIndex; ++index) { JsonNode commonNode = commonNodes.get(commonIndex); JsonNode sourceNode = sourceJsonNode.get(sourceIndex); JsonNode targetNode = targetJsonNode.get(targetIndex); if (commonNode.equals(sourceNode) && commonNode.equals(targetNode)) { ++commonIndex; ++sourceIndex; ++targetIndex; } else { if (commonNode.equals(sourceNode)) { // add missing target JsonPointer targetPath = JacksonUtils.append(path, Integer.toString(targetIndex++)); patchOperations.add(new AddOperation(targetPath, targetNode.deepCopy())); } else if (commonNode.equals(targetNode)) { // remove target JsonPointer targetPath = JacksonUtils.append(path, Integer.toString(sourceIndex++)); patchOperations.add(new RemoveOperation(targetPath)); } else { JsonPointer targetPath = JacksonUtils.append(path, Integer.toString(targetIndex++)); diff(sourceNode, targetNode, patchOperations, targetPath); ++sourceIndex; } } } } else if (sourceJsonNode.isObject() && targetJsonNode.isObject()) { // source iteration for (Iterator<String> sourceFieldNames = sourceJsonNode.fieldNames(); sourceFieldNames.hasNext();) { String fieldName = sourceFieldNames.next(); JsonPointer fieldNamePath = JacksonUtils.append(path, fieldName); if (targetJsonNode.has(fieldName)) { diff(sourceJsonNode.path(fieldName), targetJsonNode.path(fieldName), patchOperations, fieldNamePath); } else { patchOperations.add(new RemoveOperation(fieldNamePath)); } } // target iteration for (Iterator<String> targetFieldNames = targetJsonNode.fieldNames(); targetFieldNames.hasNext();) { String fieldName = targetFieldNames.next(); if (!sourceJsonNode.has(fieldName)) { JsonPointer fieldNamePath = JacksonUtils.append(path, fieldName); patchOperations.add(new AddOperation(fieldNamePath, targetJsonNode.path(fieldName).deepCopy())); } } } else { patchOperations.add(new ReplaceOperation(path, targetJsonNode.deepCopy())); } } return patchOperations; } }
src/main/java/com/shagaba/jacksync/service/SimpleDiffProcessor.java
simple diff processor - generate operation per field name or object node
src/main/java/com/shagaba/jacksync/service/SimpleDiffProcessor.java
simple diff processor - generate operation per field name or object node
<ide><path>rc/main/java/com/shagaba/jacksync/service/SimpleDiffProcessor.java <add>package com.shagaba.jacksync.service; <add> <add>import java.util.Iterator; <add>import java.util.List; <add>import java.util.Objects; <add> <add>import com.fasterxml.jackson.core.JsonPointer; <add>import com.fasterxml.jackson.databind.JsonNode; <add>import com.google.common.collect.Lists; <add>import com.shagaba.jacksync.AddOperation; <add>import com.shagaba.jacksync.PatchOperation; <add>import com.shagaba.jacksync.RemoveOperation; <add>import com.shagaba.jacksync.ReplaceOperation; <add>import com.shagaba.jacksync.utils.JacksonUtils; <add> <add>public class SimpleDiffProcessor implements DiffProcessor { <add> <add> /** <add> * <add> * @param sourceJsonNode <add> * @param targetJsonNode <add> * @return <add> */ <add> @Override <add> public List<PatchOperation> diff(JsonNode sourceJsonNode, JsonNode targetJsonNode) { <add> List<PatchOperation> operations = Lists.newArrayList(); <add> return diff(sourceJsonNode, targetJsonNode, operations, JsonPointer.compile("/")); <add> } <add> <add> /** <add> * <add> * @param sourceJsonNode <add> * @param targetJsonNode <add> * @param patchOperations <add> * @param path <add> * @return <add> */ <add> protected List<PatchOperation> diff(JsonNode sourceJsonNode, JsonNode targetJsonNode, List<PatchOperation> patchOperations, JsonPointer path) { <add> if (!Objects.equals(sourceJsonNode, targetJsonNode)) { <add> <add> if (sourceJsonNode.isArray() && targetJsonNode.isArray()) { <add> List<JsonNode> commonNodes = Lists.newArrayList(sourceJsonNode); <add> List<JsonNode> targetNodes = Lists.newArrayList(targetJsonNode); <add> commonNodes.retainAll(targetNodes); <add> <add> int commonIndex = 0; <add> int sourceIndex = 0; <add> int targetIndex = 0; <add> int maxIndex = Math.max(sourceJsonNode.size(), targetJsonNode.size()); <add> <add> for (int index = 0; index < maxIndex; ++index) { <add> JsonNode commonNode = commonNodes.get(commonIndex); <add> JsonNode sourceNode = sourceJsonNode.get(sourceIndex); <add> JsonNode targetNode = targetJsonNode.get(targetIndex); <add> <add> if (commonNode.equals(sourceNode) && commonNode.equals(targetNode)) { <add> ++commonIndex; <add> ++sourceIndex; <add> ++targetIndex; <add> } else { <add> if (commonNode.equals(sourceNode)) { <add> // add missing target <add> JsonPointer targetPath = JacksonUtils.append(path, Integer.toString(targetIndex++)); <add> patchOperations.add(new AddOperation(targetPath, targetNode.deepCopy())); <add> } else if (commonNode.equals(targetNode)) { <add> // remove target <add> JsonPointer targetPath = JacksonUtils.append(path, Integer.toString(sourceIndex++)); <add> patchOperations.add(new RemoveOperation(targetPath)); <add> } else { <add> JsonPointer targetPath = JacksonUtils.append(path, Integer.toString(targetIndex++)); <add> diff(sourceNode, targetNode, patchOperations, targetPath); <add> ++sourceIndex; <add> } <add> } <add> } <add> <add> } else if (sourceJsonNode.isObject() && targetJsonNode.isObject()) { <add> // source iteration <add> for (Iterator<String> sourceFieldNames = sourceJsonNode.fieldNames(); sourceFieldNames.hasNext();) { <add> String fieldName = sourceFieldNames.next(); <add> JsonPointer fieldNamePath = JacksonUtils.append(path, fieldName); <add> if (targetJsonNode.has(fieldName)) { <add> diff(sourceJsonNode.path(fieldName), targetJsonNode.path(fieldName), patchOperations, fieldNamePath); <add> } else { <add> patchOperations.add(new RemoveOperation(fieldNamePath)); <add> } <add> } <add> // target iteration <add> for (Iterator<String> targetFieldNames = targetJsonNode.fieldNames(); targetFieldNames.hasNext();) { <add> String fieldName = targetFieldNames.next(); <add> if (!sourceJsonNode.has(fieldName)) { <add> JsonPointer fieldNamePath = JacksonUtils.append(path, fieldName); <add> patchOperations.add(new AddOperation(fieldNamePath, targetJsonNode.path(fieldName).deepCopy())); <add> } <add> } <add> <add> } else { <add> patchOperations.add(new ReplaceOperation(path, targetJsonNode.deepCopy())); <add> } <add> } <add> return patchOperations; <add> } <add> <add>}
JavaScript
apache-2.0
cdfac54ba24277b5f9100e17b115322d646d8caa
0
streitdaniel/dugout,streitdaniel/dugout
Dugout = function() { var CONST_BASE_SPEED = 2, CONST_TURNING_SPEED = 3, CONST_COLORS = ['#ed008c', '#8cc63e', '#fcb040', '#008ad2'], audio = new Dugout_Audio(this), graphics = new Dugout_Graphics(this), logic = new Dugout_Logic(this), players = {}, playersLength = 0, playersAlive = 0, allPlayersReady = false, room, qrCodeURL; this.run = run; this.audio = audio; this.getQRCode = getQRCode; this.getPlayers = getPlayers; this.getOrderedPlayers = getOrderedPlayers; this.renderBonuses = renderBonuses; this.setNewPosition = setNewPosition; this.getVisibleCanvases = getVisibleCanvases; this.detectCollisions = detectCollisions; this.killPlayer = killPlayer; this.adjustPlayersAbility = adjustPlayersAbility; this.isSlimeAt = isSlimeAt; this.addScore = addScore; this.CONST_COLORS_NAMES = ['blue', 'green', 'red', 'yellow']; function run() { room = new MAF.PrivateRoom(new Date().getTime() + 'dugout_game'); (function (event) { var payload = event.payload; switch (event.type) { case 'onConnected': log('room connected'); // If connected but room not joined make sure to join it automaticly if (!room.joined) room.join(); return; case 'onDisconnected': onDisconnected(); log('connection lost waiting for reconnect and automaticly rejoin'); return; case 'onCreated': // Create an url to the client application and pass the hash as querystring onCreated(payload); log('room created', payload.hash); return; case 'onDestroyed': onDestroyed(); // Reset clients log('room destroyed', payload.hash); return; case 'onJoined': // If user is not the app then log the user if (payload.user !== room.user) { onJoined(payload); log('user joined', payload.user); } return; case 'onHasLeft': // If user is not the app then log the user if (payload.user !== room.user) onHasLeft(payload); log('user has left', payload.user); return; case 'onData': onData(payload.user, payload.data); break; default: log(event.type, payload); break; } }).subscribeTo(room, ['onConnected', 'onDisconnected', 'onCreated', 'onDestroyed', 'onJoined', 'onHasLeft', 'onData', 'onError']); // If Room socket is connected create and join room if (room.connected) room.join(); console.log("CONNECTED ---------------------------------"); } function onDisconnected() { } function onCreated(payload) { qrCodeURL = widget.getUrl('Client/index.html?hash=' + payload.hash); } function onDestroyed() { } function onJoined(payload) { addPlayer(payload.user); } function onHasLeft(payload) { removePlayer(payload.user); } function onData(userKey, data) { switch (data.event) { case 'cl_join': clJoin(userKey, data); break; case 'cl_ready': clReady(userKey, data); break; case 'cl_start_game': clStartGame(userKey); break; case 'cl_turn_left': clTurn(userKey, true); break; case 'cl_turn_right': clTurn(userKey, false); break; case 'cl_exit': clExit(userKey); break; } } function sendMessage(event, key, data) { if (key.toString() === key) { key = [key]; } room.send({ event: event, clients: key, attrs: data }); } function sendEvent(event) { MAF.messages.store("dugout:" + event, event); } function addPlayer(user) { players[user] = { name: "Player " + (playersLength + 1), color: CONST_COLORS[players.length], position: { x: 0, y: 0 }, direction: 0, speed: CONST_BASE_SPEED, turning_speed: CONST_TURNING_SPEED, dead: false, ready: false, score: 0 }; playersLength++; sendEvent("refresh_players"); } function removePlayer(user) { var i, key; delete players[user]; i = 0; for (key in players) { players[key].color = CONST_COLORS[i]; i++; } playersLength--; sendEvent("refresh_players"); } function getQRCode() { return qrCodeURL; } function getPlayers() { return players; } function getOrderedPlayers() { var key, max1, max2, max3, max4, max1v = -1, max2v = -1, max3v = -1, max4v, orderedPlayers = []; for (key in players) { max4 = key; max4v = players[key].score; if (max4v > max3v) { max4v = max3v; max4 = max3; max3 = key; max3v = players[key].value; } if (max3v > max2v) { max3v = max2v; max3 = max2; max2 = key; max2v = players[key].value; } if (max2v > max1v) { max2v = max1v; max2 = max1; max1 = key; max1v = players[key].value; } } if (players[max1]) { orderedPlayers.push(players[max1]); } if (players[max2]) { orderedPlayers.push(players[max2]); } if (players[max3]) { orderedPlayers.push(players[max3]); } if (players[max4]) { orderedPlayers.push(players[max4]); } return orderedPlayers; } function setNewPosition(p) { var key; for (key in p) { players[key].position = p[key].newPosition; } } function renderBonuses() { return logic.renderBonuses(); } function getVisibleCanvases() { return graphics.getVisibleCanvases(); } function detectCollisions() { logic.detectDeaths(players); logic.detectBonuses(players); } function killPlayer(key) { players[key].dead = true; audio.playSound(audio.DEATH_SOUND); sendMessage('tv_death', key); playersAlive--; if (playersAlive < 2) { endGame(); } } function adjustPlayersAbility(key, ability, diff, others) { var k; if (!others) { players[key][ability] += diff; } else { for (k in players) { if (k === key) { continue; } players[k][ability] += diff; } } } function isSlimeAt(x, y) { return graphics.isSlimeAt(x, y); } function addScore() { var key; for (key in players) { if (!players[key].dead) { players[key].score += 1; } } sendEvent("refresh_players"); } function clJoin(key) { var notReady = [], k; if (playersLength < 4) { addPlayer(key); if (allPlayersReady) { allPlayersReady = false; for (k in players) { if (players[k].ready) { notReady.push(k); } } sendMessage('tv_not_all_ready', notReady, {}); } sendMessage("tv_accepted", key, { color: players[key].color, name: players[key].name }); } else { sendMessage("tv_rejected", key, { error: { code: 429, message: "Too many players" } }); } } function clReady(key, data) { var k, allReady = true; if (data && data.attrs && data.attrs.name && data.attrs.name.length > 0) { players[key].name = data.attrs.name; } players[key].ready = true; sendEvent("refresh_players"); for (k in players) { if (!players[k].ready) { allReady = false; break; } } if (playersLength === 4 && allReady) { startTheGame(); } else if (allReady) { everyoneReady(); } } function clStartGame(key) { startTheGame(); } function clTurn(key, left) { if (left) { players[key].direction -= players[key].turning_speed * Math.PI / 180; } else { players[key].direction += players[key].turning_speed * Math.PI / 180; } } function clExit(key) { removePlayer(key); } function everyoneReady() { sendMessage('tv_all_ready', [], { num_players: playersLength }); allPlayersReady = true; } function startTheGame() { countdown(); randomlyPositionPlayers(); } function countdown() { sendEvent("countdown"); } function startDigging() { var key, playing = []; for (key in players) { playing.push(key); } playersAlive = playersLength; sendMessage('tv_show_controls', playing, {}); } function restartGame() { var key, playing = []; for (key in players) { players[key].ready = false; players[key].speed = CONST_BASE_SPEED; players[key].turning_speed = CONST_TURNING_SPEED; players[key].dead = false; players[key].score = 0; playing.push(key); } sendMessage('tv_continue', playing, {}); } function endGame() { sendEvent("end_game"); } function randomlyPositionPlayers() { var i, k, keys = [], keysLength, x, y, direction; for (k in players) { keys.push(k); } shuffle(keys); keysLength = keys.length; for (i = 0; i < keysLength; i++) { x = Math.random() * 755; y = Math.random() * 350; direction = Math.random() * Math.PI / 2; if (i == 0) { direction += Math.PI / 2; } else if (i == 1) { x += 890; direction += Math.PI; } else if (i == 2) { y += 450; } else if (i == 3) { x += 890; y += 450; direction += 3 * Math.PI / 2; } players[keys[i]].position.x = x; players[keys[i]].position.y = y; players[keys[i]].position.direction = direction; } } function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } };
com.mautilus.app.Dugout/Contents/Javascript/Engine/Dugout/dugout.js
Dugout = function() { var CONST_BASE_SPEED = 2, CONST_TURNING_SPEED = 3, CONST_COLORS = ['#ed008c', '#8cc63e', '#fcb040', '#008ad2'], audio = new Dugout_Audio(this), graphics = new Dugout_Graphics(this), logic = new Dugout_Logic(this), players = {}, playersLength = 0, playersAlive = 0, allPlayersReady = false, room, qrCodeURL; this.run = run; this.audio = audio; this.getQRCode = getQRCode; this.getPlayers = getPlayers; this.getOrderedPlayers = getOrderedPlayers; this.renderBonuses = renderBonuses; this.setNewPosition = setNewPosition; this.getVisibleCanvases = getVisibleCanvases; this.detectCollisions = detectCollisions; this.killPlayer = killPlayer; this.adjustPlayersAbility = adjustPlayersAbility; this.isSlimeAt = isSlimeAt; this.addScore = addScore; this.CONST_COLORS_NAMES = ['blue', 'green', 'red', 'yellow']; function run() { room = new MAF.PrivateRoom(new Date().getTime() + 'dugout_game'); (function (event) { var payload = event.payload; switch (event.type) { case 'onConnected': log('room connected'); // If connected but room not joined make sure to join it automaticly if (!room.joined) room.join(); return; case 'onDisconnected': onDisconnected(); log('connection lost waiting for reconnect and automaticly rejoin'); return; case 'onCreated': // Create an url to the client application and pass the hash as querystring onCreated(payload); log('room created', payload.hash); return; case 'onDestroyed': onDestroyed(); // Reset clients log('room destroyed', payload.hash); return; case 'onJoined': // If user is not the app then log the user if (payload.user !== room.user) { onJoined(payload); log('user joined', payload.user); } return; case 'onHasLeft': // If user is not the app then log the user if (payload.user !== room.user) onHasLeft(payload); log('user has left', payload.user); return; case 'onData': onData(payload.user, payload.data); break; default: log(event.type, payload); break; } }).subscribeTo(room, ['onConnected', 'onDisconnected', 'onCreated', 'onDestroyed', 'onJoined', 'onHasLeft', 'onData', 'onError']); // If Room socket is connected create and join room if (room.connected) room.join(); console.log("CONNECTED ---------------------------------"); } function onDisconnected() { } function onCreated(payload) { qrCodeURL = widget.getUrl('Client/index.html?hash=' + payload.hash); } function onDestroyed() { } function onJoined(payload) { addPlayer(payload.user); } function onHasLeft(payload) { removePlayer(payload.user); } function onData(userKey, data) { switch (data.event) { case 'cl_join': clJoin(userKey, data); break; case 'cl_ready': clReady(userKey, data); break; case 'cl_start_game': clStartGame(userKey); break; case 'cl_turn_left': clTurn(userKey, true); break; case 'cl_turn_right': clTurn(userKey, false); break; case 'cl_exit': clExit(userKey); break; } } function sendMessage(event, key, data) { if (key.toString() === key) { key = [key]; } room.send({ event: event, clients: key, attrs: data }); } function sendEvent(event) { MAF.messages.store("dugout:" + event, event); } function addPlayer(user) { players[user] = { name: "Player " + (playersLength + 1), color: CONST_COLORS[players.length], position: { x: 0, y: 0 }, direction: 0, speed: CONST_BASE_SPEED, turning_speed: CONST_TURNING_SPEED, dead: false, ready: false, score: 0 }; playersLength++; sendEvent("refresh_players"); } function removePlayer(user) { var i, key; delete players[user]; i = 0; for (key in players) { players[key].color = CONST_COLORS[i]; i++; } playersLength--; sendEvent("refresh_players"); } function getQRCode() { return qrCodeURL; } function getPlayers() { return players; } function getOrderedPlayers() { var key, max1, max2, max3, max4, max1v = -1, max2v = -1, max3v = -1, max4v, orderedPlayers = []; for (key in players) { max4 = key; max4v = players[key].score; if (max4v > max3v) { max4v = max3v; max4 = max3; max3 = key; max3v = players[key].value; } if (max3v > max2v) { max3v = max2v; max3 = max2; max2 = key; max2v = players[key].value; } if (max2v > max1v) { max2v = max1v; max2 = max1; max1 = key; max1v = players[key].value; } } if (players[max1]) { orderedPlayers.push(players[max1]); } if (players[max2]) { orderedPlayers.push(players[max2]); } if (players[max3]) { orderedPlayers.push(players[max3]); } if (players[max4]) { orderedPlayers.push(players[max4]); } return orderedPlayers; } function setNewPosition(p) { var key; for (key in p) { players[key].position = p[key].newPosition; } } function renderBonuses() { return logic.renderBonuses(); } function getVisibleCanvases() { return graphics.getVisibleCanvases(); } function detectCollisions() { logic.detectDeaths(players); logic.detectBonuses(players); } function killPlayer(key) { players[key].dead = true; audio.playSound(audio.DEATH_SOUND); sendMessage('tv_death', key); playersAlive--; if (playersAlive < 2) { endGame(); } } function adjustPlayersAbility(key, ability, diff, others) { var k; if (!others) { players[key][ability] += diff; } else { for (k in players) { if (k === key) { continue; } players[k][ability] += diff; } } } function isSlimeAt(x, y) { return graphics.isSlimeAt(x, y); } function addScore() { var key; for (key in players) { if (!players[key].dead) { players[key].score += 1; } } } function clJoin(key) { var notReady = [], k; if (playersLength < 4) { addPlayer(key); if (allPlayersReady) { allPlayersReady = false; for (k in players) { if (players[k].ready) { notReady.push(k); } } sendMessage('tv_not_all_ready', notReady, {}); } sendMessage("tv_accepted", key, { color: players[key].color, name: players[key].name }); } else { sendMessage("tv_rejected", key, { error: { code: 429, message: "Too many players" } }); } } function clReady(key, data) { var k, allReady = true; if (data && data.attrs && data.attrs.name && data.attrs.name.length > 0) { players[key].name = data.attrs.name; } players[key].ready = true; for (k in players) { if (!players[k].ready) { allReady = false; break; } } if (playersLength === 4 && allReady) { startTheGame(); } else if (allReady) { everyoneReady(); } } function clStartGame(key) { startTheGame(); } function clTurn(key, left) { if (left) { players[key].direction -= players[key].turning_speed * Math.PI / 180; } else { players[key].direction += players[key].turning_speed * Math.PI / 180; } } function clExit(key) { removePlayer(key); } function everyoneReady() { sendMessage('tv_all_ready', [], { num_players: playersLength }); allPlayersReady = true; } function startTheGame() { countdown(); randomlyPositionPlayers(); } function countdown() { sendEvent("countdown"); } function startDigging() { var key, playing = []; for (key in players) { playing.push(key); } playersAlive = playersLength; sendMessage('tv_show_controls', playing, {}); } function restartGame() { var key, playing = []; for (key in players) { players[key].ready = false; players[key].speed = CONST_BASE_SPEED; players[key].turning_speed = CONST_TURNING_SPEED; players[key].dead = false; players[key].score = 0; playing.push(key); } sendMessage('tv_continue', playing, {}); } function endGame() { sendEvent("end_game"); } function randomlyPositionPlayers() { var i, k, keys = [], keysLength, x, y, direction; for (k in players) { keys.push(k); } shuffle(keys); keysLength = keys.length; for (i = 0; i < keysLength; i++) { x = Math.random() * 755; y = Math.random() * 350; direction = Math.random() * Math.PI / 2; if (i == 0) { direction += Math.PI / 2; } else if (i == 1) { x += 890; direction += Math.PI; } else if (i == 2) { y += 450; } else if (i == 3) { x += 890; y += 450; direction += 3 * Math.PI / 2; } players[keys[i]].position.x = x; players[keys[i]].position.y = y; players[keys[i]].position.direction = direction; } } function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } };
[Engine] Sending more refresh_players events (after score and readystatechange)
com.mautilus.app.Dugout/Contents/Javascript/Engine/Dugout/dugout.js
[Engine] Sending more refresh_players events (after score and readystatechange)
<ide><path>om.mautilus.app.Dugout/Contents/Javascript/Engine/Dugout/dugout.js <ide> players[key].score += 1; <ide> } <ide> } <add> sendEvent("refresh_players"); <ide> } <ide> <ide> function clJoin(key) { <ide> players[key].name = data.attrs.name; <ide> } <ide> players[key].ready = true; <add> sendEvent("refresh_players"); <ide> for (k in players) { <ide> if (!players[k].ready) { <ide> allReady = false;
Java
bsd-3-clause
47803d886da9cfbf87c484abe7390550b767af15
0
ukcrpb6/jaxen-wmb-extensions,appcelerator/jaxen_titanium
/* * $Header$ * $Revision$ * $Date$ * * ==================================================================== * * Copyright (C) 2000-2002 bob mcwhirter & James Strachan. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the disclaimer that follows * these conditions in the documentation and/or other materials * provided with the distribution. * * 3. The name "Jaxen" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 4. Products derived from this software may not be called "Jaxen", nor * may "Jaxen" appear in their name, without prior written permission * from the Jaxen Project Management ([email protected]). * * In addition, we request (but do not require) that you include in the * end-user documentation provided with the redistribution and/or in the * software itself an acknowledgement equivalent to the following: * "This product includes software developed by the * Jaxen Project (http://www.jaxen.org/)." * Alternatively, the acknowledgment may be graphical using the logos * available at http://www.jaxen.org/ * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE Jaxen AUTHORS OR THE PROJECT * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ==================================================================== * This software consists of voluntary contributions made by many * individuals on behalf of the Jaxen Project and was originally * created by bob mcwhirter <[email protected]> and * James Strachan <[email protected]>. For more information on the * Jaxen Project, please see <http://www.jaxen.org/>. * * $Id$ */ package org.jaxen.saxpath.base; import junit.framework.TestCase; public class XPathLexerTest extends TestCase { private XPathLexer lexer; private Token token; public XPathLexerTest(String name) { super( name ); } public void setUp() { } public void tearDown() { setLexer( null ); setToken( null ); } public void testNamespace() { setText( "a:b" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "a", tokenText() ); nextToken(); assertEquals( TokenTypes.COLON, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "b", tokenText() ); } public void testIdentifier() { setText( "foo" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); setText( "foo.bar" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo.bar", tokenText() ); } /** * This tests that characters added in XML 1.1 and Unicode 3.0 * are not recognized as legal name characters. */ public void testBurmeseIdentifier() { setText( "\u1000foo" ); nextToken(); assertEquals( TokenTypes.ERROR, tokenType() ); } public void testIdentifierAndOperator() { setText( "foo and bar" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.AND, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "bar", tokenText() ); } public void testTrickyIdentifierAndOperator() { setText( "and and and" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "and", tokenText() ); nextToken(); assertEquals( TokenTypes.AND, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "and", tokenText() ); } public void testInteger() { setText( "1234" ); nextToken(); assertEquals( TokenTypes.INTEGER, tokenType() ); assertEquals( "1234", tokenText() ); } public void testDouble() { setText( "12.34" ); nextToken(); assertEquals( TokenTypes.DOUBLE, tokenType() ); assertEquals( "12.34", tokenText() ); } public void testDoubleOnlyDecimal() { setText( ".34" ); nextToken(); assertEquals( TokenTypes.DOUBLE, tokenType() ); assertEquals( ".34", tokenText() ); } public void testNumbersAndMode() { setText( "12.34 mod 3" ); nextToken(); assertEquals( TokenTypes.DOUBLE, tokenType() ); assertEquals( "12.34", tokenText() ); nextToken(); assertEquals( TokenTypes.MOD, tokenType() ); nextToken(); assertEquals( TokenTypes.INTEGER, tokenType() ); } public void testSlash() { setText( "/" ); nextToken(); assertEquals( TokenTypes.SLASH, tokenType() ); } public void testDoubleSlash() { setText( "//" ); nextToken(); assertEquals( TokenTypes.DOUBLE_SLASH, tokenType() ); } public void testIdentifierWithColon() { setText ( "foo:bar" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.COLON, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "bar", tokenText() ); } public void testEOF() { setText( "foo" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.EOF, tokenType() ); } /* public void testAttributeWithUnderscore() { setText( "@_foo" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "_foo", tokenText() ); nextToken(); assertEquals( TokenTypes.EOF, tokenType() ); } */ public void testWhitespace() { setText ( " / \tfoo:bar" ); nextToken(); assertEquals( TokenTypes.SLASH, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.COLON, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "bar", tokenText() ); } private void nextToken() { setToken( getLexer().nextToken() ); } private int tokenType() { return getToken().getTokenType(); } private String tokenText() { return getToken().getTokenText(); } private Token getToken() { return this.token; } private void setToken(Token token) { this.token = token; } private void setText(String text) { this.lexer = new XPathLexer( text ); } private void setLexer(XPathLexer lexer) { this.lexer = lexer; } private XPathLexer getLexer() { return this.lexer; } }
src/java/test/org/jaxen/saxpath/base/XPathLexerTest.java
/* * $Header$ * $Revision$ * $Date$ * * ==================================================================== * * Copyright (C) 2000-2002 bob mcwhirter & James Strachan. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the disclaimer that follows * these conditions in the documentation and/or other materials * provided with the distribution. * * 3. The name "Jaxen" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 4. Products derived from this software may not be called "Jaxen", nor * may "Jaxen" appear in their name, without prior written permission * from the Jaxen Project Management ([email protected]). * * In addition, we request (but do not require) that you include in the * end-user documentation provided with the redistribution and/or in the * software itself an acknowledgement equivalent to the following: * "This product includes software developed by the * Jaxen Project (http://www.jaxen.org/)." * Alternatively, the acknowledgment may be graphical using the logos * available at http://www.jaxen.org/ * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE Jaxen AUTHORS OR THE PROJECT * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * ==================================================================== * This software consists of voluntary contributions made by many * individuals on behalf of the Jaxen Project and was originally * created by bob mcwhirter <[email protected]> and * James Strachan <[email protected]>. For more information on the * Jaxen Project, please see <http://www.jaxen.org/>. * * $Id$ */ package org.jaxen.saxpath.base; import junit.framework.TestCase; public class XPathLexerTest extends TestCase { private XPathLexer lexer; private Token token; public XPathLexerTest(String name) { super( name ); } public void setUp() { } public void tearDown() { setLexer( null ); setToken( null ); } public void testNamespace() { setText( "a:b" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "a", tokenText() ); nextToken(); assertEquals( TokenTypes.COLON, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "b", tokenText() ); } public void testIdentifier() { setText( "foo" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); setText( "foo.bar" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo.bar", tokenText() ); } public void testIdentifierAndOperator() { setText( "foo and bar" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.AND, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "bar", tokenText() ); } public void testTrickyIdentifierAndOperator() { setText( "and and and" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "and", tokenText() ); nextToken(); assertEquals( TokenTypes.AND, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "and", tokenText() ); } public void testInteger() { setText( "1234" ); nextToken(); assertEquals( TokenTypes.INTEGER, tokenType() ); assertEquals( "1234", tokenText() ); } public void testDouble() { setText( "12.34" ); nextToken(); assertEquals( TokenTypes.DOUBLE, tokenType() ); assertEquals( "12.34", tokenText() ); } public void testDoubleOnlyDecimal() { setText( ".34" ); nextToken(); assertEquals( TokenTypes.DOUBLE, tokenType() ); assertEquals( ".34", tokenText() ); } public void testNumbersAndMode() { setText( "12.34 mod 3" ); nextToken(); assertEquals( TokenTypes.DOUBLE, tokenType() ); assertEquals( "12.34", tokenText() ); nextToken(); assertEquals( TokenTypes.MOD, tokenType() ); nextToken(); assertEquals( TokenTypes.INTEGER, tokenType() ); } public void testSlash() { setText( "/" ); nextToken(); assertEquals( TokenTypes.SLASH, tokenType() ); } public void testDoubleSlash() { setText( "//" ); nextToken(); assertEquals( TokenTypes.DOUBLE_SLASH, tokenType() ); } public void testIdentifierWithColon() { setText ( "foo:bar" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.COLON, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "bar", tokenText() ); } public void testEOF() { setText( "foo" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.EOF, tokenType() ); } /* public void testAttributeWithUnderscore() { setText( "@_foo" ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "_foo", tokenText() ); nextToken(); assertEquals( TokenTypes.EOF, tokenType() ); } */ public void testWhitespace() { setText ( " / \tfoo:bar" ); nextToken(); assertEquals( TokenTypes.SLASH, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "foo", tokenText() ); nextToken(); assertEquals( TokenTypes.COLON, tokenType() ); nextToken(); assertEquals( TokenTypes.IDENTIFIER, tokenType() ); assertEquals( "bar", tokenText() ); } private void nextToken() { setToken( getLexer().nextToken() ); } private int tokenType() { return getToken().getTokenType(); } private String tokenText() { return getToken().getTokenText(); } private Token getToken() { return this.token; } private void setToken(Token token) { this.token = token; } private void setText(String text) { this.lexer = new XPathLexer( text ); } private void setLexer(XPathLexer lexer) { this.lexer = lexer; } private XPathLexer getLexer() { return this.lexer; } }
Adding test that XML name rules are followed rather than Unicode name rules git-svn-id: 7abf240ce0ec4644a9bf59262a41ad5796234f37@427 43379f7c-b030-0410-81db-e0b70742847c
src/java/test/org/jaxen/saxpath/base/XPathLexerTest.java
Adding test that XML name rules are followed rather than Unicode name rules
<ide><path>rc/java/test/org/jaxen/saxpath/base/XPathLexerTest.java <ide> tokenText() ); <ide> } <ide> <add> <add> /** <add> * This tests that characters added in XML 1.1 and Unicode 3.0 <add> * are not recognized as legal name characters. <add> */ <add> public void testBurmeseIdentifier() <add> { <add> setText( "\u1000foo" ); <add> <add> nextToken(); <add> <add> assertEquals( TokenTypes.ERROR, <add> tokenType() ); <add> <add> } <add> <ide> public void testIdentifierAndOperator() <ide> { <ide> setText( "foo and bar" );
Java
apache-2.0
78cbbf99dcc5505474781943b7dac4245976c191
0
seznam/euphoria,seznam/euphoria
/** * Copyright 2016-2017 Seznam.cz, a.s. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.seznam.euphoria.examples.wordcount; import cz.seznam.euphoria.core.client.dataset.Dataset; import cz.seznam.euphoria.core.client.dataset.windowing.Time; import cz.seznam.euphoria.core.client.dataset.windowing.TimeInterval; import cz.seznam.euphoria.core.client.flow.Flow; import cz.seznam.euphoria.core.client.io.Context; import cz.seznam.euphoria.core.client.io.DataSink; import cz.seznam.euphoria.core.client.io.DataSource; import cz.seznam.euphoria.core.client.io.StdoutSink; import cz.seznam.euphoria.core.client.operator.AssignEventTime; import cz.seznam.euphoria.core.client.operator.FlatMap; import cz.seznam.euphoria.core.client.operator.MapElements; import cz.seznam.euphoria.core.client.operator.ReduceByKey; import cz.seznam.euphoria.core.client.util.Pair; import cz.seznam.euphoria.core.client.util.Sums; import cz.seznam.euphoria.core.executor.Executor; import cz.seznam.euphoria.examples.Executors; import cz.seznam.euphoria.hadoop.input.SimpleHadoopTextFileSource; import java.text.SimpleDateFormat; import java.time.Duration; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Simple aggregation of logs in Apache log format. Counts the number of daily * hits per client. This is a word-count like program utilizing time windowing * based on event time. * <p> * If newly coming the euphoria API, you are advised to first study the * {@link SimpleWordCount} program. * <p> * * Example usage on flink: * <pre>{@code * $ flink run -m yarn-cluster \ * -yn 1 -ys 2 -ytm 800 \ * -c cz.seznam.euphoria.examples.wordcount.AccessLogCount \ * euphoria-examples/assembly/euphoria-examples.jar \ * "flink" \ * "hdfs:///tmp/access.log" *}</pre> * * Example usage on spark: * <pre>{@code * $ spark-submit --verbose --deploy-mode cluster \ * --master yarn \ * --executor-memory 1g \ * --num-executors 1 \ * --class cz.seznam.euphoria.examples.wordcount.AccessLogCount \ * euphoria-examples/assembly/euphoria-examples.jar \ * "spark" \ * "hdfs:///tmp/access.log" * }</pre> */ public class AccessLogCount { public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: " + AccessLogCount.class + " <executor-name> <input-path>"); System.exit(1); } final String executorName = args[0]; final String inputPath = args[1]; // As with the {@code SimpleWordCount} we define a source to read data from ... DataSource<String> dataSource = new SimpleHadoopTextFileSource(inputPath); // ... and a sink to write the business logic's output to. In this particular // case we use a sink that eventually writes out the data to the executors // standard output. This is rarely useful in production environments but // is handy in local executions. DataSink<String> dataSink = new StdoutSink<>(); // We start by allocating a new flow, a container to encapsulates the // chain of transformations. Flow flow = Flow.create("Access log processor"); // From the data source describing the actual input data location and // physical form, we create an abstract data set to be processed in the // context of the created flow. // // As in other examples, reading the actual input source is deferred // until the flow's execution. The data itself is _not_ touched at this // point in time yet. Dataset<String> input = flow.createInput(dataSource); // We assume the actual input data to have a particular format; in this // case, each element is expected to be a log line from the Apache's access // log. We "map" the "parseLine" function over each such line to transform // the raw log entry into a more structured object. // // Note: Using `MapElements` implies that for each input we generate an // output. In the context of this program it means, that we are not able // to naturally "skip" invalid log lines. // // Note: Generally, user defined functions must be thread-safe. If you // inspect the `parseLine` function, you'll see that it allocates a new // `SimpleDateFormat` instance for every input element since sharing such // an instance between threads without explicit synchronization is not // thread-safe. (In this example we have intentionally used the // `SimpleDateFormat` to make this point. In a read-world program you // would probably hand out to `DateTimeFormatter` which can be safely // be re-used across threads.) Dataset<LogLine> parsed = MapElements.named("LOG-PARSER") .of(input) .using(LogParser::parseLine) .output(); // Since our log lines represent events which happened at a particular // point in time, we want our system to treat them as such, no matter in // which particular order the lines happen to be in the read input files. // // We do so by applying a so-called event-time-extractor function. As of // this moment, euphoria will treat the element as if it happended in the // corresponding time since it gets to know the timestamp the event occurred. parsed = AssignEventTime.of(parsed) .using(line -> line.getDate().getTime()) .output(); // In the previous step we derived a data set specifying points in time // at which particular IPs accessed our web-server. Our goal is now to // count how often a particular IP accessed the web-server, per day. This // is, instead of deriving the count of a particular IP from the whole // input, we want to know the number of hits per IP for every day // distinctly (we're not interested in zero hit counts, of course.) // // Actually, this computation is merely a word-count problem explained // in the already mentioned {@link SimpleWordCount}. We just count the // number of occurrences of a particular IP. However, we also specify // how the input is to be "windowed." // // Windowing splits the input into fixed sections of chunks. Such as we // can divide a data set into chunks by a certain size, we can split // a data set into chunks defined by time, e.g. a chunk for day one, // another chunk for day two, etc. provided that elements of the data // set have a notion of time. Once the input data set is logically divided // into these "time windows", the computation takes place separately on // each of them, and, produces a results for each window separately. // // Here, we specify time based windowing using the `Time.of(..)` method // specifying the size of the windows, in particular "one day" in this // example. The assignment of an element to a particular time window, // will, by definition, utilize the processed elements assigned timestamp. // This is what we did in the previous step. // // Note: There are a few different windowing strategies and you can // investigate each by looking for classes implementing {@link Windowing}. // // Note: You might wonder why we didn't just a // "select ip, count(*) from input group by (ip, day)". First, windowing // as such is a separate concern to the actual computation; there is no // need to mix them up and further complicate the actual computation. // Being a separate concern it allows for easier exchange and // experimentation. Second, by specifying windowing as a separate concern, // we can make the computation work even on unbounded, i.e. endless, input // streams. Windowing strategies generally work together with the // executor and can define a point when a window is determined to be // "filled" at which point the windows data can be processed, calculated, // and the corresponding results emitted. This makes endless stream // processing work. Dataset<Pair<String, Long>> aggregated = ReduceByKey.named("AGGREGATE") .of(parsed) .keyBy(LogLine::getIp) .valueBy(line -> 1L) .combineBy(Sums.ofLongs()) .windowBy(Time.of(Duration.ofDays(1))) .output(); // At the final stage of our flow, we nicely format the previously emitted // results before persisting them to a given data sink, e.g. external storage. // // The elements emitted from the previous operator specify the windowed // results of the "IP-count". This is, for each IP we get a count of the // number of its occurrences (within a window.) The window information // itself - if desired - can be accessed from the `FlatMap`'s context // parameter as demonstrated below. FlatMap.named("FORMAT-OUTPUT") .of(aggregated) .using(((Pair<String, Long> elem, Context<String> context) -> { Date d = new Date(((TimeInterval) context.getWindow()).getStartMillis()); SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy", Locale.ENGLISH); context.collect(sdf.format(d) + "\t" + elem.getFirst() + "\t" + elem.getSecond()); })) .output() .persist(dataSink); // Finally, we allocate an executor and submit our flow for execution on it. Executor executor = Executors.createExecutor(executorName); executor.submit(flow).get(); } private static class LogParser { private static Pattern pattern = Pattern.compile("^([[0-9a-zA-z-].]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\].*"); public static LogLine parseLine(String line) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { try { // SDF is not thread-safe, so we need to allocate one here. Ideally, // we'd use `DateTimeFormatter` and re-use it across input elements. // see the corresponding note at the operator utilizing `parseLine`. SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH); String ip = matcher.group(1); Date date = sdf.parse(matcher.group(4)); return new LogLine(ip, date); } catch (Exception e) { throw new IllegalStateException(e); } } throw new IllegalStateException("Invalid log format: " + line); } } private static class LogLine { private final String ip; private final Date date; public LogLine(String ip, Date date) { this.ip = ip; this.date = date; } public String getIp() { return ip; } public Date getDate() { return date; } } }
euphoria-examples/src/main/java/cz/seznam/euphoria/examples/wordcount/AccessLogCount.java
/** * Copyright 2016-2017 Seznam.cz, a.s. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.seznam.euphoria.examples.wordcount; import cz.seznam.euphoria.core.client.dataset.Dataset; import cz.seznam.euphoria.core.client.dataset.windowing.Time; import cz.seznam.euphoria.core.client.dataset.windowing.TimeInterval; import cz.seznam.euphoria.core.client.flow.Flow; import cz.seznam.euphoria.core.client.io.Context; import cz.seznam.euphoria.core.client.io.DataSink; import cz.seznam.euphoria.core.client.io.DataSource; import cz.seznam.euphoria.core.client.io.StdoutSink; import cz.seznam.euphoria.core.client.operator.FlatMap; import cz.seznam.euphoria.core.client.operator.MapElements; import cz.seznam.euphoria.core.client.operator.ReduceByKey; import cz.seznam.euphoria.core.client.util.Pair; import cz.seznam.euphoria.core.client.util.Sums; import cz.seznam.euphoria.core.executor.Executor; import cz.seznam.euphoria.examples.Executors; import cz.seznam.euphoria.hadoop.input.SimpleHadoopTextFileSource; import java.text.SimpleDateFormat; import java.time.Duration; import java.util.Date; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Simple aggregation of logs in Apache log format. Counts the number of daily * hits per client. This is a word-count like program utilizing time windowing * based on event time. * <p> * If newly coming the euphoria API, you are advised to first study the * {@link SimpleWordCount} program. * <p> * * Example usage on flink: * <pre>{@code * $ flink run -m yarn-cluster \ * -yn 1 -ys 2 -ytm 800 \ * -c cz.seznam.euphoria.examples.wordcount.AccessLogCount \ * euphoria-examples/assembly/euphoria-examples.jar \ * "flink" \ * "hdfs:///tmp/access.log" *}</pre> * * Example usage on spark: * <pre>{@code * $ spark-submit --verbose --deploy-mode cluster \ * --master yarn \ * --executor-memory 1g \ * --num-executors 1 \ * --class cz.seznam.euphoria.examples.wordcount.AccessLogCount \ * euphoria-examples/assembly/euphoria-examples.jar \ * "spark" \ * "hdfs:///tmp/access.log" * }</pre> */ public class AccessLogCount { public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: " + AccessLogCount.class + " <executor-name> <input-path>"); System.exit(1); } final String executorName = args[0]; final String inputPath = args[1]; // As with the {@code SimpleWordCount} we define a source to read data from ... DataSource<String> dataSource = new SimpleHadoopTextFileSource(inputPath); // ... and a sink to write the business logic's output to. In this particular // case we use a sink that eventually writes out the data to the executors // standard output. This is rarely useful in production environments but // is handy in local executions. DataSink<String> dataSink = new StdoutSink<>(); // We start by allocating a new flow, a container to encapsulates the // chain of transformations. Flow flow = Flow.create("Access log processor"); // From the data source describing the actual input data location and // physical form, we create an abstract data set to be processed in the // context of the created flow. // // As in other examples, reading the actual input source is deferred // until the flow's execution. The data itself is _not_ touched at this // point in time yet. Dataset<String> input = flow.createInput(dataSource); // We assume the actual input data to have a particular format; in this // case, each element is expected to be a log line from the Apache's access // log. We "map" the "parseLine" function over each such line to transform // the raw log entry into a more structured object. // // Note: Using `MapElements` implies that for each input we generate an // output. In the context of this program it means, that we are not able // to naturally "skip" invalid log lines. // // Note: Generally, user defined functions must be thread-safe. If you // inspect the `parseLine` function, you'll see that it allocates a new // `SimpleDateFormat` instance for every input element since sharing such // an instance between threads without explicit synchronization is not // thread-safe. (In this example we have intentionally used the // `SimpleDateFormat` to make this point. In a read-world program you // would probably hand out to `DateTimeFormatter` which can be safely // be re-used across threads.) Dataset<LogLine> parsed = MapElements.named("LOG-PARSER") .of(input) .using(LogParser::parseLine) .output(); // In the previous step we derived a data set specifying points in time // at which particular IPs accessed our web-server. Our goal is now to // count how often a particular IP accessed the web-server, per day. This // is, instead of deriving the count of a particular IP from the whole // input, we want to know the number of hits per IP for every day // distinctly (we're not interested in zero hit counts, of course.) // // Actually, this computation is merely a word-count problem explained // in the already mentioned {@link SimpleWordCount}. We just count the // number of occurrences of a particular IP. However, we also specify // how the input is to be "windowed." // // Windowing splits the input into fixed sections of chunks. Such as we // can divide a data set into chunks by a certain size, we can split // a data set into chunks defined by time, e.g. a chunk for day one, // another chunk for day two, etc. provided that elements of the data // set have a notion of time. Once the input data set is logically divided // into these "time windows", the computation takes place separately on // each of them, and, produces a results for each window separately. // // Here, we specify time based windowing using the `Time.of(..)` method // specifying the size of the windows, in particular "one day" in this // example. Then, we also specify how to determine the time of the // elements, such that these are placed into the right windows. // // Note: There are a few different windowing strategies and you can // investigate each by looking for classes implementing {@link Windowing}. // // Note: You might wonder why we didn't just a // "select ip, count(*) from input group by (ip, day)". First, windowing // as such is a separate concern to the actual computation; there is no // need to mix them up and further complicate the actual computation. // Being a separate concern it allows for easier exchange and // experimentation. Second, by specifying windowing as a separate concern, // we can make the computation work even on unbounded, i.e. endless, input // streams. Windowing strategies generally work together with the // executor and can define a point when a window is determined to be // "filled" at which point the windows data can be processed, calculated, // and the corresponding results emitted. This makes endless stream // processing work. Dataset<Pair<String, Long>> aggregated = ReduceByKey.named("AGGREGATE") .of(parsed) .keyBy(LogLine::getIp) .valueBy(line -> 1L) .combineBy(Sums.ofLongs()) .windowBy(Time.of(Duration.ofDays(1)), line -> line.getDate().getTime()) .output(); // At the final stage of our flow, we nicely format the previously emitted // results before persisting them to a given data sink, e.g. external storage. // // The elements emitted from the previous operator specify the windowed // results of the "IP-count". This is, for each IP we get a count of the // number of its occurrences (within a window.) The window information // itself - if desired - can be accessed from the `FlatMap`'s context // parameter as demonstrated below. FlatMap.named("FORMAT-OUTPUT") .of(aggregated) .using(((Pair<String, Long> elem, Context<String> context) -> { Date d = new Date(((TimeInterval) context.getWindow()).getStartMillis()); SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy", Locale.ENGLISH); context.collect(sdf.format(d) + "\t" + elem.getFirst() + "\t" + elem.getSecond()); })) .output() .persist(dataSink); // Finally, we allocate an executor and submit our flow for execution on it. Executor executor = Executors.createExecutor(executorName); executor.submit(flow).get(); } private static class LogParser { private static Pattern pattern = Pattern.compile("^([[0-9a-zA-z-].]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\].*"); public static LogLine parseLine(String line) { Matcher matcher = pattern.matcher(line); if (matcher.matches()) { try { // SDF is not thread-safe, so we need to allocate one here. Ideally, // we'd use `DateTimeFormatter` and re-use it across input elements. // see the corresponding note at the operator utilizing `parseLine`. SimpleDateFormat sdf = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH); String ip = matcher.group(1); Date date = sdf.parse(matcher.group(4)); return new LogLine(ip, date); } catch (Exception e) { throw new IllegalStateException(e); } } throw new IllegalStateException("Invalid log format: " + line); } } private static class LogLine { private final String ip; private final Date date; public LogLine(String ip, Date date) { this.ip = ip; this.date = date; } public String getIp() { return ip; } public Date getDate() { return date; } } }
#119 [euphoria-examples] Rework event time assignment
euphoria-examples/src/main/java/cz/seznam/euphoria/examples/wordcount/AccessLogCount.java
#119 [euphoria-examples] Rework event time assignment
<ide><path>uphoria-examples/src/main/java/cz/seznam/euphoria/examples/wordcount/AccessLogCount.java <ide> import cz.seznam.euphoria.core.client.io.DataSink; <ide> import cz.seznam.euphoria.core.client.io.DataSource; <ide> import cz.seznam.euphoria.core.client.io.StdoutSink; <add>import cz.seznam.euphoria.core.client.operator.AssignEventTime; <ide> import cz.seznam.euphoria.core.client.operator.FlatMap; <ide> import cz.seznam.euphoria.core.client.operator.MapElements; <ide> import cz.seznam.euphoria.core.client.operator.ReduceByKey; <ide> .using(LogParser::parseLine) <ide> .output(); <ide> <add> // Since our log lines represent events which happened at a particular <add> // point in time, we want our system to treat them as such, no matter in <add> // which particular order the lines happen to be in the read input files. <add> // <add> // We do so by applying a so-called event-time-extractor function. As of <add> // this moment, euphoria will treat the element as if it happended in the <add> // corresponding time since it gets to know the timestamp the event occurred. <add> parsed = AssignEventTime.of(parsed) <add> .using(line -> line.getDate().getTime()) <add> .output(); <add> <ide> // In the previous step we derived a data set specifying points in time <ide> // at which particular IPs accessed our web-server. Our goal is now to <ide> // count how often a particular IP accessed the web-server, per day. This <ide> // <ide> // Here, we specify time based windowing using the `Time.of(..)` method <ide> // specifying the size of the windows, in particular "one day" in this <del> // example. Then, we also specify how to determine the time of the <del> // elements, such that these are placed into the right windows. <add> // example. The assignment of an element to a particular time window, <add> // will, by definition, utilize the processed elements assigned timestamp. <add> // This is what we did in the previous step. <ide> // <ide> // Note: There are a few different windowing strategies and you can <ide> // investigate each by looking for classes implementing {@link Windowing}. <ide> .keyBy(LogLine::getIp) <ide> .valueBy(line -> 1L) <ide> .combineBy(Sums.ofLongs()) <del> .windowBy(Time.of(Duration.ofDays(1)), line -> line.getDate().getTime()) <add> .windowBy(Time.of(Duration.ofDays(1))) <ide> .output(); <ide> <ide> // At the final stage of our flow, we nicely format the previously emitted
Java
apache-2.0
d604366f5c26fd957bfb2b549183c2bda37ec962
0
JNOSQL/artemis-extension
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.artemis.graph; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.jnosql.artemis.Converters; import org.jnosql.artemis.EntityNotFoundException; import org.jnosql.artemis.reflection.ClassRepresentation; import org.jnosql.artemis.reflection.ClassRepresentations; import org.jnosql.artemis.reflection.Reflections; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Function; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * A default implementation using DefaultTraversalGraphConverter */ @GraphTraversalSourceOperation class DefaultTraversalGraphConverter extends AbstractGraphConverter implements GraphConverter { @Inject private ClassRepresentations classRepresentations; @Inject private Reflections reflections; @Inject private Converters converters; @Inject private Instance<GraphTraversalSourceSupplier> supplierInstance; @Override protected ClassRepresentations getClassRepresentations() { return classRepresentations; } @Override protected Reflections getReflections() { return reflections; } @Override protected Converters getConverters() { return converters; } @Override protected Graph getGraph() { throw new UnsupportedOperationException("GraphTraversalSource does not support graph instance"); } @Override public <T> Vertex toVertex(T entity) { requireNonNull(entity, "entity is required"); ClassRepresentation representation = getClassRepresentations().get(entity.getClass()); String label = representation.getName(); List<FieldGraph> fields = representation.getFields().stream() .map(f -> to(f, entity)) .filter(FieldGraph::isNotEmpty).collect(toList()); Optional<FieldGraph> id = fields.stream().filter(FieldGraph::isId).findFirst(); final Function<Property, Vertex> findVertexOrCreateWithId = p -> { Iterator<Vertex> vertices = getTraversalSource().V(p.value()); return vertices.hasNext() ? vertices.next() : getTraversalSource().addV(label) .property(org.apache.tinkerpop.gremlin.structure.T.id, p.value()) .next(); }; Vertex vertex = id.map(i -> i.toElement(getConverters())) .map(findVertexOrCreateWithId) .orElseGet(() -> getTraversalSource().addV(label).next()); fields.stream().filter(FieldGraph::isNotId) .flatMap(f -> f.toElements(this, getConverters()).stream()) .forEach(p -> vertex.property(p.key(), p.value())); return vertex; } @Override public Edge toEdge(EdgeEntity edge) { requireNonNull(edge, "vertex is required"); Object id = edge.getId().get(); final Iterator<Edge> edges = getTraversalSource().E(id); if (edges.hasNext()) { return edges.next(); } throw new EntityNotFoundException("Edge does not found in the database with id: " + id); } private GraphTraversalSource getTraversalSource() { return supplierInstance.get().get(); } }
graph-extension/src/main/java/org/jnosql/artemis/graph/DefaultTraversalGraphConverter.java
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.artemis.graph; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.jnosql.artemis.Converters; import org.jnosql.artemis.EntityNotFoundException; import org.jnosql.artemis.reflection.ClassRepresentation; import org.jnosql.artemis.reflection.ClassRepresentations; import org.jnosql.artemis.reflection.Reflections; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Function; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toList; /** * A default implementation using DefaultTraversalGraphConverter */ @GraphTraversalSourceOperation class DefaultTraversalGraphConverter extends AbstractGraphConverter implements GraphConverter { @Inject private ClassRepresentations classRepresentations; @Inject private Reflections reflections; @Inject private Converters converters; @Inject private Instance<GraphTraversalSourceSupplier> instance; @Override protected ClassRepresentations getClassRepresentations() { return classRepresentations; } @Override protected Reflections getReflections() { return reflections; } @Override protected Converters getConverters() { return converters; } @Override protected Graph getGraph() { throw new UnsupportedOperationException("GraphTraversalSource does not support graph instance"); } @Override public <T> Vertex toVertex(T entity) { requireNonNull(entity, "entity is required"); ClassRepresentation representation = getClassRepresentations().get(entity.getClass()); String label = representation.getName(); List<FieldGraph> fields = representation.getFields().stream() .map(f -> to(f, entity)) .filter(FieldGraph::isNotEmpty).collect(toList()); Optional<FieldGraph> id = fields.stream().filter(FieldGraph::isId).findFirst(); final Function<Property, Vertex> findVertexOrCreateWithId = p -> { Iterator<Vertex> vertices = getTraversalSource().V(p.value()); return vertices.hasNext() ? vertices.next() : getTraversalSource().addV(label) .property(org.apache.tinkerpop.gremlin.structure.T.id, p.value()) .next(); }; Vertex vertex = id.map(i -> i.toElement(getConverters())) .map(findVertexOrCreateWithId) .orElseGet(() -> getTraversalSource().addV(label).next()); fields.stream().filter(FieldGraph::isNotId) .flatMap(f -> f.toElements(this, getConverters()).stream()) .forEach(p -> vertex.property(p.key(), p.value())); return vertex; } @Override public Edge toEdge(EdgeEntity edge) { requireNonNull(edge, "vertex is required"); Object id = edge.getId().get(); final Iterator<Edge> edges = getTraversalSource().E(id); if (edges.hasNext()) { return edges.next(); } throw new EntityNotFoundException("Edge does not found in the database with id: " + id); } private GraphTraversalSource getTraversalSource() { return instance.get().get(); } }
renames field
graph-extension/src/main/java/org/jnosql/artemis/graph/DefaultTraversalGraphConverter.java
renames field
<ide><path>raph-extension/src/main/java/org/jnosql/artemis/graph/DefaultTraversalGraphConverter.java <ide> private Converters converters; <ide> <ide> @Inject <del> private Instance<GraphTraversalSourceSupplier> instance; <add> private Instance<GraphTraversalSourceSupplier> supplierInstance; <ide> <ide> <ide> @Override <ide> } <ide> <ide> private GraphTraversalSource getTraversalSource() { <del> return instance.get().get(); <add> return supplierInstance.get().get(); <ide> } <ide> }
Java
apache-2.0
ba109094ccadef3c3edd5e675557b266ff7b2d3c
0
DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,davidyan74/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar,vrozov/apex-malhar,vrozov/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,tweise/apex-malhar,PramodSSImmaneni/apex-malhar,apache/incubator-apex-malhar,vrozov/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,tweise/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,brightchen/apex-malhar,patilvikram/apex-malhar,siyuanh/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,vrozov/apex-malhar,sandeep-n/incubator-apex-malhar,trusli/apex-malhar,PramodSSImmaneni/apex-malhar,DataTorrent/incubator-apex-malhar,trusli/apex-malhar,siyuanh/apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,prasannapramod/apex-malhar,chandnisingh/apex-malhar,yogidevendra/incubator-apex-malhar,apache/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,prasannapramod/apex-malhar,siyuanh/apex-malhar,trusli/apex-malhar,chinmaykolhatkar/apex-malhar,tweise/apex-malhar,prasannapramod/apex-malhar,chandnisingh/apex-malhar,vrozov/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,tweise/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/incubator-apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,siyuanh/apex-malhar,ananthc/apex-malhar,ananthc/apex-malhar,PramodSSImmaneni/apex-malhar,tweise/incubator-apex-malhar,davidyan74/apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,tweise/incubator-apex-malhar,patilvikram/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,vrozov/apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/apex-malhar,siyuanh/incubator-apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,yogidevendra/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,ilganeli/incubator-apex-malhar,ilganeli/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,brightchen/apex-malhar,ilganeli/incubator-apex-malhar,patilvikram/apex-malhar,apache/incubator-apex-malhar,ilganeli/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/apex-malhar,DataTorrent/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,ilganeli/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,patilvikram/apex-malhar,tweise/apex-malhar,yogidevendra/apex-malhar,patilvikram/apex-malhar,chandnisingh/apex-malhar,brightchen/apex-malhar,chinmaykolhatkar/apex-malhar,sandeep-n/incubator-apex-malhar,brightchen/apex-malhar,siyuanh/incubator-apex-malhar,siyuanh/apex-malhar,tushargosavi/incubator-apex-malhar,siyuanh/incubator-apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,brightchen/apex-malhar,vrozov/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,ananthc/apex-malhar,sandeep-n/incubator-apex-malhar,davidyan74/apex-malhar,siyuanh/incubator-apex-malhar,vrozov/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,ananthc/apex-malhar,siyuanh/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,trusli/apex-malhar,PramodSSImmaneni/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,davidyan74/apex-malhar,yogidevendra/apex-malhar,chandnisingh/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,trusli/apex-malhar,ananthc/apex-malhar,chinmaykolhatkar/apex-malhar,tweise/apex-malhar,siyuanh/incubator-apex-malhar,ilganeli/incubator-apex-malhar,yogidevendra/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,chandnisingh/apex-malhar,apache/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,brightchen/apex-malhar,tweise/incubator-apex-malhar,prasannapramod/apex-malhar,vrozov/incubator-apex-malhar,siyuanh/apex-malhar,ananthc/apex-malhar
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.lib.db.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import javax.validation.constraints.NotNull; import org.codehaus.jackson.annotate.JsonIgnore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.datatorrent.lib.db.Connectable; import com.datatorrent.netlet.util.DTThrowable; /** * A {@link Connectable} that uses jdbc to connect to stores. * * @since 0.9.4 */ public class JdbcStore implements Connectable { protected static final Logger logger = LoggerFactory.getLogger(JdbcStore.class); @NotNull private String databaseUrl; @NotNull private String databaseDriver; private Properties connectionProperties; protected transient Connection connection = null; /* * Connection URL used to connect to the specific database. */ @NotNull public String getDatabaseUrl() { return databaseUrl; } /* * Connection URL used to connect to the specific database. */ public void setDatabaseUrl(@NotNull String databaseUrl) { this.databaseUrl = databaseUrl; } /* * Driver used to connect to the specific database. */ @NotNull public String getDatabaseDriver() { return databaseDriver; } /* * Driver used to connect to the specific database. */ public void setDatabaseDriver(@NotNull String databaseDriver) { this.databaseDriver = databaseDriver; } public JdbcStore() { connectionProperties = new Properties(); } public Connection getConnection() { return connection; } /** * Sets the user name. * * @param userName user name * @deprecated use {@link #setConnectionProperties(String)} instead. */ public void setUserName(String userName) { connectionProperties.put("user", userName); } /** * Sets the password. * * @param password password * @deprecated use {@link #setConnectionProperties(String)} instead. */ public void setPassword(String password) { connectionProperties.put("password", password); } /** * Sets the connection properties on JDBC connection. Connection properties are provided as a string. * * @param connectionProps Comma separated list of properties. Property key and value are separated by colon. * eg. user:xyz,password:ijk */ public void setConnectionProperties(String connectionProps) { String[] properties = Iterables.toArray(Splitter.on(CharMatcher.anyOf(":,")).omitEmptyStrings().trimResults() .split(connectionProps), String.class); for (int i = 0; i < properties.length; i += 2) { if (i + 1 < properties.length) { connectionProperties.put(properties[i], properties[i + 1]); } } } /** * Sets the connection properties on JDBC connection. * * @param connectionProperties connection properties. */ public void setConnectionProperties(Properties connectionProperties) { this.connectionProperties = connectionProperties; } /** * Get the connection properties of JDBC connection. */ public Properties getConnectionProperties() { return connectionProperties; } /** * Create connection with database using JDBC. */ @Override public void connect() { try { // This will load the JDBC driver, each DB has its own driver Class.forName(databaseDriver).newInstance(); connection = DriverManager.getConnection(databaseUrl, connectionProperties); logger.debug("JDBC connection Success"); } catch (Throwable t) { DTThrowable.rethrow(t); } } /** * Close JDBC connection. */ @Override public void disconnect() { try { connection.close(); } catch (SQLException ex) { throw new RuntimeException("closing database resource", ex); } } @Override @JsonIgnore public boolean isConnected() { try { return !connection.isClosed(); } catch (SQLException e) { throw new RuntimeException("is isConnected", e); } } }
library/src/main/java/com/datatorrent/lib/db/jdbc/JdbcStore.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.lib.db.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.datatorrent.lib.db.Connectable; import com.datatorrent.netlet.util.DTThrowable; /** * A {@link Connectable} that uses jdbc to connect to stores. * * @since 0.9.4 */ public class JdbcStore implements Connectable { protected static final Logger logger = LoggerFactory.getLogger(JdbcStore.class); @NotNull private String databaseUrl; @NotNull private String databaseDriver; private Properties connectionProperties; protected transient Connection connection = null; /* * Connection URL used to connect to the specific database. */ @NotNull public String getDatabaseUrl() { return databaseUrl; } /* * Connection URL used to connect to the specific database. */ public void setDatabaseUrl(@NotNull String databaseUrl) { this.databaseUrl = databaseUrl; } /* * Driver used to connect to the specific database. */ @NotNull public String getDatabaseDriver() { return databaseDriver; } /* * Driver used to connect to the specific database. */ public void setDatabaseDriver(@NotNull String databaseDriver) { this.databaseDriver = databaseDriver; } public JdbcStore() { connectionProperties = new Properties(); } public Connection getConnection() { return connection; } /** * Sets the user name. * * @param userName user name * @deprecated use {@link #setConnectionProperties(String)} instead. */ public void setUserName(String userName) { connectionProperties.put("user", userName); } /** * Sets the password. * * @param password password * @deprecated use {@link #setConnectionProperties(String)} instead. */ public void setPassword(String password) { connectionProperties.put("password", password); } /** * Sets the connection properties on JDBC connection. Connection properties are provided as a string. * * @param connectionProps Comma separated list of properties. Property key and value are separated by colon. * eg. user:xyz,password:ijk */ public void setConnectionProperties(String connectionProps) { String[] properties = Iterables.toArray(Splitter.on(CharMatcher.anyOf(":,")).omitEmptyStrings().trimResults() .split(connectionProps), String.class); for (int i = 0; i < properties.length; i += 2) { if (i + 1 < properties.length) { connectionProperties.put(properties[i], properties[i + 1]); } } } /** * Sets the connection properties on JDBC connection. * * @param connectionProperties connection properties. */ public void setConnectionProperties(Properties connectionProperties) { this.connectionProperties = connectionProperties; } /** * Get the connection properties of JDBC connection. */ public Properties getConnectionProperties() { return connectionProperties; } /** * Create connection with database using JDBC. */ @Override public void connect() { try { // This will load the JDBC driver, each DB has its own driver Class.forName(databaseDriver).newInstance(); connection = DriverManager.getConnection(databaseUrl, connectionProperties); logger.debug("JDBC connection Success"); } catch (Throwable t) { DTThrowable.rethrow(t); } } /** * Close JDBC connection. */ @Override public void disconnect() { try { connection.close(); } catch (SQLException ex) { throw new RuntimeException("closing database resource", ex); } } @Override public boolean isConnected() { try { return !connection.isClosed(); } catch (SQLException e) { throw new RuntimeException("is isConnected", e); } } }
APEXMALHAR-2088: Fixed JsonMappingException for operators using JDBCStore
library/src/main/java/com/datatorrent/lib/db/jdbc/JdbcStore.java
APEXMALHAR-2088: Fixed JsonMappingException for operators using JDBCStore
<ide><path>ibrary/src/main/java/com/datatorrent/lib/db/jdbc/JdbcStore.java <ide> <ide> import javax.validation.constraints.NotNull; <ide> <add>import org.codehaus.jackson.annotate.JsonIgnore; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <ide> } <ide> <ide> @Override <add> @JsonIgnore <ide> public boolean isConnected() <ide> { <ide> try {
Java
lgpl-2.1
7dccce81c584ed779a96520b4246919f5ebc858c
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id: DirtyItemList.java,v 1.15 2002/09/26 23:35:10 mdb Exp $ package com.threerings.miso.scene; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.util.ArrayList; import java.util.Comparator; import com.samskivert.util.SortableArrayList; import com.samskivert.util.StringUtil; import com.threerings.media.Log; import com.threerings.media.sprite.Sprite; import com.threerings.media.tile.ObjectTile; import com.threerings.miso.scene.util.IsoUtil; /** * The dirty item list keeps track of dirty sprites and object tiles * in a scene. */ public class DirtyItemList { /** * Appends the dirty sprite at the given coordinates to the dirty item * list. * * @param sprite the dirty sprite itself. * @param tx the sprite's x tile position. * @param ty the sprite's y tile position. */ public void appendDirtySprite (Sprite sprite, int tx, int ty) { DirtyItem item = getDirtyItem(); item.init(sprite, null, null, tx, ty); _items.add(item); } /** * Appends the dirty object tile at the given coordinates to the dirty * item list. * * @param scene the scene object that is dirty. * @param footprint the footprint of the object tile if it should be * rendered, null otherwise. */ public void appendDirtyObject (SceneObject scobj, Shape footprint) { DirtyItem item = getDirtyItem(); item.init(scobj, scobj.bounds, footprint, scobj.x, scobj.y); _items.add(item); } /** * Returns the dirty item at the given index in the list. */ public DirtyItem get (int idx) { return (DirtyItem)_items.get(idx); } /** * Returns an array of the {@link DirtyItem} objects in the list * sorted in proper rendering order. */ public void sort () { int size = size(); if (DEBUG_SORT) { Log.info("Sorting dirty item list [size=" + size + "]."); } // if we've only got one item, we need to do no sorting if (size > 1) { // get items sorted by increasing origin x-coordinate _xitems.addAll(_items); _xitems.sort(ORIGIN_X_COMP); if (DEBUG_SORT) { Log.info("Sorted by x-origin " + "[items=" + toString(_xitems) + "]."); } // get items sorted by increasing origin y-coordinate _yitems.addAll(_items); _yitems.sort(ORIGIN_Y_COMP); if (DEBUG_SORT) { Log.info("Sorted by y-origin " + "[items=" + toString(_yitems) + "]."); } // sort items into proper render order _items.sort(_rcomp); // clear out our temporary arrays _xitems.clear(); _yitems.clear(); } if (DEBUG_SORT) { Log.info("Sorted for render [items=" + toString(_items) + "]."); } } /** * Paints all the dirty items in this list using the supplied graphics * context. The items are removed from the dirty list after being * painted and the dirty list ends up empty. */ public void paintAndClear (Graphics2D gfx) { int icount = _items.size(); for (int ii = 0; ii < icount; ii++) { DirtyItem item = (DirtyItem)_items.get(ii); item.paint(gfx); item.clear(); _freelist.add(item); } _items.clear(); } /** * Clears out any items that were in this list. */ public void clear () { for (int icount = _items.size(); icount > 0; icount--) { DirtyItem item = (DirtyItem)_items.remove(0); item.clear(); _freelist.add(item); } } /** * Returns the number of items in the dirty item list. */ public int size () { return _items.size(); } /** * Obtains a new dirty item instance, reusing an old one if possible * or creating a new one otherwise. */ protected DirtyItem getDirtyItem () { if (_freelist.size() > 0) { return (DirtyItem)_freelist.remove(0); } else { return new DirtyItem(); } } /** * Returns an abbreviated string representation of the two given dirty * items describing each by only its origin coordinates. Intended for * debugging purposes. */ protected static String toString (DirtyItem a, DirtyItem b) { StringBuffer buf = new StringBuffer(); buf.append("[(ox=").append(a.ox); buf.append(", oy=").append(a.oy).append("), "); buf.append("(ox=").append(b.ox); buf.append(", oy=").append(b.oy).append(")"); return buf.append("]").toString(); } /** * Returns an abbreviated string representation of the given dirty * items describing each by only its origin coordinates. Intended for * debugging purposes. */ protected static String toString (SortableArrayList items) { StringBuffer buf = new StringBuffer(); buf.append("["); for (int ii = 0; ii < items.size(); ii++) { DirtyItem item = (DirtyItem)items.get(ii); buf.append("(ox=").append(item.ox); buf.append(", oy=").append(item.oy).append(")"); if (ii < (items.size() - 1)) { buf.append(", "); } } return buf.append("]").toString(); } /** * A class to hold the items inserted in the dirty list along with * all of the information necessary to render their dirty regions * to the target graphics context when the time comes to do so. */ public static class DirtyItem { /** The dirtied object; one of either a sprite or an object tile. */ public Object obj; /** The bounds of the dirty item if it's an object tile. */ public Rectangle bounds; /** The footprint of the dirty item if it's an object tile and * we're drawing footprints. */ public Shape footprint; /** The origin tile coordinates. */ public int ox, oy; /** The leftmost tile coordinates. */ public int lx, ly; /** The rightmost tile coordinates. */ public int rx, ry; /** * Initializes a dirty item. */ public void init (Object obj, Rectangle bounds, Shape footprint, int x, int y) { this.obj = obj; this.bounds = bounds; this.footprint = footprint; this.ox = x; this.oy = y; // calculate the item's leftmost and rightmost tiles; note // that sprites occupy only a single tile, so leftmost and // rightmost tiles are equivalent lx = rx = ox; ly = ry = oy; if (obj instanceof SceneObject) { ObjectTile tile = ((SceneObject)obj).tile; lx -= (tile.getBaseWidth() - 1); ry -= (tile.getBaseHeight() - 1); } } /** * Paints the dirty item to the given graphics context. Only * the portion of the item that falls within the given dirty * rectangle is actually drawn. */ public void paint (Graphics2D gfx) { // if there's a footprint, paint that if (footprint != null) { gfx.setColor(Color.black); gfx.draw(footprint); } // paint the item if (obj instanceof Sprite) { ((Sprite)obj).paint(gfx); } else { ((SceneObject)obj).tile.paint(gfx, bounds.x, bounds.y); } } /** * Releases all references held by this dirty item so that it * doesn't inadvertently hold on to any objects while waiting to * be reused. */ public void clear () { obj = null; bounds = null; } // documentation inherited public boolean equals (Object other) { // we're never equal to something that's not our kind if (!(other instanceof DirtyItem)) { return false; } // sprites are equivalent if they're the same sprite DirtyItem b = (DirtyItem)other; return obj.equals(b.obj); // if ((obj instanceof Sprite) && (b.obj instanceof Sprite)) { // return (obj == b.obj); // } // // objects are equivalent if they are the same object // if ((obj instanceof SceneObject) && (b.obj instanceof SceneObject)) { // return (obj == b.obj); // } // // object-to-sprite are distinguished simply by origin tile // // coordinate since they can never occupy the same tile // return (ox == b.ox && oy == b.oy); } /** * Returns a string representation of the dirty item. */ public String toString () { StringBuffer buf = new StringBuffer(); buf.append("[obj=").append(obj); buf.append(", ox=").append(ox); buf.append(", oy=").append(oy); buf.append(", lx=").append(lx); buf.append(", ly=").append(ly); buf.append(", rx=").append(rx); buf.append(", ry=").append(ry); return buf.append("]").toString(); } } /** * A comparator class for use in sorting dirty items in ascending * origin x- or y-axis coordinate order. */ protected static class OriginComparator implements Comparator { /** * Constructs an origin comparator that sorts dirty items in * ascending order based on their origin coordinate on the given * axis. */ public OriginComparator (int axis) { _axis = axis; } // documentation inherited public int compare (Object a, Object b) { DirtyItem da = (DirtyItem)a; DirtyItem db = (DirtyItem)b; return (_axis == X_AXIS) ? (da.ox - db.ox) : (da.oy - db.oy); } // documentation inherited public boolean equals (Object obj) { return (obj == this); } /** The axis this comparator sorts on. */ protected int _axis; } /** * A comparator class for use in sorting the dirty sprites and * objects in a scene in ascending x- and y-coordinate order * suitable for rendering in the isometric view with proper visual * results. */ protected class RenderComparator implements Comparator { // documentation inherited public int compare (Object a, Object b) { DirtyItem da = (DirtyItem)a; DirtyItem db = (DirtyItem)b; // check for partitioning objects on the y-axis int result = comparePartitioned(Y_AXIS, da, db); if (result != 0) { if (DEBUG_COMPARE) { String items = DirtyItemList.toString(da, db); Log.info("compare: Y-partitioned " + "[result=" + result + ", items=" + items + "]."); } return result; } // check for partitioning objects on the x-axis result = comparePartitioned(X_AXIS, da, db); if (result != 0) { if (DEBUG_COMPARE) { String items = DirtyItemList.toString(da, db); Log.info("compare: X-partitioned " + "[result=" + result + ", items=" + items + "]."); } return result; } // use normal iso-ordering check result = compareNonPartitioned(da, db); if (DEBUG_COMPARE) { String items = DirtyItemList.toString(da, db); Log.info("compare: non-partitioned " + "[result=" + result + ", items=" + items + "]."); } return result; } // documentation inherited public boolean equals (Object obj) { return (obj == this); } /** * Returns whether two dirty items have a partitioning object * between them on the given axis. */ protected int comparePartitioned ( int axis, DirtyItem da, DirtyItem db) { // prepare for the partitioning check SortableArrayList sitems; Comparator comp; boolean swapped = false; switch (axis) { case X_AXIS: if (da.ox == db.ox) { // can't be partitioned if there's no space between return 0; } // order items for proper comparison if (da.ox > db.ox) { DirtyItem temp = da; da = db; db = temp; swapped = true; } // use the axis-specific sorted array sitems = _xitems; comp = ORIGIN_X_COMP; break; case Y_AXIS: default: if (da.oy == db.oy) { // can't be partitioned if there's no space between return 0; } // order items for proper comparison if (da.oy > db.oy) { DirtyItem temp = da; da = db; db = temp; swapped = true; } // use the axis-specific sorted array sitems = _yitems; comp = ORIGIN_Y_COMP; break; } // get the bounding item indices and the number of // potentially-partitioning dirty items int aidx = sitems.binarySearch(da, comp); int bidx = sitems.binarySearch(db, comp); int size = bidx - aidx - 1; // check each potentially partitioning item int startidx = aidx + 1, endidx = startidx + size; for (int pidx = startidx; pidx < endidx; pidx++) { DirtyItem dp = (DirtyItem)sitems.get(pidx); if (dp.obj instanceof Sprite) { // sprites can't partition things continue; } else if ((dp.obj == da.obj) || (dp.obj == db.obj)) { // can't be partitioned by ourselves continue; } // perform the actual partition check for this object switch (axis) { case X_AXIS: if (dp.ly >= da.ry && dp.ry <= db.ly && dp.lx > da.rx && dp.rx < db.lx) { return (swapped) ? 1 : -1; } case Y_AXIS: default: if (dp.lx <= db.ox && dp.rx >= da.lx && dp.ry > da.oy && dp.oy < db.ry) { return (swapped) ? 1 : -1; } } } // no partitioning object found return 0; } /** * Compares the two dirty items assuming there are no partitioning * objects between them. */ protected int compareNonPartitioned (DirtyItem da, DirtyItem db) { if (da.ox == db.ox && da.oy == db.oy) { if (da.equals(db)) { // render level is equal if we're the same sprite // or an object at the same location return 0; } if ((da.obj instanceof Sprite) && (db.obj instanceof Sprite)) { Sprite as = (Sprite)da.obj, bs = (Sprite)db.obj; // we're comparing two sprites co-existing on the same // tile, first check their render order int rocomp = as.getRenderOrder() - bs.getRenderOrder(); if (rocomp != 0) { return rocomp; } // next sort them by y-position int ydiff = as.getY() - bs.getY(); if (ydiff != 0) { return ydiff; } // if they're at the same height, just use hashCode() // to establish a consistent arbitrary ordering return (as.hashCode() - bs.hashCode()); } } // if the two objects are scene objects and they overlap, we // compare them solely based on their human assigned render // priority scene; this allows us to avoid all sorts of sticky // business wherein the render order between two overlapping // objects cannot be determined without a z-buffer if ((da.obj instanceof SceneObject) && (db.obj instanceof SceneObject)) { SceneObject soa = (SceneObject)da.obj; SceneObject sob = (SceneObject)db.obj; if (IsoUtil.objectFootprintsOverlap(soa, sob)) { return (soa.priority - sob.priority); } } // otherwise use a consistent ordering for non-overlappers; // see narya/docs/miso/render_sort_diagram.png for more info if (da.lx > db.ox) { return 1; } else if (da.ry > db.oy) { return (db.lx > da.ox) ? -1 : 1; } return -1; } } /** Whether to log debug info when comparing pairs of dirty items. */ protected static final boolean DEBUG_COMPARE = false; /** Whether to log debug info for the main dirty item sorting algorithm. */ protected static final boolean DEBUG_SORT = false; /** Constants used to denote axis sorting constraints. */ protected static final int X_AXIS = 0; protected static final int Y_AXIS = 1; /** The comparator used to sort dirty items in ascending origin * x-coordinate order. */ protected static final Comparator ORIGIN_X_COMP = new OriginComparator(X_AXIS); /** The comparator used to sort dirty items in ascending origin * y-coordinate order. */ protected static final Comparator ORIGIN_Y_COMP = new OriginComparator(Y_AXIS); /** The list of dirty items. */ protected SortableArrayList _items = new SortableArrayList(); /** The list of dirty items sorted by x-position. */ protected SortableArrayList _xitems = new SortableArrayList(); /** The list of dirty items sorted by y-position. */ protected SortableArrayList _yitems = new SortableArrayList(); /** The render comparator we'll use for our final, magical sort. */ protected Comparator _rcomp = new RenderComparator(); /** Unused dirty items. */ protected ArrayList _freelist = new ArrayList(); }
src/java/com/threerings/miso/client/DirtyItemList.java
// // $Id: DirtyItemList.java,v 1.14 2002/09/23 23:07:11 mdb Exp $ package com.threerings.miso.scene; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.util.ArrayList; import java.util.Comparator; import com.samskivert.util.SortableArrayList; import com.samskivert.util.StringUtil; import com.threerings.media.Log; import com.threerings.media.sprite.Sprite; import com.threerings.media.tile.ObjectTile; import com.threerings.miso.scene.util.IsoUtil; /** * The dirty item list keeps track of dirty sprites and object tiles * in a scene. */ public class DirtyItemList { /** * Appends the dirty sprite at the given coordinates to the dirty item * list. * * @param sprite the dirty sprite itself. * @param tx the sprite's x tile position. * @param ty the sprite's y tile position. */ public void appendDirtySprite (Sprite sprite, int tx, int ty) { DirtyItem item = getDirtyItem(); item.init(sprite, null, null, tx, ty); _items.add(item); } /** * Appends the dirty object tile at the given coordinates to the dirty * item list. * * @param scene the scene object that is dirty. * @param footprint the footprint of the object tile if it should be * rendered, null otherwise. */ public void appendDirtyObject (SceneObject scobj, Shape footprint) { DirtyItem item = getDirtyItem(); item.init(scobj, scobj.bounds, footprint, scobj.x, scobj.y); _items.add(item); } /** * Returns the dirty item at the given index in the list. */ public DirtyItem get (int idx) { return (DirtyItem)_items.get(idx); } /** * Returns an array of the {@link DirtyItem} objects in the list * sorted in proper rendering order. */ public void sort () { int size = size(); if (DEBUG_SORT) { Log.info("Sorting dirty item list [size=" + size + "]."); } // if we've only got one item, we need to do no sorting if (size > 1) { // get items sorted by increasing origin x-coordinate _xitems.addAll(_items); _xitems.sort(ORIGIN_X_COMP); if (DEBUG_SORT) { Log.info("Sorted by x-origin " + "[items=" + toString(_xitems) + "]."); } // get items sorted by increasing origin y-coordinate _yitems.addAll(_items); _yitems.sort(ORIGIN_Y_COMP); if (DEBUG_SORT) { Log.info("Sorted by y-origin " + "[items=" + toString(_yitems) + "]."); } // sort items into proper render order _items.sort(_rcomp); // clear out our temporary arrays _xitems.clear(); _yitems.clear(); } if (DEBUG_SORT) { Log.info("Sorted for render [items=" + toString(_items) + "]."); } } /** * Paints all the dirty items in this list using the supplied graphics * context. The items are removed from the dirty list after being * painted and the dirty list ends up empty. */ public void paintAndClear (Graphics2D gfx) { int icount = _items.size(); for (int ii = 0; ii < icount; ii++) { DirtyItem item = (DirtyItem)_items.get(ii); item.paint(gfx); item.clear(); _freelist.add(item); } _items.clear(); } /** * Clears out any items that were in this list. */ public void clear () { for (int icount = _items.size(); icount > 0; icount--) { DirtyItem item = (DirtyItem)_items.remove(0); item.clear(); _freelist.add(item); } } /** * Returns the number of items in the dirty item list. */ public int size () { return _items.size(); } /** * Obtains a new dirty item instance, reusing an old one if possible * or creating a new one otherwise. */ protected DirtyItem getDirtyItem () { if (_freelist.size() > 0) { return (DirtyItem)_freelist.remove(0); } else { return new DirtyItem(); } } /** * Returns an abbreviated string representation of the two given dirty * items describing each by only its origin coordinates. Intended for * debugging purposes. */ protected static String toString (DirtyItem a, DirtyItem b) { StringBuffer buf = new StringBuffer(); buf.append("[(ox=").append(a.ox); buf.append(", oy=").append(a.oy).append("), "); buf.append("(ox=").append(b.ox); buf.append(", oy=").append(b.oy).append(")"); return buf.append("]").toString(); } /** * Returns an abbreviated string representation of the given dirty * items describing each by only its origin coordinates. Intended for * debugging purposes. */ protected static String toString (SortableArrayList items) { StringBuffer buf = new StringBuffer(); buf.append("["); for (int ii = 0; ii < items.size(); ii++) { DirtyItem item = (DirtyItem)items.get(ii); buf.append("(ox=").append(item.ox); buf.append(", oy=").append(item.oy).append(")"); if (ii < (items.size() - 1)) { buf.append(", "); } } return buf.append("]").toString(); } /** * A class to hold the items inserted in the dirty list along with * all of the information necessary to render their dirty regions * to the target graphics context when the time comes to do so. */ public static class DirtyItem { /** The dirtied object; one of either a sprite or an object tile. */ public Object obj; /** The bounds of the dirty item if it's an object tile. */ public Rectangle bounds; /** The footprint of the dirty item if it's an object tile and * we're drawing footprints. */ public Shape footprint; /** The origin tile coordinates. */ public int ox, oy; /** The leftmost tile coordinates. */ public int lx, ly; /** The rightmost tile coordinates. */ public int rx, ry; /** * Initializes a dirty item. */ public void init (Object obj, Rectangle bounds, Shape footprint, int x, int y) { this.obj = obj; this.bounds = bounds; this.footprint = footprint; this.ox = x; this.oy = y; // calculate the item's leftmost and rightmost tiles; note // that sprites occupy only a single tile, so leftmost and // rightmost tiles are equivalent lx = rx = ox; ly = ry = oy; if (obj instanceof SceneObject) { ObjectTile tile = ((SceneObject)obj).tile; lx -= (tile.getBaseWidth() - 1); ry -= (tile.getBaseHeight() - 1); } } /** * Paints the dirty item to the given graphics context. Only * the portion of the item that falls within the given dirty * rectangle is actually drawn. */ public void paint (Graphics2D gfx) { // if there's a footprint, paint that if (footprint != null) { gfx.setColor(Color.black); gfx.draw(footprint); } // paint the item if (obj instanceof Sprite) { ((Sprite)obj).paint(gfx); } else { ((SceneObject)obj).tile.paint(gfx, bounds.x, bounds.y); } } /** * Releases all references held by this dirty item so that it * doesn't inadvertently hold on to any objects while waiting to * be reused. */ public void clear () { obj = null; bounds = null; } // documentation inherited public boolean equals (Object other) { // we're never equal to something that's not our kind if (!(other instanceof DirtyItem)) { return false; } // sprites are equivalent if they're the same sprite DirtyItem b = (DirtyItem)other; return obj.equals(b.obj); // if ((obj instanceof Sprite) && (b.obj instanceof Sprite)) { // return (obj == b.obj); // } // // objects are equivalent if they are the same object // if ((obj instanceof SceneObject) && (b.obj instanceof SceneObject)) { // return (obj == b.obj); // } // // object-to-sprite are distinguished simply by origin tile // // coordinate since they can never occupy the same tile // return (ox == b.ox && oy == b.oy); } /** * Returns a string representation of the dirty item. */ public String toString () { StringBuffer buf = new StringBuffer(); buf.append("[obj=").append(obj); buf.append(", ox=").append(ox); buf.append(", oy=").append(oy); buf.append(", lx=").append(lx); buf.append(", ly=").append(ly); buf.append(", rx=").append(rx); buf.append(", ry=").append(ry); return buf.append("]").toString(); } } /** * A comparator class for use in sorting dirty items in ascending * origin x- or y-axis coordinate order. */ protected static class OriginComparator implements Comparator { /** * Constructs an origin comparator that sorts dirty items in * ascending order based on their origin coordinate on the given * axis. */ public OriginComparator (int axis) { _axis = axis; } // documentation inherited public int compare (Object a, Object b) { DirtyItem da = (DirtyItem)a; DirtyItem db = (DirtyItem)b; return (_axis == X_AXIS) ? (da.ox - db.ox) : (da.oy - db.oy); } // documentation inherited public boolean equals (Object obj) { return (obj == this); } /** The axis this comparator sorts on. */ protected int _axis; } /** * A comparator class for use in sorting the dirty sprites and * objects in a scene in ascending x- and y-coordinate order * suitable for rendering in the isometric view with proper visual * results. */ protected class RenderComparator implements Comparator { // documentation inherited public int compare (Object a, Object b) { DirtyItem da = (DirtyItem)a; DirtyItem db = (DirtyItem)b; // check for partitioning objects on the y-axis int result = comparePartitioned(Y_AXIS, da, db); if (result != 0) { if (DEBUG_COMPARE) { String items = DirtyItemList.toString(da, db); Log.info("compare: Y-partitioned " + "[result=" + result + ", items=" + items + "]."); } return result; } // check for partitioning objects on the x-axis result = comparePartitioned(X_AXIS, da, db); if (result != 0) { if (DEBUG_COMPARE) { String items = DirtyItemList.toString(da, db); Log.info("compare: X-partitioned " + "[result=" + result + ", items=" + items + "]."); } return result; } // use normal iso-ordering check result = compareNonPartitioned(da, db); if (DEBUG_COMPARE) { String items = DirtyItemList.toString(da, db); Log.info("compare: non-partitioned " + "[result=" + result + ", items=" + items + "]."); } return result; } // documentation inherited public boolean equals (Object obj) { return (obj == this); } /** * Returns whether two dirty items have a partitioning object * between them on the given axis. */ protected int comparePartitioned ( int axis, DirtyItem da, DirtyItem db) { // prepare for the partitioning check SortableArrayList sitems; Comparator comp; boolean swapped = false; switch (axis) { case X_AXIS: if (da.ox == db.ox) { // can't be partitioned if there's no space between return 0; } // order items for proper comparison if (da.ox > db.ox) { DirtyItem temp = da; da = db; db = temp; swapped = true; } // use the axis-specific sorted array sitems = _xitems; comp = ORIGIN_X_COMP; break; case Y_AXIS: default: if (da.oy == db.oy) { // can't be partitioned if there's no space between return 0; } // order items for proper comparison if (da.oy > db.oy) { DirtyItem temp = da; da = db; db = temp; swapped = true; } // use the axis-specific sorted array sitems = _yitems; comp = ORIGIN_Y_COMP; break; } // get the bounding item indices and the number of // potentially-partitioning dirty items int aidx = sitems.binarySearch(da, comp); int bidx = sitems.binarySearch(db, comp); int size = bidx - aidx - 1; // check each potentially partitioning item int startidx = aidx + 1, endidx = startidx + size; for (int pidx = startidx; pidx < endidx; pidx++) { DirtyItem dp = (DirtyItem)sitems.get(pidx); if (dp.obj instanceof Sprite) { // sprites can't partition things continue; } else if ((dp.obj == da.obj) || (dp.obj == db.obj)) { // can't be partitioned by ourselves continue; } // perform the actual partition check for this object switch (axis) { case X_AXIS: if (dp.ly >= da.ry && dp.ry <= db.ly && dp.lx > da.rx && dp.rx < db.lx) { return (swapped) ? 1 : -1; } case Y_AXIS: default: if (dp.lx <= db.ox && dp.rx >= da.lx && dp.ry > da.oy && dp.oy < db.ry) { return (swapped) ? 1 : -1; } } } // no partitioning object found return 0; } /** * Compares the two dirty items assuming there are no partitioning * objects between them. */ protected int compareNonPartitioned (DirtyItem da, DirtyItem db) { if (da.ox == db.ox && da.oy == db.oy) { if (da.equals(db)) { // render level is equal if we're the same sprite // or an object at the same location return 0; } if ((da.obj instanceof Sprite) && (db.obj instanceof Sprite)) { // we're comparing two sprites co-existing on the same // tile, so simply sort them by y-position Sprite as = (Sprite)da.obj, bs = (Sprite)db.obj; int diff = as.getY() - bs.getY(); // if they're at the same height, just use hashCode() // to establish a consistent arbitrary ordering return (diff != 0) ? diff : (as.hashCode() - bs.hashCode()); } } // if the two objects are scene objects and they overlap, we // compare them solely based on their human assigned render // priority scene; this allows us to avoid all sorts of sticky // business wherein the render order between two overlapping // objects cannot be determined without a z-buffer if ((da.obj instanceof SceneObject) && (db.obj instanceof SceneObject)) { SceneObject soa = (SceneObject)da.obj; SceneObject sob = (SceneObject)db.obj; if (IsoUtil.objectFootprintsOverlap(soa, sob)) { return (soa.priority - sob.priority); } } // otherwise use a consistent ordering for non-overlappers; // see narya/docs/miso/render_sort_diagram.png for more info if (da.lx > db.ox) { return 1; } else if (da.ry > db.oy) { return (db.lx > da.ox) ? -1 : 1; } return -1; } } /** Whether to log debug info when comparing pairs of dirty items. */ protected static final boolean DEBUG_COMPARE = false; /** Whether to log debug info for the main dirty item sorting algorithm. */ protected static final boolean DEBUG_SORT = false; /** Constants used to denote axis sorting constraints. */ protected static final int X_AXIS = 0; protected static final int Y_AXIS = 1; /** The comparator used to sort dirty items in ascending origin * x-coordinate order. */ protected static final Comparator ORIGIN_X_COMP = new OriginComparator(X_AXIS); /** The comparator used to sort dirty items in ascending origin * y-coordinate order. */ protected static final Comparator ORIGIN_Y_COMP = new OriginComparator(Y_AXIS); /** The list of dirty items. */ protected SortableArrayList _items = new SortableArrayList(); /** The list of dirty items sorted by x-position. */ protected SortableArrayList _xitems = new SortableArrayList(); /** The list of dirty items sorted by y-position. */ protected SortableArrayList _yitems = new SortableArrayList(); /** The render comparator we'll use for our final, magical sort. */ protected Comparator _rcomp = new RenderComparator(); /** Unused dirty items. */ protected ArrayList _freelist = new ArrayList(); }
Account for sprite render priority when sorting sprites. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1758 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/miso/client/DirtyItemList.java
Account for sprite render priority when sorting sprites.
<ide><path>rc/java/com/threerings/miso/client/DirtyItemList.java <ide> // <del>// $Id: DirtyItemList.java,v 1.14 2002/09/23 23:07:11 mdb Exp $ <add>// $Id: DirtyItemList.java,v 1.15 2002/09/26 23:35:10 mdb Exp $ <ide> <ide> package com.threerings.miso.scene; <ide> <ide> } <ide> <ide> if ((da.obj instanceof Sprite) && (db.obj instanceof Sprite)) { <add> Sprite as = (Sprite)da.obj, bs = (Sprite)db.obj; <ide> // we're comparing two sprites co-existing on the same <del> // tile, so simply sort them by y-position <del> Sprite as = (Sprite)da.obj, bs = (Sprite)db.obj; <del> int diff = as.getY() - bs.getY(); <add> // tile, first check their render order <add> int rocomp = as.getRenderOrder() - bs.getRenderOrder(); <add> if (rocomp != 0) { <add> return rocomp; <add> } <add> // next sort them by y-position <add> int ydiff = as.getY() - bs.getY(); <add> if (ydiff != 0) { <add> return ydiff; <add> } <ide> // if they're at the same height, just use hashCode() <ide> // to establish a consistent arbitrary ordering <del> return (diff != 0) ? diff : <del> (as.hashCode() - bs.hashCode()); <add> return (as.hashCode() - bs.hashCode()); <ide> } <ide> } <ide>
Java
apache-2.0
acfdb8421ab04346dd10e8fd7d989aa554b2d065
0
mpouttuclarke/cdap,chtyim/cdap,chtyim/cdap,anthcp/cdap,hsaputra/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,anthcp/cdap,hsaputra/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,caskdata/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,mpouttuclarke/cdap,chtyim/cdap,anthcp/cdap,caskdata/cdap
/* * Copyright 2012-2013 Continuuity,Inc. All Rights Reserved. */ package com.continuuity.internal.app.deploy; import com.continuuity.api.app.Application; import com.continuuity.api.app.ApplicationContext; import com.continuuity.app.ApplicationSpecification; import com.continuuity.app.DefaultAppConfigurer; import com.continuuity.app.Id; import com.continuuity.app.deploy.ConfigResponse; import com.continuuity.app.deploy.Configurator; import com.continuuity.app.program.Archive; import com.continuuity.app.program.ManifestFields; import com.continuuity.common.lang.jar.BundleJarUtil; import com.continuuity.common.utils.DirUtils; import com.continuuity.internal.app.ApplicationSpecificationAdapter; import com.continuuity.internal.app.Specifications; import com.continuuity.internal.io.ReflectionSchemaGenerator; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.io.CharStreams; import com.google.common.io.Files; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.apache.twill.filesystem.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.jar.Manifest; /** * In Memory Configurator doesn't spawn a external process, but * does this in memory. * * @see SandboxConfigurator */ public final class InMemoryConfigurator implements Configurator { private static final Logger LOG = LoggerFactory.getLogger(InMemoryConfigurator.class); /** * JAR file path. */ private final Location archive; /** * Application which needs to be configured. */ private final com.continuuity.api.Application application; /** * Constructor that accepts archive file as input to invoke configure. * * @param archive name of the archive file for which configure is invoked in-memory. */ public InMemoryConfigurator(Id.Account id, Location archive) { Preconditions.checkNotNull(id); Preconditions.checkNotNull(archive); this.archive = archive; this.application = null; } /** * Constructor that takes an {@link com.continuuity.api.Application} to invoke configure. * * @param application instance for which configure needs to be invoked. */ public InMemoryConfigurator(Id.Account id, com.continuuity.api.Application application) { Preconditions.checkNotNull(id); Preconditions.checkNotNull(application); this.archive = null; this.application = application; } /** * Executes the <code>Application.configure</code> within the same JVM. * <p> * This method could be dangerous and should be used only in singlenode. * </p> * * @return A instance of {@link ListenableFuture}. */ @Override public ListenableFuture<ConfigResponse> config() { SettableFuture<ConfigResponse> result = SettableFuture.create(); try { Object app; if (archive != null) { // Provided Application JAR. // Load the JAR using the JAR class load and load the manifest file. Manifest manifest = BundleJarUtil.getManifest(archive); Preconditions.checkArgument(manifest != null, "Failed to load manifest from %s", archive.toURI()); String mainClassName = manifest.getMainAttributes().getValue(ManifestFields.MAIN_CLASS); Preconditions.checkArgument(mainClassName != null && !mainClassName.isEmpty(), "Main class attribute cannot be empty"); File unpackedJarDir = Files.createTempDir(); try { app = new Archive(BundleJarUtil.unpackProgramJar(archive, unpackedJarDir), mainClassName).getMainClass().newInstance(); result.set(createResponse(app)); } finally { removeDir(unpackedJarDir); } } else { result.set(createResponse(application)); } return result; } catch (Throwable t) { LOG.error(t.getMessage(), t); return Futures.immediateFailedFuture(t); } } private ConfigResponse createResponse(Object app) { return new DefaultConfigResponse(0, CharStreams.newReaderSupplier(getSpecJson(app))); } @VisibleForTesting static final String getSpecJson(Object app) { // Now, we call configure, which returns application specification. ApplicationSpecification specification; if (app instanceof com.continuuity.api.Application) { specification = Specifications.from(((com.continuuity.api.Application) app).configure()); } else if (app instanceof Application) { DefaultAppConfigurer configurer = new DefaultAppConfigurer((Application) app); ((Application) app).configure(configurer, new ApplicationContext()); specification = configurer.createApplicationSpec(); } else { throw new IllegalStateException(String.format("Application main class is of invalid type: %s", app.getClass().getName())); } // Convert the specification to JSON. // We write the Application specification to output file in JSON format. // TODO: The SchemaGenerator should be injected return ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(specification); } private void removeDir(File dir) { try { DirUtils.deleteDirectoryContents(dir); } catch (IOException e) { LOG.warn("Failed to delete directory {}", dir, e); } } }
app-fabric/src/main/java/com/continuuity/internal/app/deploy/InMemoryConfigurator.java
/* * Copyright 2012-2013 Continuuity,Inc. All Rights Reserved. */ package com.continuuity.internal.app.deploy; import com.continuuity.api.app.Application; import com.continuuity.api.app.ApplicationContext; import com.continuuity.app.ApplicationSpecification; import com.continuuity.app.DefaultAppConfigurer; import com.continuuity.app.Id; import com.continuuity.app.deploy.ConfigResponse; import com.continuuity.app.deploy.Configurator; import com.continuuity.app.program.Archive; import com.continuuity.app.program.ManifestFields; import com.continuuity.common.lang.jar.BundleJarUtil; import com.continuuity.common.utils.DirUtils; import com.continuuity.internal.app.ApplicationSpecificationAdapter; import com.continuuity.internal.app.Specifications; import com.continuuity.internal.io.ReflectionSchemaGenerator; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.io.CharStreams; import com.google.common.io.Files; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.apache.twill.filesystem.Location; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.jar.Manifest; /** * In Memory Configurator doesn't spawn a external process, but * does this in memory. * * @see SandboxConfigurator */ public final class InMemoryConfigurator implements Configurator { private static final Logger LOG = LoggerFactory.getLogger(InMemoryConfigurator.class); /** * JAR file path. */ private final Location archive; /** * Application which needs to be configured. */ private final com.continuuity.api.Application application; /** * Constructor that accepts archive file as input to invoke configure. * * @param archive name of the archive file for which configure is invoked in-memory. */ public InMemoryConfigurator(Id.Account id, Location archive) { Preconditions.checkNotNull(id); Preconditions.checkNotNull(archive); this.archive = archive; this.application = null; } /** * Constructor that takes an {@link com.continuuity.api.Application} to invoke configure. * * @param application instance for which configure needs to be invoked. */ public InMemoryConfigurator(Id.Account id, com.continuuity.api.Application application) { Preconditions.checkNotNull(id); Preconditions.checkNotNull(application); this.archive = null; this.application = application; } /** * Executes the <code>Application.configure</code> within the same JVM. * <p> * This method could be dangerous and should be used only in singlenode. * </p> * * @return A instance of {@link ListenableFuture}. */ @Override public ListenableFuture<ConfigResponse> config() { SettableFuture<ConfigResponse> result = SettableFuture.create(); try { Object app; if (archive != null) { // Provided Application JAR. // Load the JAR using the JAR class load and load the manifest file. Manifest manifest = BundleJarUtil.getManifest(archive); Preconditions.checkArgument(manifest != null, "Failed to load manifest from %s", archive.toURI()); String mainClassName = manifest.getMainAttributes().getValue(ManifestFields.MAIN_CLASS); Preconditions.checkArgument(mainClassName != null && mainClassName.isEmpty(), "Main class attribute cannot be empty"); File unpackedJarDir = Files.createTempDir(); try { app = new Archive(BundleJarUtil.unpackProgramJar(archive, unpackedJarDir), mainClassName).getMainClass().newInstance(); result.set(createResponse(app)); } finally { removeDir(unpackedJarDir); } } else { result.set(createResponse(application)); } return result; } catch (Throwable t) { LOG.error(t.getMessage(), t); return Futures.immediateFailedFuture(t); } } private ConfigResponse createResponse(Object app) { return new DefaultConfigResponse(0, CharStreams.newReaderSupplier(getSpecJson(app))); } @VisibleForTesting static final String getSpecJson(Object app) { // Now, we call configure, which returns application specification. ApplicationSpecification specification; if (app instanceof com.continuuity.api.Application) { specification = Specifications.from(((com.continuuity.api.Application) app).configure()); } else if (app instanceof Application) { DefaultAppConfigurer configurer = new DefaultAppConfigurer((Application) app); ((Application) app).configure(configurer, new ApplicationContext()); specification = configurer.createApplicationSpec(); } else { throw new IllegalStateException(String.format("Application main class is of invalid type: %s", app.getClass().getName())); } // Convert the specification to JSON. // We write the Application specification to output file in JSON format. // TODO: The SchemaGenerator should be injected return ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(specification); } private void removeDir(File dir) { try { DirUtils.deleteDirectoryContents(dir); } catch (IOException e) { LOG.warn("Failed to delete directory {}", dir, e); } } }
Fix wrong precondition for main class in InMemoryConfigurator
app-fabric/src/main/java/com/continuuity/internal/app/deploy/InMemoryConfigurator.java
Fix wrong precondition for main class in InMemoryConfigurator
<ide><path>pp-fabric/src/main/java/com/continuuity/internal/app/deploy/InMemoryConfigurator.java <ide> Manifest manifest = BundleJarUtil.getManifest(archive); <ide> Preconditions.checkArgument(manifest != null, "Failed to load manifest from %s", archive.toURI()); <ide> String mainClassName = manifest.getMainAttributes().getValue(ManifestFields.MAIN_CLASS); <del> Preconditions.checkArgument(mainClassName != null && mainClassName.isEmpty(), <add> Preconditions.checkArgument(mainClassName != null && !mainClassName.isEmpty(), <ide> "Main class attribute cannot be empty"); <ide> <ide> File unpackedJarDir = Files.createTempDir();
Java
apache-2.0
8ddedbb563c8ed4801064a26f23e24d1732548f6
0
cjduffett/synthea,synthetichealth/synthea,synthetichealth/synthea,cjduffett/synthea,synthetichealth/synthea
package org.mitre.synthea.export; import java.util.Date; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.hl7.fhir.dstu3.model.Address; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent; import org.hl7.fhir.dstu3.model.Bundle.BundleType; import org.hl7.fhir.dstu3.model.CarePlan.CarePlanActivityStatus; import org.hl7.fhir.dstu3.model.CarePlan.CarePlanStatus; import org.hl7.fhir.dstu3.model.Claim.ClaimStatus; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.Condition; import org.hl7.fhir.dstu3.model.Condition.ConditionClinicalStatus; import org.hl7.fhir.dstu3.model.Condition.ConditionVerificationStatus; import org.hl7.fhir.dstu3.model.DateTimeType; import org.hl7.fhir.dstu3.model.DateType; import org.hl7.fhir.dstu3.model.DecimalType; import org.hl7.fhir.dstu3.model.DiagnosticReport; import org.hl7.fhir.dstu3.model.DiagnosticReport.DiagnosticReportStatus; import org.hl7.fhir.dstu3.model.Encounter.EncounterStatus; import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender; import org.hl7.fhir.dstu3.model.Extension; import org.hl7.fhir.dstu3.model.Goal.GoalStatus; import org.hl7.fhir.dstu3.model.Immunization; import org.hl7.fhir.dstu3.model.Immunization.ImmunizationStatus; import org.hl7.fhir.dstu3.model.MedicationRequest; import org.hl7.fhir.dstu3.model.MedicationRequest.MedicationRequestIntent; import org.hl7.fhir.dstu3.model.MedicationRequest.MedicationRequestStatus; import org.hl7.fhir.dstu3.model.Money; import org.hl7.fhir.dstu3.model.Narrative; import org.hl7.fhir.dstu3.model.Narrative.NarrativeStatus; import org.hl7.fhir.dstu3.model.Observation.ObservationStatus; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.dstu3.model.Period; import org.hl7.fhir.dstu3.model.PositiveIntType; import org.hl7.fhir.dstu3.model.Quantity; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.dstu3.model.Resource; import org.hl7.fhir.dstu3.model.StringType; import org.hl7.fhir.dstu3.model.Type; import org.hl7.fhir.utilities.xhtml.NodeType; import org.hl7.fhir.utilities.xhtml.XhtmlNode; import org.mitre.synthea.modules.HealthRecord; import org.mitre.synthea.modules.HealthRecord.CarePlan; import org.mitre.synthea.modules.HealthRecord.Claim; import org.mitre.synthea.modules.HealthRecord.ClaimItem; import org.mitre.synthea.modules.HealthRecord.Code; import org.mitre.synthea.modules.HealthRecord.Encounter; import org.mitre.synthea.modules.HealthRecord.Medication; import org.mitre.synthea.modules.HealthRecord.Observation; import org.mitre.synthea.modules.HealthRecord.Procedure; import org.mitre.synthea.modules.HealthRecord.Report; import org.mitre.synthea.modules.Person; import ca.uhn.fhir.context.FhirContext; import com.vividsolutions.jts.geom.Point; public class FhirStu3 { // HAPI FHIR warns that the context creation is expensive, and should be performed // per-application, not per-record private static final FhirContext FHIR_CTX = FhirContext.forDstu3(); private static final String SNOMED_URI = "http://snomed.info/sct"; private static final String LOINC_URI = "http://loinc.org"; private static final String RXNORM_URI = "http://www.nlm.nih.gov/research/umls/rxnorm"; private static final String CVX_URI = "http://hl7.org/fhir/sid/cvx"; /** * Convert the given Person into a JSON String, * containing a FHIR Bundle of the Person and the associated entries from their health record. * @param person Person to generate the FHIR JSON for * @param stopTime Time the simulation ended * @return String containing a JSON representation of a FHIR Bundle containing the Person's health record */ public static String convertToFHIR(Person person, long stopTime) { Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); BundleEntryComponent personEntry = basicInfo(person, bundle, stopTime); for (Encounter encounter : person.record.encounters) { BundleEntryComponent encounterEntry = encounter(personEntry, bundle, encounter); for (HealthRecord.Entry condition : encounter.conditions) { condition(personEntry, bundle, encounterEntry, condition); } for (Observation observation : encounter.observations) { observation(personEntry, bundle, encounterEntry, observation); } for (Procedure procedure : encounter.procedures) { procedure(personEntry, bundle, encounterEntry, procedure); } for (Medication medication : encounter.medications) { medication(personEntry, bundle, encounterEntry, medication); } for (HealthRecord.Entry immunization : encounter.immunizations) { immunization(personEntry, bundle, encounterEntry, immunization); } for (Report report : encounter.reports) { report(personEntry, bundle, encounterEntry, report); } for (CarePlan careplan : encounter.careplans) { careplan(personEntry, bundle, encounterEntry, careplan); } // one claim per encounter encounterClaim(personEntry, bundle, encounterEntry, encounter.claim); } String bundleJson = FHIR_CTX.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle); return bundleJson; } /** * Map the given Person to a FHIR Patient resource, and add it to the given Bundle. * @param person The Person * @param bundle The Bundle to add to * @param stopTime Time the simulation ended * @return The created Entry */ private static BundleEntryComponent basicInfo(Person person, Bundle bundle, long stopTime) { Patient patientResource = new Patient(); patientResource.addIdentifier() .setSystem("https://github.com/synthetichealth/synthea") .setValue((String)person.attributes.get(Person.ID)); patientResource.addName().addGiven((String)person.attributes.get(Person.NAME)); if (person.attributes.get(Person.GENDER).equals("M")) { patientResource.setGender(AdministrativeGender.MALE); } else if (person.attributes.get(Person.GENDER).equals("F")) { patientResource.setGender(AdministrativeGender.FEMALE); } long birthdate = (long)person.attributes.get(Person.BIRTHDATE); patientResource.setBirthDate(new Date(birthdate)); Point coord = (Point)person.attributes.get(Person.COORDINATE); Address addrResource = patientResource.addAddress(); addrResource.addLine((String)person.attributes.get(Person.ADDRESS)) .setCity((String)person.attributes.get(Person.CITY)) .setPostalCode((String)person.attributes.get(Person.ZIP)) .setState((String)person.attributes.get(Person.STATE)) .setCountry("US"); Extension geolocation = addrResource.addExtension(); geolocation.setUrl("http://hl7.org/fhir/StructureDefinition/geolocation"); geolocation.addExtension("latitude", new DecimalType(coord.getY())); geolocation.addExtension("longitude", new DecimalType(coord.getX())); if (!person.alive(stopTime)) { patientResource.setDeceased( convertFhirDateTime(person.record.death, true) ); } // TODO: ruby version also has: // telecom, language, race, ethnicity, place of birth, mother's maiden name, // birth sex, prefix+suffix, marital status, multiple birth status, // identifiers (SSN, driver's lic, passport, fingerprint) String generatedBySynthea = "Generated by <a href=\"https://github.com/synthetichealth/synthea\">Synthea</a>. " + "Version identifier: JAVA-0.0.0 . " + "Person seed: " + person.seed + "</div>"; // TODO patientResource.setText(new Narrative().setStatus(NarrativeStatus.GENERATED).setDiv(new XhtmlNode(NodeType.Element).setValue(generatedBySynthea))); // DALY and QALY values // we only write the last(current) one to the patient record Double dalyValue = (Double) person.attributes.get("most-recent-daly"); Double qalyValue = (Double) person.attributes.get("most-recent-qaly"); if (dalyValue != null) { Extension dalyExtension = new Extension(SNOMED_URI + "/disability-adjusted-life-years"); DecimalType daly = new DecimalType(dalyValue); dalyExtension.setValue(daly); patientResource.addExtension(dalyExtension); Extension qalyExtension = new Extension(SNOMED_URI + "/quality-adjusted-life-years"); DecimalType qaly = new DecimalType(qalyValue); qalyExtension.setValue(qaly); patientResource.addExtension(qalyExtension); } return newEntry(bundle, patientResource); } /** * Map the given Encounter into a FHIR Encounter resource, and add it to the given Bundle. * @param personEntry Entry for the Person * @param bundle The Bundle to add to * @param encounter The current Encounter * @return The added Entry */ private static BundleEntryComponent encounter(BundleEntryComponent personEntry, Bundle bundle, Encounter encounter) { org.hl7.fhir.dstu3.model.Encounter encounterResource = new org.hl7.fhir.dstu3.model.Encounter(); encounterResource.setSubject(new Reference(personEntry.getFullUrl())); encounterResource.setStatus(EncounterStatus.FINISHED); if (encounter.codes.isEmpty()) { // wellness encounter encounterResource.addType().addCoding() .setCode("185349003") .setDisplay("Encounter for check up") .setSystem(SNOMED_URI); } else { Code code = encounter.codes.get(0); encounterResource.addType( mapCodeToCodeableConcept(code, SNOMED_URI) ); } encounterResource.setClass_(new Coding().setCode(encounter.type)); long encounter_end = encounter.stop > 0 ? encounter.stop : encounter.stop + TimeUnit.MINUTES.toMillis(15); encounterResource.setPeriod( new Period().setStart(new Date(encounter.start)).setEnd( new Date(encounter_end)) ); // TODO: provider, reason, discharge return newEntry(bundle, encounterResource); } /** * Create an entry for the given Claim, which references a Medication. * @param personEntry Entry for the person * @param bundle The Bundle to add to * @param encounterEntry The current Encounter * @param claim the Claim object * @param medicationEntry The Entry for the Medication object, previously created * @return the added Entry */ private static BundleEntryComponent medicationClaim(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Claim claim, BundleEntryComponent medicationEntry) { org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim(); org.hl7.fhir.dstu3.model.Encounter encounterResource = (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource(); claimResource.setStatus(ClaimStatus.ACTIVE); claimResource.setUse(org.hl7.fhir.dstu3.model.Claim.Use.COMPLETE); //duration of encounter claimResource.setBillablePeriod(encounterResource.getPeriod()); claimResource.setPatient(new Reference(personEntry.getFullUrl())); claimResource.setOrganization(encounterResource.getServiceProvider()); //add item for encounter claimResource.addItem(new org.hl7.fhir.dstu3.model.Claim.ItemComponent().addEncounter(new Reference(encounterEntry.getFullUrl()))); //add prescription. claimResource.setPrescription(new Reference(medicationEntry.getFullUrl())); Money moneyResource = new Money(); moneyResource.setValue(claim.total()); claimResource.setTotal(moneyResource); return newEntry(bundle, claimResource); } /** * Create an entry for the given Claim, associated to an Encounter * @param personEntry Entry for the person * @param bundle The Bundle to add to * @param encounterEntry The current Encounter * @param claim the Claim object * @return the added Entry */ private static BundleEntryComponent encounterClaim(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Claim claim) { org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim(); org.hl7.fhir.dstu3.model.Encounter encounterResource = (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource(); claimResource.setStatus(ClaimStatus.ACTIVE); claimResource.setUse(org.hl7.fhir.dstu3.model.Claim.Use.COMPLETE); //duration of encounter claimResource.setBillablePeriod(encounterResource.getPeriod()); claimResource.setPatient(new Reference(personEntry.getFullUrl())); claimResource.setOrganization(encounterResource.getServiceProvider()); //add item for encounter claimResource.addItem(new org.hl7.fhir.dstu3.model.Claim.ItemComponent().addEncounter(new Reference(encounterEntry.getFullUrl()))); int conditionSequence = 1; int procedureSequence = 1; for (ClaimItem item : claim.items) { if (item.entry instanceof Procedure) { Type procedureReference= new Reference(item.entry.fullUrl); org.hl7.fhir.dstu3.model.Claim.ProcedureComponent claimProcedure = new org.hl7.fhir.dstu3.model.Claim.ProcedureComponent(new PositiveIntType(procedureSequence), procedureReference); claimResource.addProcedure(claimProcedure); //update claimItems list org.hl7.fhir.dstu3.model.Claim.ItemComponent procedureItem = new org.hl7.fhir.dstu3.model.Claim.ItemComponent(); procedureItem.addProcedureLinkId(procedureSequence); // TODO ??? this field needs more description //calculate cost of procedure based on rvu values for a facility Money moneyResource = new Money(); moneyResource.setValue(item.cost()); procedureItem.setNet(moneyResource); claimResource.addItem(procedureItem); procedureSequence++; } else { // assume it's a Condition, we don't have a Condition class specifically //add diagnosisComponent to claim Reference diagnosisReference = new Reference(item.entry.fullUrl); org.hl7.fhir.dstu3.model.Claim.DiagnosisComponent diagnosisComponent = new org.hl7.fhir.dstu3.model.Claim.DiagnosisComponent(new PositiveIntType(conditionSequence),diagnosisReference); claimResource.addDiagnosis(diagnosisComponent); //update claimItems with diagnosis org.hl7.fhir.dstu3.model.Claim.ItemComponent diagnosisItem = new org.hl7.fhir.dstu3.model.Claim.ItemComponent(); diagnosisItem.addDiagnosisLinkId(conditionSequence); claimResource.addItem(diagnosisItem); conditionSequence++; } } Money moneyResource = new Money(); moneyResource.setValue(claim.total()); claimResource.setTotal(moneyResource); return newEntry(bundle, claimResource); } /** * Map the Condition into a FHIR Condition resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle The Bundle to add to * @param encounterEntry The current Encounter entry * @param condition The Condition * @param claimEntry * @param sequence * @return The added Entry */ private static BundleEntryComponent condition(BundleEntryComponent personEntry, Bundle bundle,BundleEntryComponent encounterEntry, HealthRecord.Entry condition) { Condition conditionResource = new Condition(); conditionResource.setSubject(new Reference(personEntry.getFullUrl())); conditionResource.setContext(new Reference(encounterEntry.getFullUrl())); Code code = condition.codes.get(0); conditionResource.setCode( mapCodeToCodeableConcept(code, SNOMED_URI) ); conditionResource.setVerificationStatus(ConditionVerificationStatus.CONFIRMED); conditionResource.setClinicalStatus(ConditionClinicalStatus.ACTIVE); conditionResource.setOnset( convertFhirDateTime(condition.start, true) ); conditionResource.setAssertedDate(new Date(condition.start)); if (condition.stop > 0) { conditionResource.setAbatement(convertFhirDateTime(condition.stop, true)); } BundleEntryComponent conditionEntry = newEntry(bundle, conditionResource); condition.fullUrl = conditionEntry.getFullUrl(); return conditionEntry; } /** * Map the given Observation into a FHIR Observation resource, and add it to the given Bundle. * @param personEntry The Person Entry * @param bundle The Bundle to add to * @param encounterEntry The current Encounter entry * @param observation The Observation * @return The added Entry */ private static BundleEntryComponent observation(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Observation observation) { org.hl7.fhir.dstu3.model.Observation observationResource = new org.hl7.fhir.dstu3.model.Observation(); observationResource.setSubject(new Reference(personEntry.getFullUrl())); observationResource.setContext(new Reference(encounterEntry.getFullUrl())); observationResource.setStatus(ObservationStatus.FINAL); Code code = observation.codes.get(0); observationResource.setCode( mapCodeToCodeableConcept(code, LOINC_URI) ); observationResource.addCategory().addCoding() .setCode(observation.category) .setSystem("http://hl7.org/fhir/observation-category") .setDisplay(observation.category); Type value = null; if (observation.value instanceof Condition) { Code conditionCode = ((HealthRecord.Entry)observation.value).codes.get(0); value = mapCodeToCodeableConcept(conditionCode, SNOMED_URI); } else if (observation.value instanceof String) { value = new StringType((String)observation.value); } else if (observation.value instanceof Number) { value = new Quantity() .setValue(((Number)observation.value).doubleValue()) .setCode(observation.unit) .setSystem("http://unitsofmeasure.org/") .setUnit(observation.unit); } else if (observation.value != null) { throw new IllegalArgumentException("unexpected observation value class: " + observation.value.getClass().toString() + "; " + observation.value); } if (value != null) { observationResource.setValue(value); } observationResource.setEffective(convertFhirDateTime(observation.start, true)); observationResource.setIssued(new Date(observation.start)); BundleEntryComponent entry = newEntry(bundle, observationResource); observation.fullUrl = entry.getFullUrl(); return entry; } /** * Map the given Procedure into a FHIR Procedure resource, and add it to the given Bundle. * @param personEntry The Person entry * @param bundle Bundle to add to * @param encounterEntry The current Encounter entry * @param procedure The Procedure * @param claimResource * @param sequence * @return The added Entry */ private static BundleEntryComponent procedure(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Procedure procedure) { org.hl7.fhir.dstu3.model.Procedure procedureResource = new org.hl7.fhir.dstu3.model.Procedure(); procedureResource.setSubject(new Reference(personEntry.getFullUrl())); procedureResource.setContext(new Reference(encounterEntry.getFullUrl())); Code code = procedure.codes.get(0); procedureResource.setCode( mapCodeToCodeableConcept(code, SNOMED_URI) ); if (procedure.stop > 0L) { Date startDate = new Date(procedure.start); Date endDate = new Date(procedure.stop); procedureResource.setPerformed(new Period().setStart(startDate).setEnd(endDate)); } else { procedureResource.setPerformed(convertFhirDateTime(procedure.start, true)); } BundleEntryComponent procedureEntry = newEntry(bundle, procedureResource); // TODO - reason procedure.fullUrl = procedureEntry.getFullUrl(); return procedureEntry; } private static BundleEntryComponent immunization(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, HealthRecord.Entry immunization) { Immunization immResource = new Immunization(); immResource.setStatus(ImmunizationStatus.COMPLETED); immResource.setDate(new Date(immunization.start)); immResource.setVaccineCode(mapCodeToCodeableConcept(immunization.codes.get(0), CVX_URI)); immResource.setNotGiven(false); immResource.setPrimarySource(true); immResource.setPatient(new Reference(personEntry.getFullUrl())); immResource.setEncounter(new Reference(encounterEntry.getFullUrl())); return newEntry(bundle, immResource); } /** * Map the given Medication to a FHIR MedicationRequest resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle Bundle to add the Medication to * @param encounterEntry Current Encounter entry * @param medication The Medication * @return The added Entry */ private static BundleEntryComponent medication(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Medication medication) { MedicationRequest medicationResource = new MedicationRequest(); medicationResource.setSubject(new Reference(personEntry.getFullUrl())); medicationResource.setContext(new Reference(encounterEntry.getFullUrl())); medicationResource.setMedication(mapCodeToCodeableConcept(medication.codes.get(0), RXNORM_URI)); medicationResource.setAuthoredOn(new Date(medication.start)); medicationResource.setIntent(MedicationRequestIntent.ORDER); if (medication.stop > 0L) { medicationResource.setStatus(MedicationRequestStatus.STOPPED); } else { medicationResource.setStatus(MedicationRequestStatus.ACTIVE); } // TODO - prescription details & reason BundleEntryComponent medicationEntry = newEntry(bundle, medicationResource); //create new claim for medication medicationClaim(personEntry, bundle, encounterEntry, medication.claim, medicationEntry); return medicationEntry; } /** * Map the given Report to a FHIR DiagnosticReport resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle Bundle to add the Report to * @param encounterEntry Current Encounter entry * @param report The Report * @return The added Entry */ private static BundleEntryComponent report(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Report report) { DiagnosticReport reportResource = new DiagnosticReport(); reportResource.setStatus(DiagnosticReportStatus.FINAL); reportResource.setCode(mapCodeToCodeableConcept(report.codes.get(0), LOINC_URI)); reportResource.setSubject(new Reference(personEntry.getFullUrl())); reportResource.setContext(new Reference(encounterEntry.getFullUrl())); reportResource.setEffective(convertFhirDateTime(report.start, true)); reportResource.setIssued(new Date(report.start)); for(Observation observation : report.observations) { Reference reference = new Reference(observation.fullUrl); reference.setDisplay(observation.codes.get(0).display); reportResource.addResult(reference); } return newEntry(bundle, reportResource); } /** * Map the given CarePlan to a FHIR CarePlan resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle Bundle to add the CarePlan to * @param encounterEntry Current Encounter entry * @param carePlan The CarePlan to map to FHIR and add to the bundle * @return The added Entry */ private static BundleEntryComponent careplan(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, CarePlan carePlan) { org.hl7.fhir.dstu3.model.CarePlan careplanResource = new org.hl7.fhir.dstu3.model.CarePlan(); careplanResource.setSubject(new Reference(personEntry.getFullUrl())); careplanResource.setContext(new Reference(encounterEntry.getFullUrl())); Code code = carePlan.codes.get(0); careplanResource.addCategory( mapCodeToCodeableConcept(code, SNOMED_URI) ); CarePlanActivityStatus activityStatus; GoalStatus goalStatus; Period period = new Period().setStart(new Date(carePlan.start)); careplanResource.setPeriod(period); if (carePlan.stop > 0L) { period.setEnd(new Date(carePlan.stop)); careplanResource.setStatus(CarePlanStatus.COMPLETED); activityStatus = CarePlanActivityStatus.COMPLETED; goalStatus = GoalStatus.ACHIEVED; } else { careplanResource.setStatus(CarePlanStatus.ACTIVE); activityStatus = CarePlanActivityStatus.INPROGRESS; goalStatus = GoalStatus.INPROGRESS; } // TODO - goals, activities, reasons return newEntry(bundle, careplanResource); } /** * Convert the timestamp into a FHIR DateType or DateTimeType. * * @param datetime Timestamp * @param time If true, return a DateTime; if false, return a Date. * @return a DateType or DateTimeType representing the given timestamp */ private static Type convertFhirDateTime(long datetime, boolean time) { Date date = new Date(datetime); if (time) { return new DateTimeType(date); } else { return new DateType(date); } } /** * Helper function to convert a Code into a CodeableConcept. * Takes an optional system, which replaces the Code.system in the resulting CodeableConcept if not null. * * @param from The Code to create a CodeableConcept from. * @param system The system identifier, such as a URI. Optional; may be null. * @return The converted CodeableConcept */ private static CodeableConcept mapCodeToCodeableConcept(Code from, String system) { CodeableConcept to = new CodeableConcept(); if (from.display != null) { to.setText(from.display); } Coding coding = new Coding(); coding.setCode(from.code); coding.setDisplay(from.display); if (system == null) { coding.setSystem(from.system); } else { coding.setSystem(system); } to.addCoding(coding); return to; } /** * Helper function to create an Entry for the given Resource within the given Bundle. * Sets the resourceID to a random UUID, sets the entry's fullURL to that resourceID, * and adds the entry to the bundle. * * @param bundle The Bundle to add the Entry to * @param resource Resource the new Entry should contain * @return the created Entry */ private static BundleEntryComponent newEntry(Bundle bundle, Resource resource) { BundleEntryComponent entry = bundle.addEntry(); String resourceID = UUID.randomUUID().toString(); resource.setId(resourceID); entry.setFullUrl("urn:uuid:" + resourceID); entry.setResource(resource); return entry; } }
src/main/java/org/mitre/synthea/export/FhirStu3.java
package org.mitre.synthea.export; import java.util.Date; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.hl7.fhir.dstu3.model.Address; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent; import org.hl7.fhir.dstu3.model.Bundle.BundleType; import org.hl7.fhir.dstu3.model.CarePlan.CarePlanActivityStatus; import org.hl7.fhir.dstu3.model.CarePlan.CarePlanStatus; import org.hl7.fhir.dstu3.model.Claim.ClaimStatus; import org.hl7.fhir.dstu3.model.CodeableConcept; import org.hl7.fhir.dstu3.model.Coding; import org.hl7.fhir.dstu3.model.Condition; import org.hl7.fhir.dstu3.model.Condition.ConditionClinicalStatus; import org.hl7.fhir.dstu3.model.Condition.ConditionVerificationStatus; import org.hl7.fhir.dstu3.model.DateTimeType; import org.hl7.fhir.dstu3.model.DateType; import org.hl7.fhir.dstu3.model.DecimalType; import org.hl7.fhir.dstu3.model.DiagnosticReport; import org.hl7.fhir.dstu3.model.DiagnosticReport.DiagnosticReportStatus; import org.hl7.fhir.dstu3.model.Encounter.EncounterStatus; import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender; import org.hl7.fhir.dstu3.model.Extension; import org.hl7.fhir.dstu3.model.Goal.GoalStatus; import org.hl7.fhir.dstu3.model.Immunization; import org.hl7.fhir.dstu3.model.Immunization.ImmunizationStatus; import org.hl7.fhir.dstu3.model.MedicationRequest; import org.hl7.fhir.dstu3.model.MedicationRequest.MedicationRequestIntent; import org.hl7.fhir.dstu3.model.MedicationRequest.MedicationRequestStatus; import org.hl7.fhir.dstu3.model.Money; import org.hl7.fhir.dstu3.model.Narrative; import org.hl7.fhir.dstu3.model.Narrative.NarrativeStatus; import org.hl7.fhir.dstu3.model.Observation.ObservationStatus; import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.dstu3.model.Period; import org.hl7.fhir.dstu3.model.PositiveIntType; import org.hl7.fhir.dstu3.model.Quantity; import org.hl7.fhir.dstu3.model.Reference; import org.hl7.fhir.dstu3.model.Resource; import org.hl7.fhir.dstu3.model.StringType; import org.hl7.fhir.dstu3.model.Type; import org.hl7.fhir.utilities.xhtml.NodeType; import org.hl7.fhir.utilities.xhtml.XhtmlNode; import org.mitre.synthea.modules.HealthRecord; import org.mitre.synthea.modules.HealthRecord.CarePlan; import org.mitre.synthea.modules.HealthRecord.Claim; import org.mitre.synthea.modules.HealthRecord.ClaimItem; import org.mitre.synthea.modules.HealthRecord.Code; import org.mitre.synthea.modules.HealthRecord.Encounter; import org.mitre.synthea.modules.HealthRecord.Medication; import org.mitre.synthea.modules.HealthRecord.Observation; import org.mitre.synthea.modules.HealthRecord.Procedure; import org.mitre.synthea.modules.HealthRecord.Report; import org.mitre.synthea.modules.Person; import ca.uhn.fhir.context.FhirContext; import com.vividsolutions.jts.geom.Point; public class FhirStu3 { // HAPI FHIR warns that the context creation is expensive, and should be performed // per-application, not per-record private static final FhirContext FHIR_CTX = FhirContext.forDstu3(); private static final String SNOMED_URI = "http://snomed.info/sct"; private static final String LOINC_URI = "http://loinc.org"; private static final String RXNORM_URI = "http://www.nlm.nih.gov/research/umls/rxnorm"; private static final String CVX_URI = "http://hl7.org/fhir/sid/cvx"; /** * Convert the given Person into a JSON String, * containing a FHIR Bundle of the Person and the associated entries from their health record. * @param person Person to generate the FHIR JSON for * @param stopTime Time the simulation ended * @return String containing a JSON representation of a FHIR Bundle containing the Person's health record */ public static String convertToFHIR(Person person, long stopTime) { Bundle bundle = new Bundle(); bundle.setType(BundleType.COLLECTION); BundleEntryComponent personEntry = basicInfo(person, bundle, stopTime); for (Encounter encounter : person.record.encounters) { BundleEntryComponent encounterEntry = encounter(personEntry, bundle, encounter); for (HealthRecord.Entry condition : encounter.conditions) { condition(personEntry, bundle, encounterEntry, condition); } for (Observation observation : encounter.observations) { observation(personEntry, bundle, encounterEntry, observation); } for (Procedure procedure : encounter.procedures) { procedure(personEntry, bundle, encounterEntry, procedure); } for (Medication medication : encounter.medications) { medication(personEntry, bundle, encounterEntry, medication); } for (HealthRecord.Entry immunization : encounter.immunizations) { immunization(personEntry, bundle, encounterEntry, immunization); } for (Report report : encounter.reports) { report(personEntry, bundle, encounterEntry, report); } for (CarePlan careplan : encounter.careplans) { careplan(personEntry, bundle, encounterEntry, careplan); } // one claim per encounter encounterClaim(personEntry, bundle, encounterEntry, encounter.claim); } String bundleJson = FHIR_CTX.newJsonParser().setPrettyPrint(true).encodeResourceToString(bundle); return bundleJson; } /** * Map the given Person to a FHIR Patient resource, and add it to the given Bundle. * @param person The Person * @param bundle The Bundle to add to * @param stopTime Time the simulation ended * @return The created Entry */ private static BundleEntryComponent basicInfo(Person person, Bundle bundle, long stopTime) { Patient patientResource = new Patient(); patientResource.addIdentifier() .setSystem("https://github.com/synthetichealth/synthea") .setValue((String)person.attributes.get(Person.ID)); patientResource.addName().addGiven((String)person.attributes.get(Person.NAME)); if (person.attributes.get(Person.GENDER).equals("M")) { patientResource.setGender(AdministrativeGender.MALE); } else if (person.attributes.get(Person.GENDER).equals("F")) { patientResource.setGender(AdministrativeGender.FEMALE); } long birthdate = (long)person.attributes.get(Person.BIRTHDATE); patientResource.setBirthDate(new Date(birthdate)); Point coord = (Point)person.attributes.get(Person.COORDINATE); Address addrResource = patientResource.addAddress(); addrResource.addLine((String)person.attributes.get(Person.ADDRESS)) .setCity((String)person.attributes.get(Person.CITY)) .setPostalCode((String)person.attributes.get(Person.ZIP)) .setState((String)person.attributes.get(Person.STATE)) .setCountry("US"); Extension geolocation = addrResource.addExtension(); geolocation.setUrl("http://hl7.org/fhir/StructureDefinition/geolocation"); geolocation.addExtension("latitude", new DecimalType(coord.getY())); geolocation.addExtension("longitude", new DecimalType(coord.getX())); if (!person.alive(stopTime)) { patientResource.setDeceased( convertFhirDateTime(person.record.death, true) ); } // TODO: ruby version also has: // telecom, language, race, ethnicity, place of birth, mother's maiden name, // birth sex, prefix+suffix, marital status, multiple birth status, // identifiers (SSN, driver's lic, passport, fingerprint) String generatedBySynthea = "Generated by <a href=\"https://github.com/synthetichealth/synthea\">Synthea</a>. " + "Version identifier: JAVA-0.0.0 . " + "Person seed: " + person.seed + "</div>"; // TODO patientResource.setText(new Narrative().setStatus(NarrativeStatus.GENERATED).setDiv(new XhtmlNode(NodeType.Element).setValue(generatedBySynthea))); // DALY and QALY values // we only write the last(current) one to the patient record Double dalyValue = (Double) person.attributes.get("most-recent-daly"); Double qalyValue = (Double) person.attributes.get("most-recent-qaly"); if (dalyValue != null) { Extension dalyExtension = new Extension(SNOMED_URI + "/disability-adjusted-life-years"); DecimalType daly = new DecimalType(dalyValue); dalyExtension.setValue(daly); patientResource.addExtension(dalyExtension); Extension qalyExtension = new Extension(SNOMED_URI + "/quality-adjusted-life-years"); DecimalType qaly = new DecimalType(qalyValue); qalyExtension.setValue(qaly); patientResource.addExtension(qalyExtension); } return newEntry(bundle, patientResource); } /** * Map the given Encounter into a FHIR Encounter resource, and add it to the given Bundle. * @param personEntry Entry for the Person * @param bundle The Bundle to add to * @param encounter The current Encounter * @return The added Entry */ private static BundleEntryComponent encounter(BundleEntryComponent personEntry, Bundle bundle, Encounter encounter) { org.hl7.fhir.dstu3.model.Encounter encounterResource = new org.hl7.fhir.dstu3.model.Encounter(); encounterResource.setSubject(new Reference(personEntry.getFullUrl())); encounterResource.setStatus(EncounterStatus.FINISHED); if (encounter.codes.isEmpty()) { // wellness encounter encounterResource.addType().addCoding() .setCode("185349003") .setDisplay("Encounter for check up") .setSystem(SNOMED_URI); } else { Code code = encounter.codes.get(0); encounterResource.addType( mapCodeToCodeableConcept(code, SNOMED_URI) ); } encounterResource.setClass_(new Coding().setCode(encounter.type)); long encounter_end = encounter.stop > 0 ? encounter.stop : encounter.stop + TimeUnit.MINUTES.toMillis(15); encounterResource.setPeriod( new Period().setStart(new Date(encounter.start)).setEnd( new Date(encounter_end)) ); // TODO: provider, reason, discharge return newEntry(bundle, encounterResource); } /** * ... * @param personEntry The Entry for the Person * @param bundle The Bundle to add to * @param encounterEntry The current Encounter entry * @param claim The Claim * @return The added Entry */ private static BundleEntryComponent medicationClaim(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, BundleEntryComponent medicationEntry) { org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim(); org.hl7.fhir.dstu3.model.Encounter encounterResource = (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource(); claimResource.setStatus(ClaimStatus.ACTIVE); claimResource.setUse(org.hl7.fhir.dstu3.model.Claim.Use.COMPLETE); //duration of encounter claimResource.setBillablePeriod(encounterResource.getPeriod()); claimResource.setPatient(new Reference(personEntry.getFullUrl())); claimResource.setOrganization(encounterResource.getServiceProvider()); //add item for encounter claimResource.addItem(new org.hl7.fhir.dstu3.model.Claim.ItemComponent().addEncounter(new Reference(encounterEntry.getFullUrl()))); //add prescription. claimResource.setPrescription(new Reference(medicationEntry.getFullUrl())); //cost of prescription currently set to $255.00 double medCost = 255.0; org.hl7.fhir.dstu3.model.Money moneyResource = new org.hl7.fhir.dstu3.model.Money(); moneyResource.setValue(medCost); claimResource.setTotal(moneyResource); return newEntry(bundle, claimResource); } private static BundleEntryComponent encounterClaim(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Claim claim) { org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim(); org.hl7.fhir.dstu3.model.Encounter encounterResource = (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource(); claimResource.setStatus(ClaimStatus.ACTIVE); claimResource.setUse(org.hl7.fhir.dstu3.model.Claim.Use.COMPLETE); //duration of encounter claimResource.setBillablePeriod(encounterResource.getPeriod()); claimResource.setPatient(new Reference(personEntry.getFullUrl())); claimResource.setOrganization(encounterResource.getServiceProvider()); //add item for encounter claimResource.addItem(new org.hl7.fhir.dstu3.model.Claim.ItemComponent().addEncounter(new Reference(encounterEntry.getFullUrl()))); int conditionSequence = 1; int procedureSequence = 1; for (ClaimItem item : claim.items) { if (item.entry instanceof Procedure) { Type procedureReference= new Reference(item.entry.fullUrl); org.hl7.fhir.dstu3.model.Claim.ProcedureComponent claimProcedure = new org.hl7.fhir.dstu3.model.Claim.ProcedureComponent(new PositiveIntType(procedureSequence), procedureReference); claimResource.addProcedure(claimProcedure); //update claimItems list org.hl7.fhir.dstu3.model.Claim.ItemComponent procedureItem = new org.hl7.fhir.dstu3.model.Claim.ItemComponent(); procedureItem.addProcedureLinkId(procedureSequence); // TODO ??? this field needs more description //calculate cost of procedure based on rvu values for a facility Money moneyResource = new Money(); moneyResource.setValue(item.cost()); procedureItem.setNet(moneyResource); claimResource.addItem(procedureItem); procedureSequence++; } else { // assume it's a Condition, we don't have a Condition class specifically //add diagnosisComponent to claim Reference diagnosisReference = new Reference(item.entry.fullUrl); org.hl7.fhir.dstu3.model.Claim.DiagnosisComponent diagnosisComponent = new org.hl7.fhir.dstu3.model.Claim.DiagnosisComponent(new PositiveIntType(conditionSequence),diagnosisReference); claimResource.addDiagnosis(diagnosisComponent); //update claimItems with diagnosis org.hl7.fhir.dstu3.model.Claim.ItemComponent diagnosisItem = new org.hl7.fhir.dstu3.model.Claim.ItemComponent(); diagnosisItem.addDiagnosisLinkId(conditionSequence); claimResource.addItem(diagnosisItem); conditionSequence++; } } Money moneyResource = new Money(); moneyResource.setValue(claim.total()); claimResource.setTotal(moneyResource); return newEntry(bundle, claimResource); } /** * Map the Condition into a FHIR Condition resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle The Bundle to add to * @param encounterEntry The current Encounter entry * @param condition The Condition * @param claimEntry * @param sequence * @return The added Entry */ private static BundleEntryComponent condition(BundleEntryComponent personEntry, Bundle bundle,BundleEntryComponent encounterEntry, HealthRecord.Entry condition) { Condition conditionResource = new Condition(); conditionResource.setSubject(new Reference(personEntry.getFullUrl())); conditionResource.setContext(new Reference(encounterEntry.getFullUrl())); Code code = condition.codes.get(0); conditionResource.setCode( mapCodeToCodeableConcept(code, SNOMED_URI) ); conditionResource.setVerificationStatus(ConditionVerificationStatus.CONFIRMED); conditionResource.setClinicalStatus(ConditionClinicalStatus.ACTIVE); conditionResource.setOnset( convertFhirDateTime(condition.start, true) ); conditionResource.setAssertedDate(new Date(condition.start)); if (condition.stop > 0) { conditionResource.setAbatement(convertFhirDateTime(condition.stop, true)); } BundleEntryComponent conditionEntry = newEntry(bundle, conditionResource); condition.fullUrl = conditionEntry.getFullUrl(); return conditionEntry; } /** * Map the given Observation into a FHIR Observation resource, and add it to the given Bundle. * @param personEntry The Person Entry * @param bundle The Bundle to add to * @param encounterEntry The current Encounter entry * @param observation The Observation * @return The added Entry */ private static BundleEntryComponent observation(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Observation observation) { org.hl7.fhir.dstu3.model.Observation observationResource = new org.hl7.fhir.dstu3.model.Observation(); observationResource.setSubject(new Reference(personEntry.getFullUrl())); observationResource.setContext(new Reference(encounterEntry.getFullUrl())); observationResource.setStatus(ObservationStatus.FINAL); Code code = observation.codes.get(0); observationResource.setCode( mapCodeToCodeableConcept(code, LOINC_URI) ); observationResource.addCategory().addCoding() .setCode(observation.category) .setSystem("http://hl7.org/fhir/observation-category") .setDisplay(observation.category); Type value = null; if (observation.value instanceof Condition) { Code conditionCode = ((HealthRecord.Entry)observation.value).codes.get(0); value = mapCodeToCodeableConcept(conditionCode, SNOMED_URI); } else if (observation.value instanceof String) { value = new StringType((String)observation.value); } else if (observation.value instanceof Number) { value = new Quantity() .setValue(((Number)observation.value).doubleValue()) .setCode(observation.unit) .setSystem("http://unitsofmeasure.org/") .setUnit(observation.unit); } else if (observation.value != null) { throw new IllegalArgumentException("unexpected observation value class: " + observation.value.getClass().toString() + "; " + observation.value); } if (value != null) { observationResource.setValue(value); } observationResource.setEffective(convertFhirDateTime(observation.start, true)); observationResource.setIssued(new Date(observation.start)); BundleEntryComponent entry = newEntry(bundle, observationResource); observation.fullUrl = entry.getFullUrl(); return entry; } /** * Map the given Procedure into a FHIR Procedure resource, and add it to the given Bundle. * @param personEntry The Person entry * @param bundle Bundle to add to * @param encounterEntry The current Encounter entry * @param procedure The Procedure * @param claimResource * @param sequence * @return The added Entry */ private static BundleEntryComponent procedure(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Procedure procedure) { org.hl7.fhir.dstu3.model.Procedure procedureResource = new org.hl7.fhir.dstu3.model.Procedure(); procedureResource.setSubject(new Reference(personEntry.getFullUrl())); procedureResource.setContext(new Reference(encounterEntry.getFullUrl())); Code code = procedure.codes.get(0); procedureResource.setCode( mapCodeToCodeableConcept(code, SNOMED_URI) ); if (procedure.stop > 0L) { Date startDate = new Date(procedure.start); Date endDate = new Date(procedure.stop); procedureResource.setPerformed(new Period().setStart(startDate).setEnd(endDate)); } else { procedureResource.setPerformed(convertFhirDateTime(procedure.start, true)); } BundleEntryComponent procedureEntry = newEntry(bundle, procedureResource); // TODO - reason procedure.fullUrl = procedureEntry.getFullUrl(); return procedureEntry; } private static BundleEntryComponent immunization(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, HealthRecord.Entry immunization) { Immunization immResource = new Immunization(); immResource.setStatus(ImmunizationStatus.COMPLETED); immResource.setDate(new Date(immunization.start)); immResource.setVaccineCode(mapCodeToCodeableConcept(immunization.codes.get(0), CVX_URI)); immResource.setNotGiven(false); immResource.setPrimarySource(true); immResource.setPatient(new Reference(personEntry.getFullUrl())); immResource.setEncounter(new Reference(encounterEntry.getFullUrl())); return newEntry(bundle, immResource); } /** * Map the given Medication to a FHIR MedicationRequest resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle Bundle to add the Medication to * @param encounterEntry Current Encounter entry * @param medication The Medication * @return The added Entry */ private static BundleEntryComponent medication(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Medication medication) { MedicationRequest medicationResource = new MedicationRequest(); medicationResource.setSubject(new Reference(personEntry.getFullUrl())); medicationResource.setContext(new Reference(encounterEntry.getFullUrl())); medicationResource.setMedication(mapCodeToCodeableConcept(medication.codes.get(0), RXNORM_URI)); medicationResource.setAuthoredOn(new Date(medication.start)); medicationResource.setIntent(MedicationRequestIntent.ORDER); if (medication.stop > 0L) { medicationResource.setStatus(MedicationRequestStatus.STOPPED); } else { medicationResource.setStatus(MedicationRequestStatus.ACTIVE); } // TODO - prescription details & reason BundleEntryComponent medicationEntry = newEntry(bundle, medicationResource); //create new claim for medication medicationClaim(personEntry, bundle, encounterEntry, medicationEntry); return medicationEntry; } /** * Map the given Report to a FHIR DiagnosticReport resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle Bundle to add the Report to * @param encounterEntry Current Encounter entry * @param report The Report * @return The added Entry */ private static BundleEntryComponent report(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, Report report) { DiagnosticReport reportResource = new DiagnosticReport(); reportResource.setStatus(DiagnosticReportStatus.FINAL); reportResource.setCode(mapCodeToCodeableConcept(report.codes.get(0), LOINC_URI)); reportResource.setSubject(new Reference(personEntry.getFullUrl())); reportResource.setContext(new Reference(encounterEntry.getFullUrl())); reportResource.setEffective(convertFhirDateTime(report.start, true)); reportResource.setIssued(new Date(report.start)); for(Observation observation : report.observations) { Reference reference = new Reference(observation.fullUrl); reference.setDisplay(observation.codes.get(0).display); reportResource.addResult(reference); } return newEntry(bundle, reportResource); } /** * Map the given CarePlan to a FHIR CarePlan resource, and add it to the given Bundle. * @param personEntry The Entry for the Person * @param bundle Bundle to add the CarePlan to * @param encounterEntry Current Encounter entry * @param carePlan The CarePlan to map to FHIR and add to the bundle * @return The added Entry */ private static BundleEntryComponent careplan(BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry, CarePlan carePlan) { org.hl7.fhir.dstu3.model.CarePlan careplanResource = new org.hl7.fhir.dstu3.model.CarePlan(); careplanResource.setSubject(new Reference(personEntry.getFullUrl())); careplanResource.setContext(new Reference(encounterEntry.getFullUrl())); Code code = carePlan.codes.get(0); careplanResource.addCategory( mapCodeToCodeableConcept(code, SNOMED_URI) ); CarePlanActivityStatus activityStatus; GoalStatus goalStatus; Period period = new Period().setStart(new Date(carePlan.start)); careplanResource.setPeriod(period); if (carePlan.stop > 0L) { period.setEnd(new Date(carePlan.stop)); careplanResource.setStatus(CarePlanStatus.COMPLETED); activityStatus = CarePlanActivityStatus.COMPLETED; goalStatus = GoalStatus.ACHIEVED; } else { careplanResource.setStatus(CarePlanStatus.ACTIVE); activityStatus = CarePlanActivityStatus.INPROGRESS; goalStatus = GoalStatus.INPROGRESS; } // TODO - goals, activities, reasons return newEntry(bundle, careplanResource); } /** * Convert the timestamp into a FHIR DateType or DateTimeType. * * @param datetime Timestamp * @param time If true, return a DateTime; if false, return a Date. * @return a DateType or DateTimeType representing the given timestamp */ private static Type convertFhirDateTime(long datetime, boolean time) { Date date = new Date(datetime); if (time) { return new DateTimeType(date); } else { return new DateType(date); } } /** * Helper function to convert a Code into a CodeableConcept. * Takes an optional system, which replaces the Code.system in the resulting CodeableConcept if not null. * * @param from The Code to create a CodeableConcept from. * @param system The system identifier, such as a URI. Optional; may be null. * @return The converted CodeableConcept */ private static CodeableConcept mapCodeToCodeableConcept(Code from, String system) { CodeableConcept to = new CodeableConcept(); if (from.display != null) { to.setText(from.display); } Coding coding = new Coding(); coding.setCode(from.code); coding.setDisplay(from.display); if (system == null) { coding.setSystem(from.system); } else { coding.setSystem(system); } to.addCoding(coding); return to; } /** * Helper function to create an Entry for the given Resource within the given Bundle. * Sets the resourceID to a random UUID, sets the entry's fullURL to that resourceID, * and adds the entry to the bundle. * * @param bundle The Bundle to add the Entry to * @param resource Resource the new Entry should contain * @return the created Entry */ private static BundleEntryComponent newEntry(Bundle bundle, Resource resource) { BundleEntryComponent entry = bundle.addEntry(); String resourceID = UUID.randomUUID().toString(); resource.setId(resourceID); entry.setFullUrl("urn:uuid:" + resourceID); entry.setResource(resource); return entry; } }
fix claim amount
src/main/java/org/mitre/synthea/export/FhirStu3.java
fix claim amount
<ide><path>rc/main/java/org/mitre/synthea/export/FhirStu3.java <ide> } <ide> <ide> /** <del> * ... <del> * @param personEntry The Entry for the Person <del> * @param bundle The Bundle to add to <del> * @param encounterEntry The current Encounter entry <del> * @param claim The Claim <del> * @return The added Entry <del> */ <add> * Create an entry for the given Claim, which references a Medication. <add> * @param personEntry Entry for the person <add> * @param bundle The Bundle to add to <add> * @param encounterEntry The current Encounter <add> * @param claim the Claim object <add> * @param medicationEntry The Entry for the Medication object, previously created <add> * @return the added Entry <add> */ <ide> private static BundleEntryComponent medicationClaim(BundleEntryComponent personEntry, Bundle bundle, <del> BundleEntryComponent encounterEntry, BundleEntryComponent medicationEntry) <add> BundleEntryComponent encounterEntry, Claim claim, BundleEntryComponent medicationEntry) <ide> { <ide> org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim(); <ide> org.hl7.fhir.dstu3.model.Encounter encounterResource = (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource(); <ide> //add prescription. <ide> claimResource.setPrescription(new Reference(medicationEntry.getFullUrl())); <ide> <del> //cost of prescription currently set to $255.00 <del> double medCost = 255.0; <del> org.hl7.fhir.dstu3.model.Money moneyResource = new org.hl7.fhir.dstu3.model.Money(); <del> moneyResource.setValue(medCost); <add> Money moneyResource = new Money(); <add> moneyResource.setValue(claim.total()); <ide> claimResource.setTotal(moneyResource); <ide> <ide> return newEntry(bundle, claimResource); <ide> } <ide> <del> <add> /** <add> * Create an entry for the given Claim, associated to an Encounter <add> * @param personEntry Entry for the person <add> * @param bundle The Bundle to add to <add> * @param encounterEntry The current Encounter <add> * @param claim the Claim object <add> * @return the added Entry <add> */ <ide> private static BundleEntryComponent encounterClaim(BundleEntryComponent personEntry, Bundle bundle, <ide> BundleEntryComponent encounterEntry, <ide> Claim claim) <ide> return newEntry(bundle, claimResource); <ide> } <ide> <del> <del> <ide> /** <ide> * Map the Condition into a FHIR Condition resource, and add it to the given Bundle. <ide> * @param personEntry The Entry for the Person <ide> <ide> BundleEntryComponent medicationEntry = newEntry(bundle, medicationResource); <ide> //create new claim for medication <del> medicationClaim(personEntry, bundle, encounterEntry, medicationEntry); <add> medicationClaim(personEntry, bundle, encounterEntry, medication.claim, medicationEntry); <ide> <ide> return medicationEntry; <ide> }
JavaScript
agpl-3.0
c098de37f37daccfcbdeeee2b2737f5da5a94f65
0
tagspaces/tagspaces,tagspaces/tagspaces,cbop-dev/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,tagspaces/tagspaces,cbop-dev/tagspaces,cbop-dev/tagspaces,tagspaces/tagspaces
/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved. * Use of this source code is governed by a AGPL3 license that * can be found in the LICENSE file. */ /* global define, Handlebars, isNode, isFirefox */ define(function(require, exports, module) { 'use strict'; console.log('Loading core.ui.js ...'); var TSCORE = require('tscore'); var TSPOSTIO = require("tspostioapi"); var fileContent; var fileType; var showWaitingDialog = function(message, title) { if (!title) { title = $.i18n.t('ns.dialogs:titleWaiting'); } if (!message) { message = 'No Message to Display.'; } var waitingModal = $('#waitingDialog'); waitingModal.find('#waitingHeader').text(title); waitingModal.find('#waitingMessage').text(message); waitingModal.modal({ backdrop: 'static', show: true }); }; var hideWaitingDialog = function(message, title) { // $('#waitingDialog').modal('hide'); }; var showSuccessDialog = function(message) { if (!message) { return; } var n = noty({ text: message, layout: 'bottomCenter', theme: 'relax', type: 'success', animation: { open: 'animated pulse', close: 'animated flipOutX', easing: 'swing', speed: 500 }, timeout: 4000, maxVisible: 1, closeWith: ['button', 'click'], }); }; var showAlertDialog = function(message, title) { if (!title) { title = $.i18n.t('ns.dialogs:titleAlert'); } if (!message) { message = 'No Message to Display.'; } var n = noty({ text: "<strong>" + title + "</strong><br>" + message, layout: 'bottomCenter', theme: 'relax', type: 'warning', animation: { open: 'animated pulse', close: 'animated flipOutX', easing: 'swing', speed: 500 }, timeout: 6000, maxVisible: 4, closeWith: ['button', 'click'], }); /*var alertModal = $('#alertDialog'); alertModal.find('h4').text(title); alertModal.find('.modal-body').empty(); alertModal.find('.modal-body').text(message); alertModal.find('#okButton').off('click').click(function() { alertModal.modal('hide'); }); // Focusing the ok button by default alertModal.off('shown.bs.modal'); alertModal.on('shown.bs.modal', function() { alertModal.find('#okButton').focus(); }); alertModal.modal({ backdrop: 'static', show: true });*/ }; var showConfirmDialog = function(title, message, okCallback, cancelCallback, confirmShowNextTime) { if (!title) { title = $.i18n.t('ns.dialogs:titleConfirm'); } if (!message) { message = 'No Message to Display.'; } var confirmModal = $('#confirmDialog'); if (confirmShowNextTime) { confirmModal.find('#showThisDialogAgain').prop('checked', true); } else { confirmModal.find('#showThisDialogAgainContainer').hide(); } confirmModal.find('h4').text(title); confirmModal.find('#dialogContent').text(message); confirmModal.find('#confirmButton').off('click').click(function() { okCallback(confirmModal.find('#showThisDialogAgain').prop('checked')); confirmModal.modal('hide'); }); // Focusing the confirm button by default confirmModal.off('shown.bs.modal'); confirmModal.on('shown.bs.modal', function() { confirmModal.find('#confirmButton').focus(); }); confirmModal.find('#cancelButton').off('click').click(function() { if (cancelCallback !== undefined) { cancelCallback(); } confirmModal.modal('hide'); }); confirmModal.modal({ backdrop: 'static', show: true }); }; var showFileCreateDialog = function() { fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file fileType = 'txt'; $('#newFileNameTags').select2('data', null); $('#newFileNameTags').select2({ multiple: true, tags: TSCORE.Config.getAllTags(), tokenSeparators: [ ',', ' ' ], minimumInputLength: 2, selectOnBlur: true }); $('#newFileName').val(''); $('#tagWithCurrentDate').prop('checked', false); $('#txtFileTypeButton').button('toggle'); $('#formFileCreate').validator(); $('#formFileCreate').submit(function(e) { e.preventDefault(); }); $('#formFileCreate').on('invalid.bs.validator', function() { $('#fileCreateConfirmButton').prop('disabled', true); }); $('#formFileCreate').on('valid.bs.validator', function() { $('#fileCreateConfirmButton').prop('disabled', false); }); $('#dialogFileCreate').on('shown.bs.modal', function() { $('#newFileName').select2().focus(); }); $('#dialogFileCreate').modal({ backdrop: 'static', show: true }); $('#dialogFileCreate').draggable({ handle: ".modal-header" }); }; var showFileRenameDialog = function(filePath) { $('#renamedFileName').attr('filepath', filePath); $('#renamedFileName').val(TSCORE.TagUtils.extractFileName(filePath)); $('#formFileRename').validator(); $('#formFileRename').submit(function(e) { e.preventDefault(); if ($('#renameFileButton').prop('disabled') === false) { $('#renameFileButton').click(); } }); $('#formFileRename').on('invalid.bs.validator', function() { $('#renameFileButton').prop('disabled', true); }); $('#formFileRename').on('valid.bs.validator', function() { $('#renameFileButton').prop('disabled', false); }); $('#dialogFileRename').on('shown.bs.modal', function() { $('#renamedFileName').focus(); }); $('#dialogFileRename').modal({ backdrop: 'static', show: true }); $('#dialogFileRename').draggable({ handle: ".modal-header" }); }; var showFileDeleteDialog = function(filePath) { console.log('Deleting file...'); var dlgConfirmMsgId = 'ns.dialogs:fileDeleteContentConfirm'; if (TSCORE.Config.getUseTrashCan()) { dlgConfirmMsgId = 'ns.pro:trashDeleteContentConfirm'; } TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:fileDeleteTitleConfirm'), $.i18n.t(dlgConfirmMsgId, { filePath: filePath }), function() { TSCORE.IO.deleteFilePromise(filePath).then(function() { TSPOSTIO.deleteElement(filePath); }, function(error) { TSCORE.hideLoadingAnimation(); TSCORE.showAlertDialog("Deleting file " + filePath + " failed."); console.error("Deleting file " + filePath + " failed " + error); } ); }); }; var showTagEditDialog = function() { $('#newTagName').val(TSCORE.selectedTag); $('#formEditTag').validator(); $('#formEditTag').submit(function(e) { e.preventDefault(); if ($('#editTagButton').prop('disabled') === false) { $('#editTagButton').click(); } }); $('#formEditTag').on('invalid.bs.validator', function() { $('#editTagButton').prop('disabled', true); }); $('#formEditTag').on('valid.bs.validator', function() { $('#editTagButton').prop('disabled', false); }); $('#dialogEditTag').on('shown.bs.modal', function() { $('#newTagName').focus(); }); $('#dialogEditTag').modal({ backdrop: 'static', show: true }); $('#dialogEditTag').draggable({ handle: ".modal-header" }); }; var showDirectoryBrowserDialog = function(path) { require([ 'text!templates/DirectoryBrowserDialog.html', 'tsdirectorybrowser' ], function(uiTPL, controller) { TSCORE.directoryBrowser = controller; if ($('#directoryBrowserDialog').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate()); TSCORE.directoryBrowser.initUI(); } $('#directoryBrowserDialog').i18n(); TSCORE.IOUtils.listSubDirectories(path); }); }; var showOptionsDialog = function() { require([ 'text!templates/OptionsDialog.html', 'tsoptions' ], function(uiTPL, controller) { if ($('#dialogOptions').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate({isProVersion: TSCORE.PRO ? true : false})); controller.initUI(); } $('#dialogOptions').i18n(); controller.reInitUI(); }); }; var showWelcomeDialog = function() { startGettingStartedTour(); }; var startGettingStartedTour = function() { var tsGettingStarted = require('tsgettingstarted'); tsGettingStarted.startTour(); }; var showMoveCopyFilesDialog = function() { require(['text!templates/MoveCopyFilesDialog.html'], function(uiTPL) { if ($('#dialogMoveCopyFiles').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate()); $('#moveFilesButton').click(function(e) { e.preventDefault(); // TODO move to ioutils TSCORE.showWaitingDialog('Please wait, while files are being renamed.'); var newFilePath, filePath; var fileOperations = []; for (var i = 0; i < TSCORE.selectedFiles.length; i++) { newFilePath = $('#moveCopyDirectoryPath').val() + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]); filePath = TSCORE.selectedFiles[i]; fileOperations.push(TSCORE.IO.renameFilePromise(filePath, newFilePath)); } Promise.all(fileOperations).then(function(success) { // TODO handle moving sidecar files TSCORE.hideWaitingDialog(); TSCORE.navigateToDirectory(TSCORE.currentPath); TSCORE.showSuccessDialog("Files successfully moved"); }, function(err) { TSCORE.hideWaitingDialog(); TSCORE.showAlertDialog("Renaming files failed"); }); }); $('#copyFilesButton').click(function(e) { e.preventDefault(); TSCORE.showWaitingDialog('Please wait, while files are being copied.'); var newFilePath, filePath; var fileOperations = []; for (var i = 0; i < TSCORE.selectedFiles.length; i++) { var newFilePath = $('#moveCopyDirectoryPath').val() + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]); var filePath = TSCORE.selectedFiles[i]; fileOperations.push(TSCORE.IO.copyFilePromise(filePath, newFilePath)); } Promise.all(fileOperations).then(function(success) { // TODO handle copying sidecar files TSCORE.hideWaitingDialog(); TSCORE.showSuccessDialog("Files successfully copied"); }, function(err) { TSCORE.hideWaitingDialog(); TSCORE.showAlertDialog("Copying files failed"); }); }); $('#selectDirectoryMoveCopyDialog').click(function(e) { e.preventDefault(); TSCORE.IO.selectDirectory(); }); } $('#moveCopyDirectoryPath').val(TSCORE.currentPath); $('#moveCopyFileList').children().remove(); for (var i = 0; i < TSCORE.selectedFiles.length; i++) { $('#moveCopyFileList').append($('<p>', { text: TSCORE.selectedFiles[i] })); } $('#dialogMoveCopyFiles').i18n(); $('#dialogMoveCopyFiles').draggable({ handle: '.modal-header' }); $('#dialogMoveCopyFiles').modal({ backdrop: 'static', show: true }); $('#dialogMoveCopyFiles').draggable({ handle: ".modal-header" }); console.log('Selected files: ' + TSCORE.selectedFiles); }); }; var showAboutDialog = function() { $('#dialogAboutTS').modal({ backdrop: 'static', show: true }); $('#dialogAboutTS').draggable({ handle: ".modal-header" }); }; var initUI = function() { if (TSCORE.PRO) { //TSCORE.PRO.sayHi(); } $('#appVersion').text(TSCORE.Config.DefaultSettings.appVersion + '.' + TSCORE.Config.DefaultSettings.appBuild); $('#appVersion').attr('title', 'BuildID: ' + TSCORE.Config.DefaultSettings.appVersion + '.' + TSCORE.Config.DefaultSettings.appBuild + '.' + TSCORE.Config.DefaultSettings.appBuildID); // prevent default behavior from changing page on dropped file $(document).on('drop dragend dragenter dragleave dragover', function(event) { // dragstart drag event.preventDefault(); }); // Managing droping of files in the perspectives if (isNode) { $('#viewContainers').on('dragenter', function(event) { event.preventDefault(); $('#viewContainers').attr('style', 'border:2px dashed #098ddf'); }); $('#viewContainers').on('dragleave', function(event) { event.preventDefault(); $('#viewContainers').attr('style', 'border:0px'); }); $('#viewContainers').on('drop', function(event) { //event.preventDefault(); if (event.originalEvent.dataTransfer !== undefined) { var files = event.originalEvent.dataTransfer.files; TSCORE.IO.focusWindow(); $('#viewContainers').attr('style', 'border:0px'); TSCORE.PerspectiveManager.clearSelectedFiles(); var filePath; if (files !== undefined && files.length > 0) { for (var i = 0; i < files.length; i++) { filePath = files[i].path; if (filePath.length > 1) { //console.log("Selecting files: "+JSON.stringify(files[i])); TSCORE.selectedFiles.push(filePath); //{"webkitRelativePath":"","path\":"/home/na/Desktop/Kola2","lastModifiedDate":"2014-07-11T16:40:52.000Z","name":"Kola2","type":"","size":4096} } } } if (TSCORE.selectedFiles.length > 0) { showMoveCopyFilesDialog(); } } }); } platformTuning(); var addFileInputName; $('#addFileInput').on('change', function(selection) { //console.log("Selected File: "+$("#addFileInput").val()); var file = selection.currentTarget.files[0]; //console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0])); addFileInputName = decodeURIComponent(file.name); var reader = new FileReader(); reader.onload = onFileReadComplete; reader.readAsArrayBuffer(file); }); function onFileReadComplete(event) { console.log('Content on file read complete: ' + JSON.stringify(event)); //change name for ios fakepath if (isCordovaiOS) { var parts = addFileInputName.split('.'); var ext = (parts.length > 1) ? '.' + parts.pop() : ''; addFileInputName = TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + ext; } var filePath = TSCORE.currentPath + TSCORE.dirSeparator + addFileInputName; TSCORE.IO.saveBinaryFilePromise(filePath, event.currentTarget.result).then(function() { TSPOSTIO.saveBinaryFile(filePath); }, function(error) { TSCORE.hideLoadingAnimation(); TSCORE.showAlertDialog("Saving " + filePath + " failed."); console.error("Save to file " + filePath + " failed " + error); }); addFileInputName = undefined; } $('#openLeftPanel').click(function() { TSCORE.openLeftPanel(); }); $('#closeLeftPanel').click(function() { TSCORE.closeLeftPanel(); }); $('#txtFileTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); fileContent = TSCORE.Config.getNewTextFileContent(); fileType = 'txt'; }); $('#htmlFileTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); fileContent = TSCORE.Config.getNewHTMLFileContent(); fileType = 'html'; }); $('#mdFileTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); fileContent = TSCORE.Config.getNewMDFileContent(); fileType = 'md'; }); $('#fileCreateConfirmButton').click(function() { var fileTags = ''; var rawTags = $('#newFileNameTags').val().split(','); rawTags.forEach(function(value, index) { if (index === 0) { fileTags = value; } else { fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value; } }); if ($('#tagWithCurrentDate').prop('checked')) { if (fileTags.length < 1) { fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date()); } else { fileTags = fileTags + TSCORE.Config.getTagDelimiter() + TSCORE.TagUtils.formatDateTime4Tag(new Date()); } } if (fileTags.length > 0) { fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer; } var filePath = TSCORE.currentPath + TSCORE.dirSeparator + $('#newFileName').val() + fileTags + '.' + fileType; TSCORE.IO.saveFilePromise(filePath, fileContent).then(function() { TSPOSTIO.saveTextFile(filePath, isNewFile); }, function(error) { TSCORE.hideLoadingAnimation(); TSCORE.showAlertDialog("Saving " + filePath + " failed."); console.error("Save to file " + filePath + " failed " + error); }); }); $('#renameFileButton').click(function() { var initialFilePath = $('#renamedFileName').attr('filepath'); var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(initialFilePath); var newFilePath = containingDir + TSCORE.dirSeparator + $('#renamedFileName').val(); TSCORE.IO.renameFilePromise(initialFilePath, newFilePath).then(function(success) { TSCORE.hideWaitingDialog(); TSPOSTIO.renameFile(initialFilePath, newFilePath); }, function(err) { TSCORE.hideWaitingDialog(); TSCORE.showAlertDialog(err); }); }); // Edit Tag Dialog $('#plainTagTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); TSCORE.selectedTag, $('#newTagName').datepicker('destroy').val(''); }); $('#dateTagTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); TSCORE.selectedTag, $('#newTagName').datepicker({ showWeek: true, firstDay: 1, dateFormat: 'yymmdd' }); }); $('#currencyTagTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); TSCORE.selectedTag, $('#newTagName').datepicker('destroy').val('XEUR'); }); $('#editTagButton').click(function() { TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $('#newTagName').val()); }); // End Edit Tag Dialog $('#startNewInstanceBack').click(function() { if (!isCordova) { window.open(window.location.href, '_blank'); } }); $('#aboutDialogBack').click(function() { if (TSCORE.PRO) { $('#aboutIframe').attr('src', 'pro/about.html'); } else { $('#aboutIframe').attr('src', 'about.html'); } }); // Open About Dialog $('#openAboutBox').click(function() { $('#dialogAbout').modal({ backdrop: 'static', show: true }); $('#dialogAbout').draggable({ handle: ".modal-header" }); }); // Open Options Dialog $('#openOptions').click(function() { showOptionsDialog(); }); // File Menu $('#fileMenuAddTag').click(function() { TSCORE.showAddTagsDialog(); }); $('#fileMenuOpenFile').click(function() { TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]); }); $('#fileMenuOpenNatively').click(function() { TSCORE.IO.openFile(TSCORE.selectedFiles[0]); }); $('#fileMenuSendTo').click(function() { TSCORE.IO.sendFile(TSCORE.selectedFiles[0]); }); $('#fileMenuOpenDirectory').click(function() { TSCORE.IO.openDirectory(TSCORE.currentPath); }); $('#fileMenuRenameFile').click(function() { TSCORE.showFileRenameDialog(TSCORE.selectedFiles[0]); }); $('#fileMenuMoveCopyFile').click(function() { TSCORE.showMoveCopyFilesDialog(); }); $('#fileMenuDeleteFile').click(function() { TSCORE.showFileDeleteDialog(TSCORE.selectedFiles[0]); }); $('#fileOpenProperties').click(function() {}); // End File Menu $('#showLocations').click(function() { showLocationsPanel(); }); $('#showTagGroups').click(function() { showTagsPanel(); }); $('#contactUs').click(function() { showContactUsPanel(); }); // Hide the tagGroupsContent or locationContent by default $('#locationContent').hide(); // Search UI $('#searchToolbar').on('click', '#closeSearchOptionButton', function() { $('#searchBox').popover('hide'); }); $('#searchToolbar').on('click', '#includeSubfoldersOption', function() { var searchQuery = $('#searchBox').val(); if (searchQuery.indexOf('?') === 0) { $('#includeSubfoldersOption i').removeClass('fa-toggle-on').addClass('fa-toggle-off'); $('#searchBox').val(searchQuery.substring(1, searchQuery.length)); } else { $('#includeSubfoldersOption i').removeClass('fa-toggle-off').addClass('fa-toggle-on'); $('#searchBox').val('?' + searchQuery); } }); $('#searchBox').on('show.bs.popover', function() { var searchQuery = $('#searchBox').val(); if (searchQuery.indexOf('?') === 0) { $('#includeSubfoldersOption i').removeClass('fa-toggle-off').addClass('fa-toggle-on'); } else { $('#includeSubfoldersOption i').removeClass('fa-toggle-on').addClass('fa-toggle-off'); } }); $('#searchBox').on('shown.bs.popover', function() { $('.popover').i18n(); }); $('#searchBox').prop('disabled', true) /*.focus(function() { $("#searchOptions").show(); })*/ .popover({ html: true, placement: 'bottom', trigger: 'focus', content: $('#searchOptions').html() }).keyup(function(e) { // On enter fire the search if (e.keyCode === 13) { $('#clearFilterButton').addClass('filterOn'); TSCORE.PerspectiveManager.redrawCurrentPerspective(); $('#searchOptions').hide(); $('#searchButton').focus(); } else if (e.keyCode == 27) { cancelSearch(); } else { TSCORE.Search.nextQuery = this.value; } if (this.value.length === 0) { TSCORE.Search.nextQuery = this.value; $('#clearFilterButton').removeClass('filterOn'); TSCORE.PerspectiveManager.redrawCurrentPerspective(); } }).blur(function() { if (this.value.length === 0) { $('#clearFilterButton').removeClass('filterOn'); TSCORE.PerspectiveManager.redrawCurrentPerspective(); } }); $('#showSearchButton').on('click', function() { TSCORE.showSearchArea(); }); $('#searchButton').prop('disabled', true).click(function(evt) { evt.preventDefault(); $('#clearFilterButton').addClass('filterOn'); $('#searchOptions').hide(); TSCORE.PerspectiveManager.redrawCurrentPerspective(); $('#searchBox').popover('hide'); }); $('#clearFilterButton').prop('disabled', true).click(function(e) { e.preventDefault(); cancelSearch(); }); // Search UI END $('#perspectiveSwitcherButton').prop('disabled', true); var $contactUsContent = $('#contactUsContent'); $contactUsContent.on('click', '#openHints', showWelcomeDialog); $contactUsContent.on('click', '#openUservoice', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openGooglePlay', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openAppleAppStore', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openWhatsnew', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openGitHubIssues', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#helpUsTranslate', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openTwitter', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openTwitter2', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openGooglePlus', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openFacebook', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openSupportUs', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $('#newVersionMenu').on('click', '.whatsNewLink', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); // Hide drop downs by click and drag $(document).click(function() { TSCORE.hideAllDropDownMenus(); }); }; function cancelSearch() { clearSearchFilter(); $('#searchBox').popover('hide'); $('#searchToolbar').hide(); $('#showSearchButton').show(); // Restoring initial dir listing without subdirectories TSCORE.IO.listDirectoryPromise(TSCORE.currentPath).then( function(entries) { TSPOSTIO.listDirectory(entries); }, function(err) { TSPOSTIO.errorOpeningPath(); console.warn("Error listing directory" + err); } ); } function showSearchArea() { $('#searchToolbar').show(); //.addClass('animated bounceIn'); $('#showSearchButton').hide(); $('#searchBox').focus(); } // Handle external links function openLinkExternally(url) { if (isNode) { gui.Shell.openExternal(url); } else { // _system is needed for cordova window.open(url, '_system'); } } function clearSearchFilter() { $('#searchOptions').hide(); $('#searchBox').val(''); $('#clearFilterButton').removeClass('filterOn'); TSCORE.Search.nextQuery = ''; } function disableTopToolbar() { $('#perspectiveSwitcherButton').prop('disabled', true); $('#searchBox').prop('disabled', true); $('#searchButton').prop('disabled', true); $('#clearFilterButton').prop('disabled', true); } function enableTopToolbar() { $('#perspectiveSwitcherButton').prop('disabled', false); $('#searchBox').prop('disabled', false); $('#searchButton').prop('disabled', false); $('#clearFilterButton').prop('disabled', false); } function platformTuning() { if (isCordova) { $('#directoryMenuOpenDirectory').parent().hide(); $('#fileMenuOpenDirectory').parent().hide(); $('#openDirectory').parent().hide(); $('#downloadFile').parent().hide(); $('#openFileInNewWindow').hide(); $('#openGooglePlay').hide(); $('.cancelButton').hide(); } else if (isCordovaiOS) { $('#fullscreenFile').parent().hide(); } else if (isChrome) { $('#directoryMenuOpenDirectory').parent().hide(); $('#fileMenuOpenDirectory').parent().hide(); $('#fileMenuOpenNatively').parent().hide(); $('#openDirectory').parent().hide(); $('#openNatively').hide(); } else if (isWeb) { $('#directoryMenuOpenDirectory').parent().hide(); $('#fileMenuOpenDirectory').parent().hide(); $('#fileMenuOpenNatively').parent().hide(); $('#openDirectory').parent().hide(); $('#openNatively').hide(); } else if (isFirefox) { $('#openNatively').hide(); $('#fileMenuOpenNatively').parent().hide(); } else if (isNode) { $('#openFileInNewWindow').hide(); //handling window maximization var nwwin = gui.Window.get(); nwwin.on('maximize', function() { TSCORE.Config.setIsWindowMaximized(true); TSCORE.Config.saveSettings(); }); nwwin.on('unmaximize', function() { TSCORE.Config.setIsWindowMaximized(false); TSCORE.Config.saveSettings(); }); // Disabling automatic maximazation of the main window //if(TSCORE.Config.getIsWindowMaximized()){ // nwwin.maximize(); //} } // Disable send to feature on all platforms except android cordova if (!isCordova) { $('#sendFile').hide(); $('#fileMenuSendTo').hide(); } if (isOSX) { $('body').addClass('osx'); } } var showContextMenu = function(menuId, sourceObject) { var leftPos = sourceObject.offset().left; var topPos = sourceObject.offset().top; if (sourceObject.offset().top + sourceObject.height() + $(menuId).height() > window.innerHeight) { topPos = window.innerHeight - $(menuId).height(); leftPos = sourceObject.offset().left + 15; } if (sourceObject.offset().left + sourceObject.width() + $(menuId).width() > window.innerWidth) { leftPos = window.innerWidth - $(menuId).width(); } $(menuId).css({ display: 'block', left: leftPos, top: topPos }); }; var hideAllDropDownMenus = function() { $('#tagGroupMenu').hide(); $('#tagTreeMenu').hide(); $('#directoryMenu').hide(); $('#tagMenu').hide(); $('#fileMenu').hide(); $('.dirAltNavMenu').hide(); }; var showLocationsPanel = function() { TSCORE.openLeftPanel(); $('#tagGroupsContent').hide(); $('#contactUsContent').hide(); $('#locationContent').show(); $('#showTagGroups').removeClass('active'); $('#contactUs').removeClass('active'); $('#showLocations').addClass('active'); }; var showTagsPanel = function() { TSCORE.openLeftPanel(); $('#locationContent').hide(); $('#contactUsContent').hide(); $('#tagGroupsContent').show(); $('#showLocations').removeClass('active'); $('#contactUs').removeClass('active'); $('#showTagGroups').addClass('active'); }; var showContactUsPanel = function() { TSCORE.openLeftPanel(); $('#locationContent').hide(); $('#tagGroupsContent').hide(); $('#contactUsContent').show(); $('#showLocations').removeClass('active'); $('#showTagGroups').removeClass('active'); $('#contactUs').addClass('active'); }; function createHTMLFile() { var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.html'; createNewTextFile(filePath, TSCORE.Config.getNewHTMLFileContent()); } function createMDFile() { var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.md'; createNewTextFile(filePath, TSCORE.Config.getNewMDFileContent()); } function createTXTFile() { var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.txt'; createNewTextFile(filePath, TSCORE.Config.getNewTextFileContent()); } function createNewTextFile(filePath, content) { TSCORE.IO.saveFilePromise(filePath, content).then(function(isNewFile) { TSPOSTIO.saveTextFile(filePath, isNewFile); }, function(error) { TSCORE.hideLoadingAnimation(); console.error("Save to file " + filePath + " failed " + error); TSCORE.showAlertDialog("Saving " + filePath + " failed."); }); } // Public API definition exports.showContextMenu = showContextMenu; exports.initUI = initUI; exports.clearSearchFilter = clearSearchFilter; exports.openLinkExternally = openLinkExternally; exports.enableTopToolbar = enableTopToolbar; exports.disableTopToolbar = disableTopToolbar; exports.hideWaitingDialog = hideWaitingDialog; exports.showWaitingDialog = showWaitingDialog; exports.showAlertDialog = showAlertDialog; exports.showSuccessDialog = showSuccessDialog; exports.showConfirmDialog = showConfirmDialog; exports.showFileRenameDialog = showFileRenameDialog; exports.showFileCreateDialog = showFileCreateDialog; exports.showFileDeleteDialog = showFileDeleteDialog; exports.showWelcomeDialog = showWelcomeDialog; exports.startGettingStartedTour = startGettingStartedTour; exports.showTagEditDialog = showTagEditDialog; exports.showOptionsDialog = showOptionsDialog; exports.showAboutDialog = showAboutDialog; exports.showLocationsPanel = showLocationsPanel; exports.showTagsPanel = showTagsPanel; exports.showContactUsPanel = showContactUsPanel; exports.showDirectoryBrowserDialog = showDirectoryBrowserDialog; exports.showMoveCopyFilesDialog = showMoveCopyFilesDialog; exports.hideAllDropDownMenus = hideAllDropDownMenus; exports.createHTMLFile = createHTMLFile; exports.createMDFile = createMDFile; exports.createTXTFile = createTXTFile; exports.showSearchArea = showSearchArea; });
data/js/core.ui.js
/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved. * Use of this source code is governed by a AGPL3 license that * can be found in the LICENSE file. */ /* global define, Handlebars, isNode, isFirefox */ define(function(require, exports, module) { 'use strict'; console.log('Loading core.ui.js ...'); var TSCORE = require('tscore'); var TSPOSTIO = require("tspostioapi"); var fileContent; var fileType; var showWaitingDialog = function(message, title) { if (!title) { title = $.i18n.t('ns.dialogs:titleWaiting'); } if (!message) { message = 'No Message to Display.'; } var waitingModal = $('#waitingDialog'); waitingModal.find('#waitingHeader').text(title); waitingModal.find('#waitingMessage').text(message); waitingModal.modal({ backdrop: 'static', show: true }); }; var hideWaitingDialog = function(message, title) { // $('#waitingDialog').modal('hide'); }; var showSuccessDialog = function(message) { if (!message) { return; } var n = noty({ text: message, layout: 'bottomCenter', theme: 'relax', type: 'success', animation: { open: 'animated pulse', close: 'animated flipOutX', easing: 'swing', speed: 500 }, timeout: 4000, maxVisible: 1, closeWith: ['button', 'click'], }); }; var showAlertDialog = function(message, title) { if (!title) { title = $.i18n.t('ns.dialogs:titleAlert'); } if (!message) { message = 'No Message to Display.'; } var n = noty({ text: "<strong>" + title + "</strong><br>" + message, layout: 'bottomCenter', theme: 'relax', type: 'warning', animation: { open: 'animated pulse', close: 'animated flipOutX', easing: 'swing', speed: 500 }, timeout: 6000, maxVisible: 4, closeWith: ['button', 'click'], }); /*var alertModal = $('#alertDialog'); alertModal.find('h4').text(title); alertModal.find('.modal-body').empty(); alertModal.find('.modal-body').text(message); alertModal.find('#okButton').off('click').click(function() { alertModal.modal('hide'); }); // Focusing the ok button by default alertModal.off('shown.bs.modal'); alertModal.on('shown.bs.modal', function() { alertModal.find('#okButton').focus(); }); alertModal.modal({ backdrop: 'static', show: true });*/ }; var showConfirmDialog = function(title, message, okCallback, cancelCallback, confirmShowNextTime) { if (!title) { title = $.i18n.t('ns.dialogs:titleConfirm'); } if (!message) { message = 'No Message to Display.'; } var confirmModal = $('#confirmDialog'); if (confirmShowNextTime) { confirmModal.find('#showThisDialogAgain').prop('checked', true); } else { confirmModal.find('#showThisDialogAgainContainer').hide(); } confirmModal.find('h4').text(title); confirmModal.find('#dialogContent').text(message); confirmModal.find('#confirmButton').off('click').click(function() { okCallback(confirmModal.find('#showThisDialogAgain').prop('checked')); confirmModal.modal('hide'); }); // Focusing the confirm button by default confirmModal.off('shown.bs.modal'); confirmModal.on('shown.bs.modal', function() { confirmModal.find('#confirmButton').focus(); }); confirmModal.find('#cancelButton').off('click').click(function() { if (cancelCallback !== undefined) { cancelCallback(); } confirmModal.modal('hide'); }); confirmModal.modal({ backdrop: 'static', show: true }); }; var showFileCreateDialog = function() { fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file fileType = 'txt'; $('#newFileNameTags').select2('data', null); $('#newFileNameTags').select2({ multiple: true, tags: TSCORE.Config.getAllTags(), tokenSeparators: [ ',', ' ' ], minimumInputLength: 2, selectOnBlur: true }); $('#newFileName').val(''); $('#tagWithCurrentDate').prop('checked', false); $('#txtFileTypeButton').button('toggle'); $('#formFileCreate').validator(); $('#formFileCreate').submit(function(e) { e.preventDefault(); }); $('#formFileCreate').on('invalid.bs.validator', function() { $('#fileCreateConfirmButton').prop('disabled', true); }); $('#formFileCreate').on('valid.bs.validator', function() { $('#fileCreateConfirmButton').prop('disabled', false); }); $('#dialogFileCreate').on('shown.bs.modal', function() { $('#newFileName').select2().focus(); }); $('#dialogFileCreate').modal({ backdrop: 'static', show: true }); $('#dialogFileCreate').draggable({ handle: ".modal-header" }); }; var showFileRenameDialog = function(filePath) { $('#renamedFileName').attr('filepath', filePath); $('#renamedFileName').val(TSCORE.TagUtils.extractFileName(filePath)); $('#formFileRename').validator(); $('#formFileRename').submit(function(e) { e.preventDefault(); if ($('#renameFileButton').prop('disabled') === false) { $('#renameFileButton').click(); } }); $('#formFileRename').on('invalid.bs.validator', function() { $('#renameFileButton').prop('disabled', true); }); $('#formFileRename').on('valid.bs.validator', function() { $('#renameFileButton').prop('disabled', false); }); $('#dialogFileRename').on('shown.bs.modal', function() { $('#renamedFileName').focus(); }); $('#dialogFileRename').modal({ backdrop: 'static', show: true }); $('#dialogFileRename').draggable({ handle: ".modal-header" }); }; var showFileDeleteDialog = function(filePath) { console.log('Deleting file...'); var dlgConfirmMsgId = 'ns.dialogs:fileDeleteContentConfirm'; if (TSCORE.Config.getUseTrashCan()) { dlgConfirmMsgId = 'ns.pro:trashDeleteContentConfirm'; } TSCORE.showConfirmDialog($.i18n.t('ns.dialogs:fileDeleteTitleConfirm'), $.i18n.t(dlgConfirmMsgId, { filePath: filePath }), function() { TSCORE.IO.deleteFilePromise(filePath).then(function() { TSPOSTIO.deleteElement(filePath); }, function(error) { TSCORE.hideLoadingAnimation(); TSCORE.showAlertDialog("Deleting file " + filePath + " failed."); console.error("Deleting file " + filePath + " failed " + error); } ); }); }; var showTagEditDialog = function() { $('#newTagName').val(TSCORE.selectedTag); $('#formEditTag').validator(); $('#formEditTag').submit(function(e) { e.preventDefault(); if ($('#editTagButton').prop('disabled') === false) { $('#editTagButton').click(); } }); $('#formEditTag').on('invalid.bs.validator', function() { $('#editTagButton').prop('disabled', true); }); $('#formEditTag').on('valid.bs.validator', function() { $('#editTagButton').prop('disabled', false); }); $('#dialogEditTag').on('shown.bs.modal', function() { $('#newTagName').focus(); }); $('#dialogEditTag').modal({ backdrop: 'static', show: true }); $('#dialogEditTag').draggable({ handle: ".modal-header" }); }; var showDirectoryBrowserDialog = function(path) { require([ 'text!templates/DirectoryBrowserDialog.html', 'tsdirectorybrowser' ], function(uiTPL, controller) { TSCORE.directoryBrowser = controller; if ($('#directoryBrowserDialog').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate()); TSCORE.directoryBrowser.initUI(); } $('#directoryBrowserDialog').i18n(); TSCORE.IOUtils.listSubDirectories(path); }); }; var showOptionsDialog = function() { require([ 'text!templates/OptionsDialog.html', 'tsoptions' ], function(uiTPL, controller) { if ($('#dialogOptions').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate({isProVersion: TSCORE.PRO ? true : false})); controller.initUI(); } $('#dialogOptions').i18n(); controller.reInitUI(); }); }; var showWelcomeDialog = function() { startGettingStartedTour(); }; var startGettingStartedTour = function() { var tsGettingStarted = require('tsgettingstarted'); tsGettingStarted.startTour(); }; var showMoveCopyFilesDialog = function() { require(['text!templates/MoveCopyFilesDialog.html'], function(uiTPL) { if ($('#dialogMoveCopyFiles').length < 1) { var uiTemplate = Handlebars.compile(uiTPL); $('body').append(uiTemplate()); $('#moveFilesButton').click(function(e) { e.preventDefault(); TSCORE.showWaitingDialog('Please wait, while files are being renamed.'); var newFilePath, filePath; var fileOperations = []; for (var i = 0; i < TSCORE.selectedFiles.length; i++) { newFilePath = $('#moveCopyDirectoryPath').val() + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]); filePath = TSCORE.selectedFiles[i]; fileOperations.push(TSCORE.IO.renameFilePromise(filePath, newFilePath)); } Promise.all(fileOperations).then(function(success) { // TODO handle moving sidecar files TSCORE.hideWaitingDialog(); TSCORE.navigateToDirectory(TSCORE.currentPath); TSCORE.showSuccessDialog("Files successfully moved"); }, function(err) { TSCORE.hideWaitingDialog(); TSCORE.showAlertDialog("Renaming files failed"); }); }); $('#copyFilesButton').click(function(e) { e.preventDefault(); TSCORE.showWaitingDialog('Please wait, while files are being copied.'); var newFilePath, filePath; var fileOperations = []; for (var i = 0; i < TSCORE.selectedFiles.length; i++) { var newFilePath = $('#moveCopyDirectoryPath').val() + TSCORE.dirSeparator + TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[i]); var filePath = TSCORE.selectedFiles[i]; fileOperations.push(TSCORE.IO.copyFilePromise(filePath, newFilePath)); } Promise.all(fileOperations).then(function(success) { // TODO handle copying sidecar files TSCORE.hideWaitingDialog(); TSCORE.showSuccessDialog("Files successfully copied"); }, function(err) { TSCORE.hideWaitingDialog(); TSCORE.showAlertDialog("Copying files failed"); }); }); $('#selectDirectoryMoveCopyDialog').click(function(e) { e.preventDefault(); TSCORE.IO.selectDirectory(); }); } $('#moveCopyDirectoryPath').val(TSCORE.currentPath); $('#moveCopyFileList').children().remove(); for (var i = 0; i < TSCORE.selectedFiles.length; i++) { $('#moveCopyFileList').append($('<p>', { text: TSCORE.selectedFiles[i] })); } $('#dialogMoveCopyFiles').i18n(); $('#dialogMoveCopyFiles').draggable({ handle: '.modal-header' }); $('#dialogMoveCopyFiles').modal({ backdrop: 'static', show: true }); $('#dialogMoveCopyFiles').draggable({ handle: ".modal-header" }); console.log('Selected files: ' + TSCORE.selectedFiles); }); }; var showAboutDialog = function() { $('#dialogAboutTS').modal({ backdrop: 'static', show: true }); $('#dialogAboutTS').draggable({ handle: ".modal-header" }); }; var initUI = function() { if (TSCORE.PRO) { //TSCORE.PRO.sayHi(); } $('#appVersion').text(TSCORE.Config.DefaultSettings.appVersion + '.' + TSCORE.Config.DefaultSettings.appBuild); $('#appVersion').attr('title', 'BuildID: ' + TSCORE.Config.DefaultSettings.appVersion + '.' + TSCORE.Config.DefaultSettings.appBuild + '.' + TSCORE.Config.DefaultSettings.appBuildID); // prevent default behavior from changing page on dropped file $(document).on('drop dragend dragenter dragleave dragover', function(event) { // dragstart drag event.preventDefault(); }); // Managing droping of files in the perspectives if (isNode) { $('#viewContainers').on('dragenter', function(event) { event.preventDefault(); $('#viewContainers').attr('style', 'border:2px dashed #098ddf'); }); $('#viewContainers').on('dragleave', function(event) { event.preventDefault(); $('#viewContainers').attr('style', 'border:0px'); }); $('#viewContainers').on('drop', function(event) { //event.preventDefault(); if (event.originalEvent.dataTransfer !== undefined) { var files = event.originalEvent.dataTransfer.files; TSCORE.IO.focusWindow(); $('#viewContainers').attr('style', 'border:0px'); TSCORE.PerspectiveManager.clearSelectedFiles(); var filePath; if (files !== undefined && files.length > 0) { for (var i = 0; i < files.length; i++) { filePath = files[i].path; if (filePath.length > 1) { //console.log("Selecting files: "+JSON.stringify(files[i])); TSCORE.selectedFiles.push(filePath); //{"webkitRelativePath":"","path\":"/home/na/Desktop/Kola2","lastModifiedDate":"2014-07-11T16:40:52.000Z","name":"Kola2","type":"","size":4096} } } } if (TSCORE.selectedFiles.length > 0) { showMoveCopyFilesDialog(); } } }); } platformTuning(); var addFileInputName; $('#addFileInput').on('change', function(selection) { //console.log("Selected File: "+$("#addFileInput").val()); var file = selection.currentTarget.files[0]; //console.log("Selected File: "+JSON.stringify(selection.currentTarget.files[0])); addFileInputName = decodeURIComponent(file.name); var reader = new FileReader(); reader.onload = onFileReadComplete; reader.readAsArrayBuffer(file); }); function onFileReadComplete(event) { console.log('Content on file read complete: ' + JSON.stringify(event)); //change name for ios fakepath if (isCordovaiOS) { var parts = addFileInputName.split('.'); var ext = (parts.length > 1) ? '.' + parts.pop() : ''; addFileInputName = TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + ext; } var filePath = TSCORE.currentPath + TSCORE.dirSeparator + addFileInputName; TSCORE.IO.saveBinaryFilePromise(filePath, event.currentTarget.result).then(function() { TSPOSTIO.saveBinaryFile(filePath); }, function(error) { TSCORE.hideLoadingAnimation(); TSCORE.showAlertDialog("Saving " + filePath + " failed."); console.error("Save to file " + filePath + " failed " + error); }); addFileInputName = undefined; } $('#openLeftPanel').click(function() { TSCORE.openLeftPanel(); }); $('#closeLeftPanel').click(function() { TSCORE.closeLeftPanel(); }); $('#txtFileTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); fileContent = TSCORE.Config.getNewTextFileContent(); fileType = 'txt'; }); $('#htmlFileTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); fileContent = TSCORE.Config.getNewHTMLFileContent(); fileType = 'html'; }); $('#mdFileTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); fileContent = TSCORE.Config.getNewMDFileContent(); fileType = 'md'; }); $('#fileCreateConfirmButton').click(function() { var fileTags = ''; var rawTags = $('#newFileNameTags').val().split(','); rawTags.forEach(function(value, index) { if (index === 0) { fileTags = value; } else { fileTags = fileTags + TSCORE.Config.getTagDelimiter() + value; } }); if ($('#tagWithCurrentDate').prop('checked')) { if (fileTags.length < 1) { fileTags = TSCORE.TagUtils.formatDateTime4Tag(new Date()); } else { fileTags = fileTags + TSCORE.Config.getTagDelimiter() + TSCORE.TagUtils.formatDateTime4Tag(new Date()); } } if (fileTags.length > 0) { fileTags = TSCORE.TagUtils.beginTagContainer + fileTags + TSCORE.TagUtils.endTagContainer; } var filePath = TSCORE.currentPath + TSCORE.dirSeparator + $('#newFileName').val() + fileTags + '.' + fileType; TSCORE.IO.saveFilePromise(filePath, fileContent).then(function() { TSPOSTIO.saveTextFile(filePath, isNewFile); }, function(error) { TSCORE.hideLoadingAnimation(); TSCORE.showAlertDialog("Saving " + filePath + " failed."); console.error("Save to file " + filePath + " failed " + error); }); }); $('#renameFileButton').click(function() { var initialFilePath = $('#renamedFileName').attr('filepath'); var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(initialFilePath); var newFilePath = containingDir + TSCORE.dirSeparator + $('#renamedFileName').val(); TSCORE.IO.renameFilePromise(initialFilePath, newFilePath).then(function(success) { TSCORE.hideWaitingDialog(); TSPOSTIO.renameFile(initialFilePath, newFilePath); }, function(err) { TSCORE.hideWaitingDialog(); TSCORE.showAlertDialog(err); }); }); // Edit Tag Dialog $('#plainTagTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); TSCORE.selectedTag, $('#newTagName').datepicker('destroy').val(''); }); $('#dateTagTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); TSCORE.selectedTag, $('#newTagName').datepicker({ showWeek: true, firstDay: 1, dateFormat: 'yymmdd' }); }); $('#currencyTagTypeButton').click(function(e) { // Fixes reloading of the application by click e.preventDefault(); TSCORE.selectedTag, $('#newTagName').datepicker('destroy').val('XEUR'); }); $('#editTagButton').click(function() { TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $('#newTagName').val()); }); // End Edit Tag Dialog $('#startNewInstanceBack').click(function() { if (!isCordova) { window.open(window.location.href, '_blank'); } }); $('#aboutDialogBack').click(function() { if (TSCORE.PRO) { $('#aboutIframe').attr('src', 'pro/about.html'); } else { $('#aboutIframe').attr('src', 'about.html'); } }); // Open About Dialog $('#openAboutBox').click(function() { $('#dialogAbout').modal({ backdrop: 'static', show: true }); $('#dialogAbout').draggable({ handle: ".modal-header" }); }); // Open Options Dialog $('#openOptions').click(function() { showOptionsDialog(); }); // File Menu $('#fileMenuAddTag').click(function() { TSCORE.showAddTagsDialog(); }); $('#fileMenuOpenFile').click(function() { TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]); }); $('#fileMenuOpenNatively').click(function() { TSCORE.IO.openFile(TSCORE.selectedFiles[0]); }); $('#fileMenuSendTo').click(function() { TSCORE.IO.sendFile(TSCORE.selectedFiles[0]); }); $('#fileMenuOpenDirectory').click(function() { TSCORE.IO.openDirectory(TSCORE.currentPath); }); $('#fileMenuRenameFile').click(function() { TSCORE.showFileRenameDialog(TSCORE.selectedFiles[0]); }); $('#fileMenuMoveCopyFile').click(function() { TSCORE.showMoveCopyFilesDialog(); }); $('#fileMenuDeleteFile').click(function() { TSCORE.showFileDeleteDialog(TSCORE.selectedFiles[0]); }); $('#fileOpenProperties').click(function() {}); // End File Menu $('#showLocations').click(function() { showLocationsPanel(); }); $('#showTagGroups').click(function() { showTagsPanel(); }); $('#contactUs').click(function() { showContactUsPanel(); }); // Hide the tagGroupsContent or locationContent by default $('#locationContent').hide(); // Search UI $('#searchToolbar').on('click', '#closeSearchOptionButton', function() { $('#searchBox').popover('hide'); }); $('#searchToolbar').on('click', '#includeSubfoldersOption', function() { var searchQuery = $('#searchBox').val(); if (searchQuery.indexOf('?') === 0) { $('#includeSubfoldersOption i').removeClass('fa-toggle-on').addClass('fa-toggle-off'); $('#searchBox').val(searchQuery.substring(1, searchQuery.length)); } else { $('#includeSubfoldersOption i').removeClass('fa-toggle-off').addClass('fa-toggle-on'); $('#searchBox').val('?' + searchQuery); } }); $('#searchBox').on('show.bs.popover', function() { var searchQuery = $('#searchBox').val(); if (searchQuery.indexOf('?') === 0) { $('#includeSubfoldersOption i').removeClass('fa-toggle-off').addClass('fa-toggle-on'); } else { $('#includeSubfoldersOption i').removeClass('fa-toggle-on').addClass('fa-toggle-off'); } }); $('#searchBox').on('shown.bs.popover', function() { $('.popover').i18n(); }); $('#searchBox').prop('disabled', true) /*.focus(function() { $("#searchOptions").show(); })*/ .popover({ html: true, placement: 'bottom', trigger: 'focus', content: $('#searchOptions').html() }).keyup(function(e) { // On enter fire the search if (e.keyCode === 13) { $('#clearFilterButton').addClass('filterOn'); TSCORE.PerspectiveManager.redrawCurrentPerspective(); $('#searchOptions').hide(); $('#searchButton').focus(); } else if (e.keyCode == 27) { cancelSearch(); } else { TSCORE.Search.nextQuery = this.value; } if (this.value.length === 0) { TSCORE.Search.nextQuery = this.value; $('#clearFilterButton').removeClass('filterOn'); TSCORE.PerspectiveManager.redrawCurrentPerspective(); } }).blur(function() { if (this.value.length === 0) { $('#clearFilterButton').removeClass('filterOn'); TSCORE.PerspectiveManager.redrawCurrentPerspective(); } }); $('#showSearchButton').on('click', function() { TSCORE.showSearchArea(); }); $('#searchButton').prop('disabled', true).click(function(evt) { evt.preventDefault(); $('#clearFilterButton').addClass('filterOn'); $('#searchOptions').hide(); TSCORE.PerspectiveManager.redrawCurrentPerspective(); $('#searchBox').popover('hide'); }); $('#clearFilterButton').prop('disabled', true).click(function(e) { e.preventDefault(); cancelSearch(); }); // Search UI END $('#perspectiveSwitcherButton').prop('disabled', true); var $contactUsContent = $('#contactUsContent'); $contactUsContent.on('click', '#openHints', showWelcomeDialog); $contactUsContent.on('click', '#openUservoice', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openGooglePlay', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openAppleAppStore', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openWhatsnew', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openGitHubIssues', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#helpUsTranslate', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openTwitter', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openTwitter2', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openGooglePlus', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openFacebook', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $contactUsContent.on('click', '#openSupportUs', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); $('#newVersionMenu').on('click', '.whatsNewLink', function(e) { e.preventDefault(); openLinkExternally($(this).attr('href')); }); // Hide drop downs by click and drag $(document).click(function() { TSCORE.hideAllDropDownMenus(); }); }; function cancelSearch() { clearSearchFilter(); $('#searchBox').popover('hide'); $('#searchToolbar').hide(); $('#showSearchButton').show(); // Restoring initial dir listing without subdirectories TSCORE.IO.listDirectoryPromise(TSCORE.currentPath).then( function(entries) { TSPOSTIO.listDirectory(entries); }, function(err) { TSPOSTIO.errorOpeningPath(); console.warn("Error listing directory" + err); } ); } function showSearchArea() { $('#searchToolbar').show(); //.addClass('animated bounceIn'); $('#showSearchButton').hide(); $('#searchBox').focus(); } // Handle external links function openLinkExternally(url) { if (isNode) { gui.Shell.openExternal(url); } else { // _system is needed for cordova window.open(url, '_system'); } } function clearSearchFilter() { $('#searchOptions').hide(); $('#searchBox').val(''); $('#clearFilterButton').removeClass('filterOn'); TSCORE.Search.nextQuery = ''; } function disableTopToolbar() { $('#perspectiveSwitcherButton').prop('disabled', true); $('#searchBox').prop('disabled', true); $('#searchButton').prop('disabled', true); $('#clearFilterButton').prop('disabled', true); } function enableTopToolbar() { $('#perspectiveSwitcherButton').prop('disabled', false); $('#searchBox').prop('disabled', false); $('#searchButton').prop('disabled', false); $('#clearFilterButton').prop('disabled', false); } function platformTuning() { if (isCordova) { $('#directoryMenuOpenDirectory').parent().hide(); $('#fileMenuOpenDirectory').parent().hide(); $('#openDirectory').parent().hide(); $('#downloadFile').parent().hide(); $('#openFileInNewWindow').hide(); $('#openGooglePlay').hide(); $('.cancelButton').hide(); } else if (isCordovaiOS) { $('#fullscreenFile').parent().hide(); } else if (isChrome) { $('#directoryMenuOpenDirectory').parent().hide(); $('#fileMenuOpenDirectory').parent().hide(); $('#fileMenuOpenNatively').parent().hide(); $('#openDirectory').parent().hide(); $('#openNatively').hide(); } else if (isWeb) { $('#directoryMenuOpenDirectory').parent().hide(); $('#fileMenuOpenDirectory').parent().hide(); $('#fileMenuOpenNatively').parent().hide(); $('#openDirectory').parent().hide(); $('#openNatively').hide(); } else if (isFirefox) { $('#openNatively').hide(); $('#fileMenuOpenNatively').parent().hide(); } else if (isNode) { $('#openFileInNewWindow').hide(); //handling window maximization var nwwin = gui.Window.get(); nwwin.on('maximize', function() { TSCORE.Config.setIsWindowMaximized(true); TSCORE.Config.saveSettings(); }); nwwin.on('unmaximize', function() { TSCORE.Config.setIsWindowMaximized(false); TSCORE.Config.saveSettings(); }); // Disabling automatic maximazation of the main window //if(TSCORE.Config.getIsWindowMaximized()){ // nwwin.maximize(); //} } // Disable send to feature on all platforms except android cordova if (!isCordova) { $('#sendFile').hide(); $('#fileMenuSendTo').hide(); } if (isOSX) { $('body').addClass('osx'); } } var showContextMenu = function(menuId, sourceObject) { var leftPos = sourceObject.offset().left; var topPos = sourceObject.offset().top; if (sourceObject.offset().top + sourceObject.height() + $(menuId).height() > window.innerHeight) { topPos = window.innerHeight - $(menuId).height(); leftPos = sourceObject.offset().left + 15; } if (sourceObject.offset().left + sourceObject.width() + $(menuId).width() > window.innerWidth) { leftPos = window.innerWidth - $(menuId).width(); } $(menuId).css({ display: 'block', left: leftPos, top: topPos }); }; var hideAllDropDownMenus = function() { $('#tagGroupMenu').hide(); $('#tagTreeMenu').hide(); $('#directoryMenu').hide(); $('#tagMenu').hide(); $('#fileMenu').hide(); $('.dirAltNavMenu').hide(); }; var showLocationsPanel = function() { TSCORE.openLeftPanel(); $('#tagGroupsContent').hide(); $('#contactUsContent').hide(); $('#locationContent').show(); $('#showTagGroups').removeClass('active'); $('#contactUs').removeClass('active'); $('#showLocations').addClass('active'); }; var showTagsPanel = function() { TSCORE.openLeftPanel(); $('#locationContent').hide(); $('#contactUsContent').hide(); $('#tagGroupsContent').show(); $('#showLocations').removeClass('active'); $('#contactUs').removeClass('active'); $('#showTagGroups').addClass('active'); }; var showContactUsPanel = function() { TSCORE.openLeftPanel(); $('#locationContent').hide(); $('#tagGroupsContent').hide(); $('#contactUsContent').show(); $('#showLocations').removeClass('active'); $('#showTagGroups').removeClass('active'); $('#contactUs').addClass('active'); }; function createHTMLFile() { var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.html'; createNewTextFile(filePath, TSCORE.Config.getNewHTMLFileContent()); } function createMDFile() { var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.md'; createNewTextFile(filePath, TSCORE.Config.getNewMDFileContent()); } function createTXTFile() { var filePath = TSCORE.currentPath + TSCORE.dirSeparator + TSCORE.TagUtils.beginTagContainer + TSCORE.TagUtils.formatDateTime4Tag(new Date(), true) + TSCORE.TagUtils.endTagContainer + '.txt'; createNewTextFile(filePath, TSCORE.Config.getNewTextFileContent()); } function createNewTextFile(filePath, content) { TSCORE.IO.saveFilePromise(filePath, content).then(function(isNewFile) { TSPOSTIO.saveTextFile(filePath, isNewFile); }, function(error) { TSCORE.hideLoadingAnimation(); console.error("Save to file " + filePath + " failed " + error); TSCORE.showAlertDialog("Saving " + filePath + " failed."); }); } // Public API definition exports.showContextMenu = showContextMenu; exports.initUI = initUI; exports.clearSearchFilter = clearSearchFilter; exports.openLinkExternally = openLinkExternally; exports.enableTopToolbar = enableTopToolbar; exports.disableTopToolbar = disableTopToolbar; exports.hideWaitingDialog = hideWaitingDialog; exports.showWaitingDialog = showWaitingDialog; exports.showAlertDialog = showAlertDialog; exports.showSuccessDialog = showSuccessDialog; exports.showConfirmDialog = showConfirmDialog; exports.showFileRenameDialog = showFileRenameDialog; exports.showFileCreateDialog = showFileCreateDialog; exports.showFileDeleteDialog = showFileDeleteDialog; exports.showWelcomeDialog = showWelcomeDialog; exports.startGettingStartedTour = startGettingStartedTour; exports.showTagEditDialog = showTagEditDialog; exports.showOptionsDialog = showOptionsDialog; exports.showAboutDialog = showAboutDialog; exports.showLocationsPanel = showLocationsPanel; exports.showTagsPanel = showTagsPanel; exports.showContactUsPanel = showContactUsPanel; exports.showDirectoryBrowserDialog = showDirectoryBrowserDialog; exports.showMoveCopyFilesDialog = showMoveCopyFilesDialog; exports.hideAllDropDownMenus = hideAllDropDownMenus; exports.createHTMLFile = createHTMLFile; exports.createMDFile = createMDFile; exports.createTXTFile = createTXTFile; exports.showSearchArea = showSearchArea; });
adding comment
data/js/core.ui.js
adding comment
<ide><path>ata/js/core.ui.js <ide> <ide> $('#moveFilesButton').click(function(e) { <ide> e.preventDefault(); <add> // TODO move to ioutils <ide> TSCORE.showWaitingDialog('Please wait, while files are being renamed.'); <ide> var newFilePath, filePath; <ide> var fileOperations = [];
Java
unlicense
a89d3a4bf8c53a79c6c3ae68d3293ff51d56b801
0
Patrikwebb/BlackJackProjekt,Patrikwebb/BlackJackProjekt
package kodaLoss; import java.util.ArrayList; import java.util.Collections; public class Deck { // Deck blir en arrayList med 52 kort. public ArrayList<Card> getDeck() { ArrayList<Card> deck = new ArrayList<>(); for (Suite s : Suite.values()) { for (Rank r : Rank.values()) { deck.add(new Card(s,r)); } } return deck; } } class shuffel{ public ArrayList<Card> shuffelDeck(ArrayList<Card> arrayList){ Collections.shuffle(arrayList); ArrayList<Card> shuffeled = arrayList; return shuffeled; } }
src/main/java/kodaLoss/Deck.java
package kodaLoss; import java.util.ArrayList; public class Deck { // Deck blir en arrayList med 52 kort. public ArrayList<Card> getDeck() { ArrayList<Card> deck = new ArrayList<>(); for (Suite s : Suite.values()) { for (Rank r : Rank.values()) { deck.add(new Card(s,r)); } } return deck; } }
Deck update
src/main/java/kodaLoss/Deck.java
Deck update
<ide><path>rc/main/java/kodaLoss/Deck.java <ide> package kodaLoss; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collections; <ide> <ide> public class Deck { // Deck blir en arrayList med 52 kort. <ide> <ide> return deck; <ide> } <ide> } <add>class shuffel{ <add> public ArrayList<Card> shuffelDeck(ArrayList<Card> arrayList){ <add> Collections.shuffle(arrayList); <add> ArrayList<Card> shuffeled = arrayList; <add> return shuffeled; <add> } <add>}
Java
apache-2.0
e47792c3a7f3cc3da2c786cf6ad4767157a64f7a
0
JNOSQL/diana-driver,JNOSQL/diana-driver
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.elasticsearch.document; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.jnosql.diana.api.Settings; import org.jnosql.diana.api.document.UnaryDocumentConfiguration; import org.jnosql.diana.driver.ConfigurationReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static java.util.Objects.requireNonNull; /** * The implementation of {@link UnaryDocumentConfiguration} that returns {@link ElasticsearchDocumentCollectionManagerFactory}. * It tries to read the configuration properties from diana-elasticsearch.properties file. To get some information: * <p>elasticsearch-host-n: the host to client connection, if necessary to define a different port than default just * use colon, ':' eg: elasticsearch-host-1=172.17.0.2:1234</p> */ public class ElasticsearchDocumentConfiguration implements UnaryDocumentConfiguration<ElasticsearchDocumentCollectionManagerFactory> { private static final String FILE_CONFIGURATION = "diana-elasticsearch.properties"; private static final String HOST_PREFIX = "elasticsearch-host-"; private static final int DEFAULT_PORT = 9200; private List<HttpHost> httpHosts = new ArrayList<>(); private List<Header> headers = new ArrayList<>(); public ElasticsearchDocumentConfiguration() { Map<String, String> configurations = ConfigurationReader.from(FILE_CONFIGURATION); if (configurations.isEmpty()) { return; } configurations.keySet().stream() .filter(k -> k.startsWith(HOST_PREFIX)) .sorted() .map(h -> ElasticsearchAddress.of(configurations.get(h), DEFAULT_PORT)) .map(ElasticsearchAddress::toHttpHost) .forEach(httpHosts::add); } @Override public ElasticsearchDocumentCollectionManagerFactory get() throws UnsupportedOperationException { return get(Settings.builder().build()); } @Override public ElasticsearchDocumentCollectionManagerFactory get(Settings settings) throws NullPointerException { requireNonNull(settings, "settings is required"); Map<String, String> configurations = new HashMap<>(); settings.forEach((key, value) -> configurations.put(key, value.toString())); configurations.keySet().stream() .filter(k -> k.startsWith(HOST_PREFIX)) .sorted() .map(h -> ElasticsearchAddress.of(configurations.get(h), DEFAULT_PORT)) .map(ElasticsearchAddress::toHttpHost) .forEach(httpHosts::add); RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[httpHosts.size()])); RestHighLevelClient client = new RestHighLevelClient(builder); return new ElasticsearchDocumentCollectionManagerFactory(client); } @Override public ElasticsearchDocumentCollectionManagerFactory getAsync() throws UnsupportedOperationException { return get(); } @Override public ElasticsearchDocumentCollectionManagerFactory getAsync(org.jnosql.diana.api.Settings settings) throws NullPointerException { return get(settings); } /** * returns an {@link ElasticsearchDocumentCollectionManagerFactory} instance * * @param builder the builder {@link RestClientBuilder} * @return a manager factory instance * @throws NullPointerException when builder is null */ public ElasticsearchDocumentCollectionManagerFactory get(RestClientBuilder builder) { Objects.requireNonNull(builder, "builder is required"); RestHighLevelClient client = new RestHighLevelClient(builder); return new ElasticsearchDocumentCollectionManagerFactory(client); } /** * returns an {@link ElasticsearchDocumentCollectionManagerFactory} instance * * @param client the client {@link RestHighLevelClient} * @return a manager factory instance * @throws NullPointerException when client is null */ public ElasticsearchDocumentCollectionManagerFactory get(RestHighLevelClient client) { Objects.requireNonNull(client, "client is required"); return new ElasticsearchDocumentCollectionManagerFactory(client); } }
elasticsearch-driver/src/main/java/org/jnosql/diana/elasticsearch/document/ElasticsearchDocumentConfiguration.java
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.elasticsearch.document; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.jnosql.diana.api.Settings; import org.jnosql.diana.api.document.UnaryDocumentConfiguration; import org.jnosql.diana.driver.ConfigurationReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Objects.requireNonNull; /** * The implementation of {@link UnaryDocumentConfiguration} that returns {@link ElasticsearchDocumentCollectionManagerFactory}. * It tries to read the configuration properties from diana-elasticsearch.properties file. To get some information: * <p>elasticsearch-host-n: the host to client connection, if necessary to define a different port than default just * use colon, ':' eg: elasticsearch-host-1=172.17.0.2:1234</p> */ public class ElasticsearchDocumentConfiguration implements UnaryDocumentConfiguration<ElasticsearchDocumentCollectionManagerFactory> { private static final String FILE_CONFIGURATION = "diana-elasticsearch.properties"; private static final String HOST_PREFIX = "elasticsearch-host-"; private static final int DEFAULT_PORT = 9200; private List<HttpHost> httpHosts = new ArrayList<>(); public ElasticsearchDocumentConfiguration() { Map<String, String> configurations = ConfigurationReader.from(FILE_CONFIGURATION); if (configurations.isEmpty()) { return; } configurations.keySet().stream() .filter(k -> k.startsWith(HOST_PREFIX)) .sorted() .map(h -> ElasticsearchAddress.of(configurations.get(h), DEFAULT_PORT)) .map(ElasticsearchAddress::toHttpHost) .forEach(httpHosts::add); } @Override public ElasticsearchDocumentCollectionManagerFactory get() throws UnsupportedOperationException { return get(Settings.builder().build()); } @Override public ElasticsearchDocumentCollectionManagerFactory get(Settings settings) throws NullPointerException { requireNonNull(settings, "settings is required"); Map<String, String> configurations = new HashMap<>(); settings.forEach((key, value) -> configurations.put(key, value.toString())); configurations.keySet().stream() .filter(k -> k.startsWith(HOST_PREFIX)) .sorted() .map(h -> ElasticsearchAddress.of(configurations.get(h), DEFAULT_PORT)) .map(ElasticsearchAddress::toHttpHost) .forEach(httpHosts::add); RestClientBuilder builder = RestClient.builder(httpHosts.toArray(new HttpHost[httpHosts.size()])); RestHighLevelClient client = new RestHighLevelClient(builder); return new ElasticsearchDocumentCollectionManagerFactory(client); } @Override public ElasticsearchDocumentCollectionManagerFactory getAsync() throws UnsupportedOperationException { return get(); } @Override public ElasticsearchDocumentCollectionManagerFactory getAsync(org.jnosql.diana.api.Settings settings) throws NullPointerException { return get(settings); } }
adds more factory
elasticsearch-driver/src/main/java/org/jnosql/diana/elasticsearch/document/ElasticsearchDocumentConfiguration.java
adds more factory
<ide><path>lasticsearch-driver/src/main/java/org/jnosql/diana/elasticsearch/document/ElasticsearchDocumentConfiguration.java <ide> package org.jnosql.diana.elasticsearch.document; <ide> <ide> <add>import org.apache.http.Header; <add>import org.apache.http.HttpHeaders; <ide> import org.apache.http.HttpHost; <ide> import org.elasticsearch.client.RestClient; <ide> import org.elasticsearch.client.RestClientBuilder; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Objects; <ide> <ide> import static java.util.Objects.requireNonNull; <ide> <ide> <ide> private List<HttpHost> httpHosts = new ArrayList<>(); <ide> <add> private List<Header> headers = new ArrayList<>(); <add> <ide> <ide> public ElasticsearchDocumentConfiguration() { <ide> <ide> .map(ElasticsearchAddress::toHttpHost) <ide> .forEach(httpHosts::add); <ide> } <del> <del> <ide> <ide> <ide> @Override <ide> } <ide> <ide> <add> /** <add> * returns an {@link ElasticsearchDocumentCollectionManagerFactory} instance <add> * <add> * @param builder the builder {@link RestClientBuilder} <add> * @return a manager factory instance <add> * @throws NullPointerException when builder is null <add> */ <add> public ElasticsearchDocumentCollectionManagerFactory get(RestClientBuilder builder) { <add> Objects.requireNonNull(builder, "builder is required"); <add> RestHighLevelClient client = new RestHighLevelClient(builder); <add> return new ElasticsearchDocumentCollectionManagerFactory(client); <add> } <ide> <ide> <del> <add> /** <add> * returns an {@link ElasticsearchDocumentCollectionManagerFactory} instance <add> * <add> * @param client the client {@link RestHighLevelClient} <add> * @return a manager factory instance <add> * @throws NullPointerException when client is null <add> */ <add> public ElasticsearchDocumentCollectionManagerFactory get(RestHighLevelClient client) { <add> Objects.requireNonNull(client, "client is required"); <add> return new ElasticsearchDocumentCollectionManagerFactory(client); <add> } <ide> <ide> }
Java
mit
9789acf8ad023b8dfa59f07277e51521174f6586
0
luthai/LiteWorkoutTimer
package com.luanthanhthai.android.liteworkouttimer; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.Toast; /** * Created by Thai on 15.01.2016. * Copyright (c) [2016] [Luan Thanh Thai] * See the file LICENSE.txt for copying permission */ public class TimerFragment extends Fragment implements View.OnClickListener { private Button mPauseButton; private ViewGroup keypadPanel; private ViewGroup pauseBarPanel; private boolean isRunning = false; public static TimerFragment newInstance() { return new TimerFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_timer, container, false); Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(toolbar); // The sliding panels keypadPanel = (ViewGroup) v.findViewById(R.id.start_button_bar_with_keypad); pauseBarPanel = (ViewGroup) v.findViewById(R.id.pause_button_bar); // Timer buttons Button startButton = (Button) v.findViewById(R.id.button_start); startButton.setOnClickListener(this); Button restButton = (Button) v.findViewById(R.id.button_rest); restButton.setOnClickListener(this); mPauseButton = (Button) v.findViewById(R.id.button_pause); mPauseButton.setOnClickListener(this); Button restartButton = (Button) v.findViewById(R.id.button_restart); restartButton.setOnClickListener(this); Button resetButton = (Button) v.findViewById(R.id.button_reset); resetButton.setOnClickListener(this); // Keypad numeric buttons // For backwards compatibility set this // near the end setHasOptionsMenu(true); return v; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_start: animSlidePanel(keypadPanel, pauseBarPanel); isRunning = true; break; case R.id.button_rest: animSlidePanel(keypadPanel, pauseBarPanel); isRunning = true; break; case R.id.button_pause: mPauseButton.setVisibility(View.INVISIBLE); isRunning = false; break; case R.id.button_restart: mPauseButton.setVisibility(View.VISIBLE); isRunning = true; break; case R.id.button_reset: animSlidePanel(pauseBarPanel, keypadPanel); isRunning = false; break; default: break; } } public void animSlidePanel(ViewGroup slidePanelDown, ViewGroup slidePanelUp) { // Slide panel down Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_down); slidePanelDown.startAnimation(slideDown); slidePanelDown.setVisibility(View.GONE); //Slide panel up Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_up); slidePanelUp.startAnimation(slideUp); slidePanelUp.setVisibility(View.VISIBLE); } @Override public boolean onOptionsItemSelected(MenuItem item) { Context context = getActivity(); CharSequence text; int duration = Toast.LENGTH_SHORT; Toast toast; switch (item.getItemId()) { case R.id.menu_ic_create_routine: text = "Create routine"; toast = Toast.makeText(context, text, duration); toast.show(); return true; case R.id.menu_ic_settings: text = "Settings"; toast = Toast.makeText(context, text, duration); toast.show(); return true; default: return super.onOptionsItemSelected(item); } } }
app/src/main/java/com/luanthanhthai/android/liteworkouttimer/TimerFragment.java
package com.luanthanhthai.android.liteworkouttimer; import android.content.Context; import android.graphics.PorterDuff; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.Toast; /** * Created by Thai on 15.01.2016. * Copyright (c) [2016] [Luan Thanh Thai] * See the file LICENSE.txt for copying permission */ public class TimerFragment extends Fragment { private Toolbar mToolbar; private Button mStartButton; private Button mRestButton; private Button mPauseButton; private Button mResetButton; private Button mStartButton2; private ViewGroup keypadPanel; private ViewGroup pauseBar; private boolean isRunning; public static TimerFragment newInstance() { return new TimerFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_timer, container, false); mToolbar = (Toolbar) v.findViewById(R.id.toolbar); AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(mToolbar); // Check if timer is running isRunning = false; // The sliding panels keypadPanel = (ViewGroup) v.findViewById(R.id.start_button_bar_with_keypad); pauseBar = (ViewGroup) v.findViewById(R.id.pause_button_bar); mStartButton = (Button) v.findViewById(R.id.button_start); mStartButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { keypadSlideDown(); pauseBarSlideUP(); isRunning = true; } }); mRestButton = (Button) v.findViewById(R.id.button_rest); mRestButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { keypadSlideDown(); pauseBarSlideUP(); isRunning = true; } }); mPauseButton = (Button) v.findViewById(R.id.button_pause); mPauseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mPauseButton.setVisibility(View.INVISIBLE); isRunning = false; } }); mStartButton2 = (Button) v.findViewById(R.id.button_restart); mStartButton2.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mPauseButton.setVisibility(View.VISIBLE); isRunning = true; } }); mResetButton = (Button) v.findViewById(R.id.button_reset); mResetButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { pauseBarSlideDown(); keypadSlideUp(); isRunning = false; } }); // For backwards compatibility set this // near the end setHasOptionsMenu(true); return v; } public void keypadSlideUp() { Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_up); keypadPanel.startAnimation(slideUp); keypadPanel.setVisibility(View.VISIBLE); } public void keypadSlideDown() { Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_down); keypadPanel.startAnimation(slideDown); keypadPanel.setVisibility(View.GONE); } public void pauseBarSlideUP() { Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_up); pauseBar.startAnimation(slideUp); pauseBar.setVisibility(View.VISIBLE); } public void pauseBarSlideDown() { Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_down); pauseBar.startAnimation(slideDown); pauseBar.setVisibility(View.GONE); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_timer, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Context context = getActivity(); CharSequence text; int duration = Toast.LENGTH_SHORT; Toast toast; switch (item.getItemId()) { case R.id.menu_ic_create_routine: text = "Create routine"; toast = Toast.makeText(context, text, duration); toast.show(); return true; case R.id.menu_ic_settings: text = "Settings"; toast = Toast.makeText(context, text, duration); toast.show(); return true; default: return super.onOptionsItemSelected(item); } } }
Made code more DRY, reduce complexity
app/src/main/java/com/luanthanhthai/android/liteworkouttimer/TimerFragment.java
Made code more DRY, reduce complexity
<ide><path>pp/src/main/java/com/luanthanhthai/android/liteworkouttimer/TimerFragment.java <ide> package com.luanthanhthai.android.liteworkouttimer; <ide> <ide> import android.content.Context; <del>import android.graphics.PorterDuff; <ide> import android.os.Bundle; <ide> import android.support.v4.app.Fragment; <del>import android.support.v4.app.FragmentManager; <del>import android.support.v4.app.FragmentTransaction; <ide> import android.support.v7.app.AppCompatActivity; <ide> import android.support.v7.widget.Toolbar; <ide> import android.view.LayoutInflater; <del>import android.view.Menu; <del>import android.view.MenuInflater; <ide> import android.view.MenuItem; <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> * Copyright (c) [2016] [Luan Thanh Thai] <ide> * See the file LICENSE.txt for copying permission <ide> */ <del>public class TimerFragment extends Fragment { <add>public class TimerFragment extends Fragment implements View.OnClickListener { <ide> <del> private Toolbar mToolbar; <del> private Button mStartButton; <del> private Button mRestButton; <ide> private Button mPauseButton; <del> private Button mResetButton; <del> private Button mStartButton2; <ide> <ide> private ViewGroup keypadPanel; <del> private ViewGroup pauseBar; <add> private ViewGroup pauseBarPanel; <ide> <del> private boolean isRunning; <add> private boolean isRunning = false; <ide> <ide> public static TimerFragment newInstance() { <ide> return new TimerFragment(); <ide> Bundle savedInstanceState) { <ide> View v = inflater.inflate(R.layout.fragment_timer, container, false); <ide> <del> mToolbar = (Toolbar) v.findViewById(R.id.toolbar); <add> Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar); <ide> AppCompatActivity activity = (AppCompatActivity) getActivity(); <del> activity.setSupportActionBar(mToolbar); <del> <del> // Check if timer is running <del> isRunning = false; <add> activity.setSupportActionBar(toolbar); <ide> <ide> // The sliding panels <ide> keypadPanel = (ViewGroup) v.findViewById(R.id.start_button_bar_with_keypad); <del> pauseBar = (ViewGroup) v.findViewById(R.id.pause_button_bar); <add> pauseBarPanel = (ViewGroup) v.findViewById(R.id.pause_button_bar); <ide> <del> mStartButton = (Button) v.findViewById(R.id.button_start); <del> mStartButton.setOnClickListener(new View.OnClickListener() { <del> public void onClick(View view) { <del> keypadSlideDown(); <del> pauseBarSlideUP(); <del> isRunning = true; <del> } <del> }); <add> // Timer buttons <add> Button startButton = (Button) v.findViewById(R.id.button_start); <add> startButton.setOnClickListener(this); <add> Button restButton = (Button) v.findViewById(R.id.button_rest); <add> restButton.setOnClickListener(this); <add> mPauseButton = (Button) v.findViewById(R.id.button_pause); <add> mPauseButton.setOnClickListener(this); <add> Button restartButton = (Button) v.findViewById(R.id.button_restart); <add> restartButton.setOnClickListener(this); <add> Button resetButton = (Button) v.findViewById(R.id.button_reset); <add> resetButton.setOnClickListener(this); <ide> <del> mRestButton = (Button) v.findViewById(R.id.button_rest); <del> mRestButton.setOnClickListener(new View.OnClickListener() { <del> public void onClick(View view) { <del> keypadSlideDown(); <del> pauseBarSlideUP(); <del> isRunning = true; <del> } <del> }); <add> // Keypad numeric buttons <ide> <del> mPauseButton = (Button) v.findViewById(R.id.button_pause); <del> mPauseButton.setOnClickListener(new View.OnClickListener() { <del> public void onClick(View view) { <del> mPauseButton.setVisibility(View.INVISIBLE); <del> isRunning = false; <del> } <del> }); <ide> <del> mStartButton2 = (Button) v.findViewById(R.id.button_restart); <del> mStartButton2.setOnClickListener(new View.OnClickListener() { <del> public void onClick(View view) { <del> mPauseButton.setVisibility(View.VISIBLE); <del> isRunning = true; <del> } <del> }); <del> <del> mResetButton = (Button) v.findViewById(R.id.button_reset); <del> mResetButton.setOnClickListener(new View.OnClickListener() { <del> public void onClick(View view) { <del> pauseBarSlideDown(); <del> keypadSlideUp(); <del> isRunning = false; <del> } <del> }); <ide> <ide> // For backwards compatibility set this <ide> // near the end <ide> return v; <ide> } <ide> <del> public void keypadSlideUp() { <add> @Override <add> public void onClick(View v) { <add> switch (v.getId()) { <add> case R.id.button_start: <add> animSlidePanel(keypadPanel, pauseBarPanel); <add> isRunning = true; <add> break; <add> <add> case R.id.button_rest: <add> animSlidePanel(keypadPanel, pauseBarPanel); <add> isRunning = true; <add> break; <add> <add> case R.id.button_pause: <add> mPauseButton.setVisibility(View.INVISIBLE); <add> isRunning = false; <add> break; <add> <add> case R.id.button_restart: <add> mPauseButton.setVisibility(View.VISIBLE); <add> isRunning = true; <add> break; <add> <add> case R.id.button_reset: <add> animSlidePanel(pauseBarPanel, keypadPanel); <add> isRunning = false; <add> break; <add> <add> default: <add> break; <add> } <add> } <add> <add> public void animSlidePanel(ViewGroup slidePanelDown, ViewGroup slidePanelUp) { <add> // Slide panel down <add> Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_down); <add> <add> slidePanelDown.startAnimation(slideDown); <add> slidePanelDown.setVisibility(View.GONE); <add> <add> //Slide panel up <ide> Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_up); <ide> <del> keypadPanel.startAnimation(slideUp); <del> keypadPanel.setVisibility(View.VISIBLE); <del> } <del> <del> public void keypadSlideDown() { <del> Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_down); <del> <del> keypadPanel.startAnimation(slideDown); <del> keypadPanel.setVisibility(View.GONE); <del> } <del> <del> public void pauseBarSlideUP() { <del> Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_up); <del> <del> pauseBar.startAnimation(slideUp); <del> pauseBar.setVisibility(View.VISIBLE); <del> } <del> <del> public void pauseBarSlideDown() { <del> Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slide_bottom_down); <del> <del> pauseBar.startAnimation(slideDown); <del> pauseBar.setVisibility(View.GONE); <del> } <del> <del> @Override <del> public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { <del> super.onCreateOptionsMenu(menu, inflater); <del> inflater.inflate(R.menu.menu_timer, menu); <add> slidePanelUp.startAnimation(slideUp); <add> slidePanelUp.setVisibility(View.VISIBLE); <ide> } <ide> <ide> @Override <ide> toast = Toast.makeText(context, text, duration); <ide> toast.show(); <ide> return true; <add> <ide> case R.id.menu_ic_settings: <ide> text = "Settings"; <ide> toast = Toast.makeText(context, text, duration); <ide> toast.show(); <ide> return true; <add> <ide> default: <ide> return super.onOptionsItemSelected(item); <ide> }
Java
mit
f3adce47429ac2261480379944b5dbedf611dd5c
0
strongback/strongback-java,AGausmann/strongback-java,WawerOS/strongback-java,AGausmann/strongback-java,strongback/strongback-java
/* * Strongback * Copyright 2015, Strongback and individual contributors by the @authors tag. * See the COPYRIGHT.txt in the distribution for a full listing of individual * contributors. * * Licensed under the MIT License; you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.strongback; import static org.fest.assertions.Assertions.assertThat; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.strongback.Logger.Level; import junit.framework.AssertionFailedError; /** * This test attempts to measure the timing of the {@link Strongback#executor() Strongback Executor} instance at various periods * <p> * The code committed into Git are small execution rates and sample sizes to minimize the time required to run the tests. As * such, the results are probably not terribly meaningful. To obtain more meaningful results on your own platform, simply adjust * the execution rates and sample sizes and run locally (though do not commit these changes). * * @author Randall Hauch */ public class ExecutableTimerTest { @BeforeClass public static void beforeAll() { Strongback.configure().setLogLevel(Level.ERROR).recordNoData().recordNoEvents(); } @AfterClass public static void afterAll() { Strongback.stop(); } @Test public void shouldMeasureAndPrintTimingHistogramFor4MillisecondPeriod() throws InterruptedException { runTimer(4, 2000); } @Test public void shouldMeasureAndPrintTimingHistogramFor10MillisecondPeriod() throws InterruptedException { runTimer(10, 2000); } /** * Time for the given duration the execution using the supplied mode and execution period. * * @param mode the execution wait mode; may not be null * @param millisecondExecutionPeriod the execution period in milliseconds * @param sampleTimeInMilliseconds the sample time in milliseconds */ protected void runTimer(int millisecondExecutionPeriod, int sampleTimeInMilliseconds) { try { Strongback.stop(); Strongback.configure() .useExecutionPeriod(millisecondExecutionPeriod, TimeUnit.MILLISECONDS); Strongback.start(); assertThat(ExecutableTimer.measureTimingAndPrint(Strongback.executor(), " for " + millisecondExecutionPeriod + " ms", sampleTimeInMilliseconds / millisecondExecutionPeriod) .await(4, TimeUnit.SECONDS) .isComplete()); } catch (InterruptedException e) { Thread.interrupted(); throw new AssertionFailedError(); } } }
strongback-tests/src/org/strongback/ExecutableTimerTest.java
/* * Strongback * Copyright 2015, Strongback and individual contributors by the @authors tag. * See the COPYRIGHT.txt in the distribution for a full listing of individual * contributors. * * Licensed under the MIT License; you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.strongback; import static org.fest.assertions.Assertions.assertThat; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.strongback.Logger.Level; import junit.framework.AssertionFailedError; /** * This test attempts to measure the timing of the {@link Strongback#executor() Strongback Executor} instance at various periods * <p> * The code committed into Git are small execution rates and sample sizes to minimize the time required to run the tests. As * such, the results are probably not terribly meaningful. To obtain more meaningful results on your own platform, simply adjust * the execution rates and sample sizes and run locally (though do not commit these changes). * * @author Randall Hauch */ public class ExecutableTimerTest { @BeforeClass public static void beforeAll() { Strongback.configure().setLogLevel(Level.ERROR).recordNoData().recordNoEvents(); } @AfterClass public static void afterAll() { Strongback.stop(); } @Test public void shouldMeasureAndPrintTimingHistogramFor4MillisecondPeriod() throws InterruptedException { runTimer(4, 2000); } @Test public void shouldMeasureAndPrintTimingHistogramFor10MillisecondPeriod() throws InterruptedException { runTimer(10, 2000); } /** * Time for the given duration the execution using the supplied mode and execution period. * * @param mode the execution wait mode; may not be null * @param millisecondExecutionPeriod the execution period in milliseconds * @param sampleTimeInMilliseconds the sample time in milliseconds */ protected void runTimer(int millisecondExecutionPeriod, int sampleTimeInMilliseconds) { try { Strongback.stop(); Strongback.configure() .useExecutionPeriod(millisecondExecutionPeriod, TimeUnit.MILLISECONDS); Strongback.start(); assertThat(ExecutableTimer.measureTimingAndPrint(Strongback.executor(), " for " + millisecondExecutionPeriod + " ms", sampleTimeInMilliseconds / millisecondExecutionPeriod) .await(10, TimeUnit.SECONDS) .isComplete()); } catch (InterruptedException e) { Thread.interrupted(); throw new AssertionFailedError(); } } }
Reduced time required to run executable timer test
strongback-tests/src/org/strongback/ExecutableTimerTest.java
Reduced time required to run executable timer test
<ide><path>trongback-tests/src/org/strongback/ExecutableTimerTest.java <ide> assertThat(ExecutableTimer.measureTimingAndPrint(Strongback.executor(), <ide> " for " + millisecondExecutionPeriod + " ms", <ide> sampleTimeInMilliseconds / millisecondExecutionPeriod) <del> .await(10, TimeUnit.SECONDS) <add> .await(4, TimeUnit.SECONDS) <ide> .isComplete()); <ide> } catch (InterruptedException e) { <ide> Thread.interrupted();
Java
apache-2.0
26d42d7c55d3ef4c5f52c93b4126774d3f3bd94e
0
FUNCATE/TerraMobile,FUNCATE/TerraMobile,TerraMobile/TerraMobile,TerraMobile/TerraMobile
package br.org.funcate.terramobile.controller.activity; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.ConnectivityManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ExpandableListView; import android.widget.TextView; import android.widget.Toast; import com.augtech.geoapi.feature.SimpleFeatureImpl; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.GeometryType; import org.osmdroid.bonuspack.kml.KmlDocument; import org.osmdroid.bonuspack.kml.Style; import org.osmdroid.bonuspack.overlays.FolderOverlay; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Overlay; import java.io.File; import java.util.ArrayList; import java.util.List; import br.org.funcate.dynamicforms.images.ImageUtilities; import br.org.funcate.jgpkg.exception.QueryException; import br.org.funcate.jgpkg.service.GeoPackageService; import br.org.funcate.terramobile.R; import br.org.funcate.terramobile.configuration.ViewContextParameters; import br.org.funcate.terramobile.controller.activity.settings.SettingsActivity; import br.org.funcate.terramobile.model.Project; import br.org.funcate.terramobile.model.Settings; import br.org.funcate.terramobile.model.db.dao.ProjectDAO; import br.org.funcate.terramobile.model.db.dao.SettingsDAO; import br.org.funcate.terramobile.model.exception.TerraMobileException; import br.org.funcate.terramobile.model.geomsource.SFSLayer; import br.org.funcate.terramobile.model.gpkg.objects.GpkgLayer; import br.org.funcate.terramobile.model.tilesource.AppGeoPackageService; import br.org.funcate.terramobile.util.Message; import br.org.funcate.terramobile.util.ResourceUtil; public class MainActivity extends FragmentActivity { private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private ActionBar actionBar; private CharSequence mDrawerTitle; private CharSequence mTitle; private TreeView treeView; private ViewContextParameters parameters=new ViewContextParameters(); private Project mProject; private Settings settings; private ProjectDAO projectDAO; private SettingsDAO settingsDAO; private static int FORM_COLLECT_DATA = 222; // Progress bar private ProgressDialog progressDialog; private ProjectListFragment projectListFragment; /* public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK && requestCode == FORM_COLLECT_DATA) { Bundle extras = data.getBundleExtra(LibraryConstants.PREFS_KEY_FORM); try { AppGeoPackageService.storeData(this,extras); }catch (TerraMobileException tme) { //Message.showMessage(this, R.drawable.error, getResources().getString(R.string.error), tme.getMessage()); Message.showErrorMessage(this, R.string.error, R.string.missing_form_data); }catch (QueryException qe) { //Message.showMessage(this, R.drawable.error, getResources().getString(R.string.error), qe.getMessage()); Message.showErrorMessage(this, R.string.error, R.string.error_while_storing_form_data); } }else { Message.showErrorMessage(this, R.string.error, R.string.cancel_form_data); } }*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionBar = getActionBar(); PreferenceManager.setDefaultValues(this, R.xml.settings, false); settingsDAO = new SettingsDAO(this); if(settingsDAO.getById(1) == null){ settings = new Settings(); settings.setId(1); settings.setUrl(ResourceUtil.getStringResource(getResources(), R.string.terramobile_url)); // URL for test settingsDAO.insert(settings); } else{ settings = settingsDAO.getById(1); } File directory = ResourceUtil.getDirectory(this.getResources().getString(R.string.app_workspace_dir)); String fileName = settings.getCurrentProject(); String ext = this.getString(R.string.geopackage_extension); if(settings.getCurrentProject() != null) { projectDAO = new ProjectDAO(this); mProject = projectDAO.getByName(settings.getCurrentProject()); File currentProject = ResourceUtil.getGeoPackageByName(directory, ext, fileName); if(currentProject != null) { if(mProject == null) { Project project = new Project(); project.setId(null); project.setName(fileName); project.setFilePath(currentProject.getPath()); projectDAO.insert(project); mProject = projectDAO.getByName(settings.getCurrentProject()); } } else{ if(mProject != null){ if(projectDAO.remove(mProject.getId())){ Log.i("Remove project","Project removed"); } else Log.e("Remove project","Couldn't remove the project"); } } } treeView = new TreeView(this); mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // set a custom shadow that overlays the action_bar content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); int ActionBarTitleID = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); TextView ActionBarTextView = (TextView) this.findViewById(ActionBarTitleID); ActionBarTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.title_text_size)); actionBar.setDisplayHomeAsUpEnabled(true); // ActionBarDrawerToggle ties together the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, //host Activity mDrawerLayout, //DrawerLayout object R.drawable.ic_drawer, //nav drawer image to replace 'Up' caret R.string.drawer_open, //"open drawer" description for accessibility R.string.drawer_close //"close drawer" description for accessibility ) { public void onDrawerClosed(View view) { actionBar.setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { actionBar.setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { insertMapView(); } } @Override public void onBackPressed() { this.finish(); System.exit(0); return; } public ViewContextParameters getParameters(){ return parameters; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar, menu); MenuItem menuItem = menu.findItem(R.id.project); menuItem.setTitle(mProject != null ? mProject.toString() : "Project"); return super.onCreateOptionsMenu(menu); } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { ExpandableListView mDrawerList=treeView.getUIComponent(); if(mDrawerList==null) return false; MenuItem menuItem = menu.findItem(R.id.project); menuItem.setTitle(mProject != null?mProject.toString():"Project"); // If the nav drawer is open, hide action items related to the content view return super.onPrepareOptionsMenu(menu); } /** * This method is called when item from action bar is selected. * @param item, the menu item component * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) return true; // Handle action buttons switch(item.getItemId()) { case R.id.project: projectListFragment = new ProjectListFragment(); projectListFragment.show(getFragmentManager(), "packageList"); return true; case R.id.acquire_new_point: FragmentManager fm = getSupportFragmentManager(); MapFragment fragment = (MapFragment)fm.findFragmentById(R.id.content_frame); // add an bookmark on map and show the related form fragment.startForm(); break; /* case R.id.test_vector_data: testVectorData(); break; case R.id.test_editable_layer: testEditableLayer(); break; case R.id.test_insert_sfs: testInsertSFS(); break; */ case R.id.settings: startActivity(new Intent(this, SettingsActivity.class)); break; case R.id.exit: this.finish(); System.exit(0); break; default: return super.onOptionsItemSelected(item); } return true; } public MapFragment getMapFragment() { FragmentManager fm = getSupportFragmentManager(); MapFragment fragment = (MapFragment)fm.findFragmentById(R.id.content_frame); return fragment; } private void insertMapView() { // update the action_bar content by replacing fragments Fragment fragment = new MapFragment(); /* Bundle args = new Bundle(); args.putStringArrayList(MapFragment.mLayers); fragment.setArguments(args);*/ FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } @Override public void setTitle(CharSequence title) { mTitle = title; actionBar.setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } /** * Shows a progress bar with the download progress */ public void showProgressDialog(String message) { progressDialog = new ProgressDialog(this); progressDialog.setMessage(message); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setMax(100); progressDialog.setProgress(0); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, MainActivity.this.getString(R.string.btn_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MainActivity.this.getProjectListFragment().getDownloadTask().cancel(true); } }); progressDialog.show(); } public void showLoadingDialog(String message) { progressDialog = new ProgressDialog(this); progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.show(); } public ProgressDialog getProgressDialog() { return progressDialog; } public TreeView getTreeView() { return treeView; } public ProjectListFragment getProjectListFragment() { return projectListFragment; } public Project getProject() { return mProject; } public void setProject(Project project) { this.mProject = project; settings.setCurrentProject(project!=null?project.getName():null); settingsDAO.update(settings); treeView.refreshTreeView(); invalidateOptionsMenu(); } private void testEditableLayer() { GpkgLayer layer = null; SFSLayer l = null; try { layer = treeView.getLayerByName("field_work_collect_data"); l = AppGeoPackageService.getFeatures(layer); } catch (TerraMobileException e) { e.printStackTrace(); } MapView map = (MapView) findViewById(R.id.mapview); map.setTileSource(TileSourceFactory.MAPNIK); map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); Style defaultStyle = new Style(null, 0x901010AA, 1.0f, 0x20AA1010); KmlDocument kmlDocument = new KmlDocument(); Overlay overlay = l.buildOverlay(map, defaultStyle, null, kmlDocument); map.getOverlays().add(overlay); map.invalidate(); } private void testInsertSFS() { GpkgLayer layer = null; try { layer = treeView.getLayerByName("field_work_collect_data"); }catch (TerraMobileException e) { e.printStackTrace(); } SimpleFeatureType ft = layer.getFeatureType(); GeometryType geometryType = ft.getGeometryDescriptor().getType(); List<Object> attributeValues = new ArrayList<Object>(); SimpleFeatureImpl feature = new SimpleFeatureImpl(null, attributeValues, ft); GeometryFactory factory=new GeometryFactory(); Coordinate coordinate = new Coordinate(-45.10,5.20); Point point = factory.createPoint(coordinate); feature.setDefaultGeometry(point); feature.setAttribute("location_name", "Teste de insercao");// testar com palavras acentuadas feature.setAttribute("temperature",25.1); feature.setAttribute("soil_ph",6); /* String date = formData.getString(key); Date dt = DateUtil.deserializeDate(date); if (dt == null) dt = new Date(); feature.setAttribute(key,dt); */ feature.setAttribute("collect_date",null); feature.setAttribute("termites",null); feature.setAttribute("crop_stage",null); feature.setAttribute("picture",null); /*String path = ""; if (ImageUtilities.isImagePath(path)) { byte[] blob = ImageUtilities.getImageFromPath(path, 1); feature.setAttribute("picture",blob); }else{ feature.setAttribute("picture",null); }*/ /* location_name" TEXT, "temperature" DOUBLE, "soil_ph" INTEGER, "collect_date" DATE, "termites" INTEGER, "crop_stage" TEXT, "picture" BLOB, */ try { GeoPackageService.writeLayerFeature(layer.getGeoPackage(), feature); } catch (QueryException e) { e.printStackTrace(); } } private void testVectorData() { GpkgLayer layer = null; SFSLayer l = null; try { layer = treeView.getLayerByName("inpe_area_de_estudo_canasat_2000"); l = AppGeoPackageService.getFeatures(layer); } catch (TerraMobileException e) { e.printStackTrace(); } MapView map = (MapView) findViewById(R.id.mapview); map.setTileSource(TileSourceFactory.MAPNIK); map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); Style defaultStyle = new Style(null, 0x901010AA, 1.0f, 0x20AA1010); KmlDocument kmlDocument = new KmlDocument(); Overlay overlay = l.buildOverlay(map, defaultStyle, null, kmlDocument); map.getOverlays().add(overlay); map.invalidate(); // map.zoomToBoundingBox(l.getBoundingBox()); /* String url = "http://mapsengine.google.com/map/kml?mid=z6IJfj90QEd4.kUUY9FoHFRdE"; KmlDocument kmlDocument = new KmlDocument(); kmlDocument.parseKMLUrl(url); FolderOverlay kmlOverlay = (FolderOverlay)kmlDocument.mKmlRoot.buildOverlay(map, null, null, kmlDocument); map.getOverlays().add(kmlOverlay); map.invalidate(); map.zoomToBoundingBox(kmlDocument.mKmlRoot.getBoundingBox());*/ } }
app/src/main/java/br/org/funcate/terramobile/controller/activity/MainActivity.java
package br.org.funcate.terramobile.controller.activity; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.net.ConnectivityManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.util.TypedValue; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ExpandableListView; import android.widget.TextView; import android.widget.Toast; import com.augtech.geoapi.feature.SimpleFeatureImpl; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.GeometryType; import org.osmdroid.bonuspack.kml.KmlDocument; import org.osmdroid.bonuspack.kml.Style; import org.osmdroid.bonuspack.overlays.FolderOverlay; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.Overlay; import java.io.File; import java.util.ArrayList; import java.util.List; import br.org.funcate.dynamicforms.images.ImageUtilities; import br.org.funcate.jgpkg.exception.QueryException; import br.org.funcate.jgpkg.service.GeoPackageService; import br.org.funcate.terramobile.R; import br.org.funcate.terramobile.configuration.ViewContextParameters; import br.org.funcate.terramobile.controller.activity.settings.SettingsActivity; import br.org.funcate.terramobile.model.Project; import br.org.funcate.terramobile.model.Settings; import br.org.funcate.terramobile.model.db.dao.ProjectDAO; import br.org.funcate.terramobile.model.db.dao.SettingsDAO; import br.org.funcate.terramobile.model.exception.TerraMobileException; import br.org.funcate.terramobile.model.geomsource.SFSLayer; import br.org.funcate.terramobile.model.gpkg.objects.GpkgLayer; import br.org.funcate.terramobile.model.tilesource.AppGeoPackageService; import br.org.funcate.terramobile.util.Message; import br.org.funcate.terramobile.util.ResourceUtil; public class MainActivity extends FragmentActivity { private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private ActionBar actionBar; private CharSequence mDrawerTitle; private CharSequence mTitle; private TreeView treeView; private ViewContextParameters parameters=new ViewContextParameters(); private Project mProject; private Settings settings; private ProjectDAO projectDAO; private SettingsDAO settingsDAO; private static int FORM_COLLECT_DATA = 222; // Progress bar private ProgressDialog progressDialog; private ProjectListFragment projectListFragment; /* public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK && requestCode == FORM_COLLECT_DATA) { Bundle extras = data.getBundleExtra(LibraryConstants.PREFS_KEY_FORM); try { AppGeoPackageService.storeData(this,extras); }catch (TerraMobileException tme) { //Message.showMessage(this, R.drawable.error, getResources().getString(R.string.error), tme.getMessage()); Message.showErrorMessage(this, R.string.error, R.string.missing_form_data); }catch (QueryException qe) { //Message.showMessage(this, R.drawable.error, getResources().getString(R.string.error), qe.getMessage()); Message.showErrorMessage(this, R.string.error, R.string.error_while_storing_form_data); } }else { Message.showErrorMessage(this, R.string.error, R.string.cancel_form_data); } }*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); actionBar = getActionBar(); PreferenceManager.setDefaultValues(this, R.xml.settings, false); settingsDAO = new SettingsDAO(this); if(settingsDAO.getById(1) == null){ settings = new Settings(); settings.setId(1); settings.setUrl(ResourceUtil.getStringResource(getResources(), R.string.terramobile_url)); // URL for test settingsDAO.insert(settings); } else{ settings = settingsDAO.getById(1); } File directory = ResourceUtil.getDirectory(this.getResources().getString(R.string.app_workspace_dir)); String fileName = settings.getCurrentProject(); String ext = this.getString(R.string.geopackage_extension); if(settings.getCurrentProject() != null) { projectDAO = new ProjectDAO(this); mProject = projectDAO.getByName(settings.getCurrentProject()); if(ResourceUtil.getGeoPackageByName(directory, ext, fileName) != null) { if(mProject == null) { Project project = new Project(); project.setId(null); project.setName(fileName); project.setFilePath(directory.getPath()); projectDAO.insert(project); mProject = projectDAO.getByName(settings.getCurrentProject()); } } else{ if(mProject != null){ if(projectDAO.remove(mProject.getId())){ Log.i("Remove project","Project removed"); } else Log.e("Remove project","Couldn't remove the project"); } } } treeView = new TreeView(this); mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // set a custom shadow that overlays the action_bar content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); int ActionBarTitleID = Resources.getSystem().getIdentifier("action_bar_title", "id", "android"); TextView ActionBarTextView = (TextView) this.findViewById(ActionBarTitleID); ActionBarTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.title_text_size)); actionBar.setDisplayHomeAsUpEnabled(true); // ActionBarDrawerToggle ties together the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, //host Activity mDrawerLayout, //DrawerLayout object R.drawable.ic_drawer, //nav drawer image to replace 'Up' caret R.string.drawer_open, //"open drawer" description for accessibility R.string.drawer_close //"close drawer" description for accessibility ) { public void onDrawerClosed(View view) { actionBar.setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { actionBar.setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { insertMapView(); } } @Override public void onBackPressed() { this.finish(); System.exit(0); return; } public ViewContextParameters getParameters(){ return parameters; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar, menu); MenuItem menuItem = menu.findItem(R.id.project); menuItem.setTitle(mProject != null ? mProject.toString() : "Project"); return super.onCreateOptionsMenu(menu); } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { ExpandableListView mDrawerList=treeView.getUIComponent(); if(mDrawerList==null) return false; MenuItem menuItem = menu.findItem(R.id.project); menuItem.setTitle(mProject != null?mProject.toString():"Project"); // If the nav drawer is open, hide action items related to the content view return super.onPrepareOptionsMenu(menu); } /** * This method is called when item from action bar is selected. * @param item, the menu item component * @return */ @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) return true; // Handle action buttons switch(item.getItemId()) { case R.id.project: projectListFragment = new ProjectListFragment(); projectListFragment.show(getFragmentManager(), "packageList"); return true; case R.id.acquire_new_point: FragmentManager fm = getSupportFragmentManager(); MapFragment fragment = (MapFragment)fm.findFragmentById(R.id.content_frame); // add an bookmark on map and show the related form fragment.startForm(); break; /* case R.id.test_vector_data: testVectorData(); break; case R.id.test_editable_layer: testEditableLayer(); break; case R.id.test_insert_sfs: testInsertSFS(); break; */ case R.id.settings: startActivity(new Intent(this, SettingsActivity.class)); break; case R.id.exit: this.finish(); System.exit(0); break; default: return super.onOptionsItemSelected(item); } return true; } public MapFragment getMapFragment() { FragmentManager fm = getSupportFragmentManager(); MapFragment fragment = (MapFragment)fm.findFragmentById(R.id.content_frame); return fragment; } private void insertMapView() { // update the action_bar content by replacing fragments Fragment fragment = new MapFragment(); /* Bundle args = new Bundle(); args.putStringArrayList(MapFragment.mLayers); fragment.setArguments(args);*/ FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); } @Override public void setTitle(CharSequence title) { mTitle = title; actionBar.setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } /** * Shows a progress bar with the download progress */ public void showProgressDialog(String message) { progressDialog = new ProgressDialog(this); progressDialog.setMessage(message); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.setMax(100); progressDialog.setProgress(0); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, MainActivity.this.getString(R.string.btn_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MainActivity.this.getProjectListFragment().getDownloadTask().cancel(true); } }); progressDialog.show(); } public void showLoadingDialog(String message) { progressDialog = new ProgressDialog(this); progressDialog.setMessage(message); progressDialog.setCancelable(false); progressDialog.show(); } public ProgressDialog getProgressDialog() { return progressDialog; } public TreeView getTreeView() { return treeView; } public ProjectListFragment getProjectListFragment() { return projectListFragment; } public Project getProject() { return mProject; } public void setProject(Project project) { this.mProject = project; settings.setCurrentProject(project!=null?project.getName():null); settingsDAO.update(settings); treeView.refreshTreeView(); invalidateOptionsMenu(); } private void testEditableLayer() { GpkgLayer layer = null; SFSLayer l = null; try { layer = treeView.getLayerByName("field_work_collect_data"); l = AppGeoPackageService.getFeatures(layer); } catch (TerraMobileException e) { e.printStackTrace(); } MapView map = (MapView) findViewById(R.id.mapview); map.setTileSource(TileSourceFactory.MAPNIK); map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); Style defaultStyle = new Style(null, 0x901010AA, 1.0f, 0x20AA1010); KmlDocument kmlDocument = new KmlDocument(); Overlay overlay = l.buildOverlay(map, defaultStyle, null, kmlDocument); map.getOverlays().add(overlay); map.invalidate(); } private void testInsertSFS() { GpkgLayer layer = null; try { layer = treeView.getLayerByName("field_work_collect_data"); }catch (TerraMobileException e) { e.printStackTrace(); } SimpleFeatureType ft = layer.getFeatureType(); GeometryType geometryType = ft.getGeometryDescriptor().getType(); List<Object> attributeValues = new ArrayList<Object>(); SimpleFeatureImpl feature = new SimpleFeatureImpl(null, attributeValues, ft); GeometryFactory factory=new GeometryFactory(); Coordinate coordinate = new Coordinate(-45.10,5.20); Point point = factory.createPoint(coordinate); feature.setDefaultGeometry(point); feature.setAttribute("location_name", "Teste de insercao");// testar com palavras acentuadas feature.setAttribute("temperature",25.1); feature.setAttribute("soil_ph",6); /* String date = formData.getString(key); Date dt = DateUtil.deserializeDate(date); if (dt == null) dt = new Date(); feature.setAttribute(key,dt); */ feature.setAttribute("collect_date",null); feature.setAttribute("termites",null); feature.setAttribute("crop_stage",null); feature.setAttribute("picture",null); /*String path = ""; if (ImageUtilities.isImagePath(path)) { byte[] blob = ImageUtilities.getImageFromPath(path, 1); feature.setAttribute("picture",blob); }else{ feature.setAttribute("picture",null); }*/ /* location_name" TEXT, "temperature" DOUBLE, "soil_ph" INTEGER, "collect_date" DATE, "termites" INTEGER, "crop_stage" TEXT, "picture" BLOB, */ try { GeoPackageService.writeLayerFeature(layer.getGeoPackage(), feature); } catch (QueryException e) { e.printStackTrace(); } } private void testVectorData() { GpkgLayer layer = null; SFSLayer l = null; try { layer = treeView.getLayerByName("inpe_area_de_estudo_canasat_2000"); l = AppGeoPackageService.getFeatures(layer); } catch (TerraMobileException e) { e.printStackTrace(); } MapView map = (MapView) findViewById(R.id.mapview); map.setTileSource(TileSourceFactory.MAPNIK); map.setBuiltInZoomControls(true); map.setMultiTouchControls(true); Style defaultStyle = new Style(null, 0x901010AA, 1.0f, 0x20AA1010); KmlDocument kmlDocument = new KmlDocument(); Overlay overlay = l.buildOverlay(map, defaultStyle, null, kmlDocument); map.getOverlays().add(overlay); map.invalidate(); // map.zoomToBoundingBox(l.getBoundingBox()); /* String url = "http://mapsengine.google.com/map/kml?mid=z6IJfj90QEd4.kUUY9FoHFRdE"; KmlDocument kmlDocument = new KmlDocument(); kmlDocument.parseKMLUrl(url); FolderOverlay kmlOverlay = (FolderOverlay)kmlDocument.mKmlRoot.buildOverlay(map, null, null, kmlDocument); map.getOverlays().add(kmlOverlay); map.invalidate(); map.zoomToBoundingBox(kmlDocument.mKmlRoot.getBoundingBox());*/ } }
Fixing current project loader, missing fileName on filePath
app/src/main/java/br/org/funcate/terramobile/controller/activity/MainActivity.java
Fixing current project loader, missing fileName on filePath
<ide><path>pp/src/main/java/br/org/funcate/terramobile/controller/activity/MainActivity.java <ide> if(settings.getCurrentProject() != null) { <ide> projectDAO = new ProjectDAO(this); <ide> mProject = projectDAO.getByName(settings.getCurrentProject()); <del> if(ResourceUtil.getGeoPackageByName(directory, ext, fileName) != null) { <add> File currentProject = ResourceUtil.getGeoPackageByName(directory, ext, fileName); <add> if(currentProject != null) { <ide> if(mProject == null) { <ide> Project project = new Project(); <ide> project.setId(null); <ide> project.setName(fileName); <del> project.setFilePath(directory.getPath()); <add> project.setFilePath(currentProject.getPath()); <ide> projectDAO.insert(project); <ide> <ide> mProject = projectDAO.getByName(settings.getCurrentProject());
Java
mit
6d22436362e5344a9bab7f23c001618be775c303
0
dbwiddis/oshi,hazendaz/oshi
/** * Oshi (https://github.com/dblock/oshi) * * Copyright (c) 2010 - 2016 The Oshi Project Team * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * dblock[at]dblock[dot]org * alessandro[at]perucchi[dot]org * widdis[at]gmail[dot]com * https://github.com/dblock/oshi/graphs/contributors */ package oshi.hardware.platform.linux; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.json.Json; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import oshi.hardware.Display; import oshi.json.NullAwareJsonObjectBuilder; import oshi.util.EdidUtil; import oshi.util.ExecutingCommand; import oshi.util.ParseUtil; /** * A Display * * @author widdis[at]gmail[dot]com */ public class LinuxDisplay implements Display { private static final Logger LOG = LoggerFactory.getLogger(LinuxDisplay.class); private byte[] edid; private JsonBuilderFactory jsonFactory = Json.createBuilderFactory(null); public LinuxDisplay(byte[] edid) { this.edid = edid; LOG.debug("Initialized LinuxDisplay"); } @Override public byte[] getEdid() { return Arrays.copyOf(edid, edid.length); } @Override public JsonObject toJSON() { return NullAwareJsonObjectBuilder.wrap(jsonFactory.createObjectBuilder()) .add("edid", EdidUtil.toString(getEdid())).build(); } /** * Gets Display Information * * @return An array of Display objects representing monitors, etc. */ public static Display[] getDisplays() { List<Display> displays = new ArrayList<Display>(); ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose"); if (xrandr != null) { boolean foundEdid = false; StringBuilder sb = new StringBuilder(); for (String s : xrandr) { if (s.contains("EDID")) { foundEdid = true; sb = new StringBuilder(); continue; } if (foundEdid) { sb.append(s.trim()); if (sb.length() >= 256) { String edidStr = sb.toString(); LOG.debug("Parsed EDID: {}", edidStr); Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr)); displays.add(display); foundEdid = false; } } } } return displays.toArray(new Display[displays.size()]); } }
src/main/java/oshi/hardware/platform/linux/LinuxDisplay.java
/** * Oshi (https://github.com/dblock/oshi) * * Copyright (c) 2010 - 2016 The Oshi Project Team * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * dblock[at]dblock[dot]org * alessandro[at]perucchi[dot]org * widdis[at]gmail[dot]com * https://github.com/dblock/oshi/graphs/contributors */ package oshi.hardware.platform.linux; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.json.Json; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import oshi.hardware.Display; import oshi.json.NullAwareJsonObjectBuilder; import oshi.util.EdidUtil; import oshi.util.ExecutingCommand; import oshi.util.ParseUtil; /** * A Display * * @author widdis[at]gmail[dot]com */ public class LinuxDisplay implements Display { private static final Logger LOG = LoggerFactory.getLogger(LinuxDisplay.class); private byte[] edid; private JsonBuilderFactory jsonFactory = Json.createBuilderFactory(null); public LinuxDisplay(byte[] edid) { this.edid = edid; LOG.debug("Initialized LinuxDisplay"); } @Override public byte[] getEdid() { return Arrays.copyOf(edid, edid.length); } @Override public JsonObject toJSON() { return NullAwareJsonObjectBuilder.wrap(jsonFactory.createObjectBuilder()) .add("edid", EdidUtil.toString(getEdid())).build(); } /** * Gets Display Information * * @return An array of Display objects representing monitors, etc. */ public static Display[] getDisplays() { List<Display> displays = new ArrayList<Display>(); ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose"); boolean foundEdid = false; StringBuilder sb = new StringBuilder(); for (String s : xrandr) { if (s.contains("EDID")) { foundEdid = true; sb = new StringBuilder(); continue; } if (foundEdid) { sb.append(s.trim()); if (sb.length() >= 256) { String edidStr = sb.toString(); LOG.debug("Parsed EDID: {}", edidStr); Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr)); displays.add(display); foundEdid = false; } } } return displays.toArray(new Display[displays.size()]); } }
Fix NPE with no xrandr command.
src/main/java/oshi/hardware/platform/linux/LinuxDisplay.java
Fix NPE with no xrandr command.
<ide><path>rc/main/java/oshi/hardware/platform/linux/LinuxDisplay.java <ide> public static Display[] getDisplays() { <ide> List<Display> displays = new ArrayList<Display>(); <ide> ArrayList<String> xrandr = ExecutingCommand.runNative("xrandr --verbose"); <del> boolean foundEdid = false; <del> StringBuilder sb = new StringBuilder(); <del> for (String s : xrandr) { <del> if (s.contains("EDID")) { <del> foundEdid = true; <del> sb = new StringBuilder(); <del> continue; <del> } <del> if (foundEdid) { <del> sb.append(s.trim()); <del> if (sb.length() >= 256) { <del> String edidStr = sb.toString(); <del> LOG.debug("Parsed EDID: {}", edidStr); <del> Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr)); <del> displays.add(display); <del> foundEdid = false; <add> if (xrandr != null) { <add> boolean foundEdid = false; <add> StringBuilder sb = new StringBuilder(); <add> for (String s : xrandr) { <add> if (s.contains("EDID")) { <add> foundEdid = true; <add> sb = new StringBuilder(); <add> continue; <add> } <add> if (foundEdid) { <add> sb.append(s.trim()); <add> if (sb.length() >= 256) { <add> String edidStr = sb.toString(); <add> LOG.debug("Parsed EDID: {}", edidStr); <add> Display display = new LinuxDisplay(ParseUtil.hexStringToByteArray(edidStr)); <add> displays.add(display); <add> foundEdid = false; <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
7c46eafed456a69cb70c035e48d13aa067d6257a
0
attatrol/Orekit,liscju/Orekit,liscju/Orekit,Yakushima/Orekit,CS-SI/Orekit,wardev/orekit,ProjectPersephone/Orekit,treeform/orekit,Yakushima/Orekit,attatrol/Orekit,petrushy/Orekit,petrushy/Orekit,CS-SI/Orekit,ProjectPersephone/Orekit
package fr.cs.orekit.frames.series; import java.io.ByteArrayInputStream; import java.io.InputStream; import fr.cs.orekit.errors.OrekitException; import fr.cs.orekit.frames.series.Development; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class DevelopmentTest extends TestCase { public void testBadData() { checkBadData(""); checkBadData("this is NOT an IERS nutation model file\n"); checkBadData(" 0.0 + 0.0 t - 0.0 t^2 - 0.0 t^3 - 0.0 t^4 + 0.0 t^5\n"); checkBadData(" 0.0 + 0.0 t - 0.0 t^2 - 0.0 t^3 - 0.0 t^4 + 0.0 t^5\n" + "j = 0 Nb of terms = 1\n"); } public void testNoFile() { try { InputStream stream = DevelopmentTest.class.getResourceAsStream("/fr/cs/orekit/resources/missing"); new Development(stream, 1.0, "missing"); fail("exception expected"); } catch (OrekitException oe) { // expected behaviour } } public void testSmall() { try { String data = " 0.0 + 0.0 t - 0.0 t^2 - 0.0 t^3 - 0.0 t^4 + 0.0 t^5\n" + "j = 0 Nb of terms = 1\n" + "1 0.0 0.0 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n"; Development nd = new Development(new ByteArrayInputStream(data.getBytes()), 1.0, ""); assertNotNull(nd); } catch (OrekitException oe) { fail(oe.getMessage()); } } public void testSecondsMarkers() { try { String data = " 0''.0 + 0''.0 t - 0''.0 t^2 - 0''.0 t^3 - 0''.0 t^4 + 0''.0 t^5\n" + "j = 0 Nb of terms = 1\n" + "1 0.0 0.0 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n"; Development nd = new Development(new ByteArrayInputStream(data.getBytes()), 1.0, ""); assertNotNull(nd); } catch (OrekitException oe) { fail(oe.getMessage()); } } public void testExtract() throws OrekitException { String data = "Expression for the X coordinate of the CIP in the GCRS based on the IAU2000A\n" + "precession-nutation model\n" + "\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + "X = polynomial part + non-polynomial part\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + "Polynomial part (unit microarcsecond)\n" + "\n" + " -16616.99 + 2004191742.88 t - 427219.05 t^2 - 198620.54 t^3 - 46.05 t^4 + 5.98 t^5\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + "Non-polynomial part (unit microarcsecond)\n" + "(ARG being for various combination of the fundamental arguments of the nutation theory)\n" + "\n" + " Sum_i[a_{s,0})_i * sin(ARG) + a_{c,0})_i * cos(ARG)] \n" + "\n" + "+ Sum_i)j=1,4 [a_{s,j})_i * t^j * sin(ARG) + a_{c,j})_i * cos(ARG)] * t^j]\n" + "\n" + "The Table below provides the values for a_{s,j})_i and a_{c,j})_i\n" + "\n" + "The expressions for the fundamental arguments appearing in columns 4 to 8 (luni-solar part) \n" + "and in columns 6 to 17 (planetary part) are those of the IERS Conventions 2000\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + " i a_{s,j})_i a_{c,j})_i l l' F D Om L_Me L_Ve L_E L_Ma L_J L_Sa L_U L_Ne p_A\n" + "\n" + "----------------------------------------------------------------------\n" + "-16616.99 + 2004191742.88 t - 427219.05 t^2 - 198620.54 t^3 - 46.05 t^4 + 5.98 t^5\n" + "j = 0 Nb of terms = 2\n" + "\n" + " 1 -6844318.44 1328.67 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + "1306 0.11 0.00 0 0 4 -4 4 0 0 0 0 0 0 0 0 0\n" + "\n" + "j = 1 Nb of terms = 2\n" + "\n" + " 1307 -3328.48 205833.15 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + " 1559 0.00 -0.10 1 -1 -2 -2 -1 0 0 0 0 0 0 0 0 0\n" + "\n" + " j = 2 Nb of terms = 2\n" + "\n" + " 1560 2038.00 82.26 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + " 1595 -0.12 0.00 1 0 -2 -2 -1 0 0 0 0 0 0 0 0 0\n" + " \n" + " j = 3 Nb of terms = 2\n" + "\n" + " 1596 1.76 -20.39 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + " 1599 0.00 0.20 0 0 0 0 2 0 0 0 0 0 0 0 0 0\n" + "\n" + " j = 4 Nb of terms = 1\n" + " \n" + " 1600 -0.10 -0.02 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n"; assertNotNull(new Development(new ByteArrayInputStream(data.getBytes()), 1.0, "dummy")); } public void testTrueFiles() throws OrekitException { String directory = "/META-INF/IERS-conventions-2003/"; InputStream xStream = getClass().getResourceAsStream(directory + "tab5.2a.txt"); assertNotNull(new Development(xStream, 1.0, "tab5.2a.txt")); InputStream yStream = getClass().getResourceAsStream(directory + "tab5.2b.txt"); assertNotNull(new Development(yStream, 1.0, "tab5.2b.txt")); InputStream zStream = getClass().getResourceAsStream(directory + "tab5.2c.txt"); assertNotNull(new Development(zStream, 1.0, "tab5.2c.txt")); InputStream gstStream = getClass().getResourceAsStream(directory + "tab5.4.txt"); assertNotNull(new Development(gstStream, 1.0, "tab5.4.txt")); } private void checkBadData(String data) { try { new Development(new ByteArrayInputStream(data.getBytes()), 1.0, "<file-content>" + data + "</file-content>"); fail("an exception should have been thrown"); } catch (OrekitException oe) { // expected behaviour } catch (Exception e) { fail("wrong exception type caught"); } } public static Test suite() { return new TestSuite(DevelopmentTest.class); } }
src/test/java/fr/cs/orekit/frames/series/DevelopmentTest.java
package fr.cs.orekit.frames.series; import java.io.ByteArrayInputStream; import java.io.InputStream; import fr.cs.orekit.errors.OrekitException; import fr.cs.orekit.frames.series.Development; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class DevelopmentTest extends TestCase { public void testBadData() { checkBadData(""); checkBadData("this is NOT an IERS nutation model file\n"); checkBadData(" 0.0 + 0.0 t - 0.0 t^2 - 0.0 t^3 - 0.0 t^4 + 0.0 t^5\n"); checkBadData(" 0.0 + 0.0 t - 0.0 t^2 - 0.0 t^3 - 0.0 t^4 + 0.0 t^5\n" + "j = 0 Nb of terms = 1\n"); } public void testNoFile() { try { InputStream stream = DevelopmentTest.class.getResourceAsStream("/fr.cs/orekit/resources/missing"); new Development(stream, 1.0, "missing"); fail("exception expected"); } catch (OrekitException oe) { // expected behaviour } } public void testSmall() { try { String data = " 0.0 + 0.0 t - 0.0 t^2 - 0.0 t^3 - 0.0 t^4 + 0.0 t^5\n" + "j = 0 Nb of terms = 1\n" + "1 0.0 0.0 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n"; Development nd = new Development(new ByteArrayInputStream(data.getBytes()), 1.0, ""); assertNotNull(nd); } catch (OrekitException oe) { fail(oe.getMessage()); } } public void testSecondsMarkers() { try { String data = " 0''.0 + 0''.0 t - 0''.0 t^2 - 0''.0 t^3 - 0''.0 t^4 + 0''.0 t^5\n" + "j = 0 Nb of terms = 1\n" + "1 0.0 0.0 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n"; Development nd = new Development(new ByteArrayInputStream(data.getBytes()), 1.0, ""); assertNotNull(nd); } catch (OrekitException oe) { fail(oe.getMessage()); } } public void testExtract() throws OrekitException { String data = "Expression for the X coordinate of the CIP in the GCRS based on the IAU2000A\n" + "precession-nutation model\n" + "\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + "X = polynomial part + non-polynomial part\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + "Polynomial part (unit microarcsecond)\n" + "\n" + " -16616.99 + 2004191742.88 t - 427219.05 t^2 - 198620.54 t^3 - 46.05 t^4 + 5.98 t^5\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + "Non-polynomial part (unit microarcsecond)\n" + "(ARG being for various combination of the fundamental arguments of the nutation theory)\n" + "\n" + " Sum_i[a_{s,0})_i * sin(ARG) + a_{c,0})_i * cos(ARG)] \n" + "\n" + "+ Sum_i)j=1,4 [a_{s,j})_i * t^j * sin(ARG) + a_{c,j})_i * cos(ARG)] * t^j]\n" + "\n" + "The Table below provides the values for a_{s,j})_i and a_{c,j})_i\n" + "\n" + "The expressions for the fundamental arguments appearing in columns 4 to 8 (luni-solar part) \n" + "and in columns 6 to 17 (planetary part) are those of the IERS Conventions 2000\n" + "\n" + "----------------------------------------------------------------------\n" + "\n" + " i a_{s,j})_i a_{c,j})_i l l' F D Om L_Me L_Ve L_E L_Ma L_J L_Sa L_U L_Ne p_A\n" + "\n" + "----------------------------------------------------------------------\n" + "-16616.99 + 2004191742.88 t - 427219.05 t^2 - 198620.54 t^3 - 46.05 t^4 + 5.98 t^5\n" + "j = 0 Nb of terms = 2\n" + "\n" + " 1 -6844318.44 1328.67 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + "1306 0.11 0.00 0 0 4 -4 4 0 0 0 0 0 0 0 0 0\n" + "\n" + "j = 1 Nb of terms = 2\n" + "\n" + " 1307 -3328.48 205833.15 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + " 1559 0.00 -0.10 1 -1 -2 -2 -1 0 0 0 0 0 0 0 0 0\n" + "\n" + " j = 2 Nb of terms = 2\n" + "\n" + " 1560 2038.00 82.26 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + " 1595 -0.12 0.00 1 0 -2 -2 -1 0 0 0 0 0 0 0 0 0\n" + " \n" + " j = 3 Nb of terms = 2\n" + "\n" + " 1596 1.76 -20.39 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n" + " 1599 0.00 0.20 0 0 0 0 2 0 0 0 0 0 0 0 0 0\n" + "\n" + " j = 4 Nb of terms = 1\n" + " \n" + " 1600 -0.10 -0.02 0 0 0 0 1 0 0 0 0 0 0 0 0 0\n"; assertNotNull(new Development(new ByteArrayInputStream(data.getBytes()), 1.0, "dummy")); } public void testTrueFiles() throws OrekitException { String directory = "/META-INF/IERS-conventions-2003/"; InputStream xStream = getClass().getResourceAsStream(directory + "tab5.2a.txt"); assertNotNull(new Development(xStream, 1.0, "tab5.2a.txt")); InputStream yStream = getClass().getResourceAsStream(directory + "tab5.2b.txt"); assertNotNull(new Development(yStream, 1.0, "tab5.2b.txt")); InputStream zStream = getClass().getResourceAsStream(directory + "tab5.2c.txt"); assertNotNull(new Development(zStream, 1.0, "tab5.2c.txt")); InputStream gstStream = getClass().getResourceAsStream(directory + "tab5.4.txt"); assertNotNull(new Development(gstStream, 1.0, "tab5.4.txt")); } private void checkBadData(String data) { try { new Development(new ByteArrayInputStream(data.getBytes()), 1.0, "<file-content>" + data + "</file-content>"); fail("an exception should have been thrown"); } catch (OrekitException oe) { // expected behaviour } catch (Exception e) { fail("wrong exception type caught"); } } public static Test suite() { return new TestSuite(DevelopmentTest.class); } }
fixed a typo
src/test/java/fr/cs/orekit/frames/series/DevelopmentTest.java
fixed a typo
<ide><path>rc/test/java/fr/cs/orekit/frames/series/DevelopmentTest.java <ide> public void testNoFile() { <ide> try { <ide> InputStream stream = <del> DevelopmentTest.class.getResourceAsStream("/fr.cs/orekit/resources/missing"); <add> DevelopmentTest.class.getResourceAsStream("/fr/cs/orekit/resources/missing"); <ide> new Development(stream, 1.0, "missing"); <ide> fail("exception expected"); <ide> } catch (OrekitException oe) {
Java
mit
82c1ae614c4ddad5a355a2780b7370faee39020a
0
Um-Mitternacht/Witchworks,backuporg/Witchworks
package com.witchworks.common.block.magic; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.witchworks.common.block.BlockMod; import com.witchworks.common.block.ModBlocks; import com.witchworks.common.item.ModItems; import com.witchworks.common.lib.LibBlockName; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureAttribute; import net.minecraft.entity.monster.EntityBlaze; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.monster.EntityGhast; import net.minecraft.entity.monster.EntityVex; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.*; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.List; import java.util.Random; import java.util.Set; /** * This class was created by BerciTheBeast on 27.3.2017. * It's distributed as part of Witchworks under * the MIT license. */ @SuppressWarnings("WeakerAccess") public class BlockSaltBarrier extends BlockMod { public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> NORTH = PropertyEnum.create("north", BlockSaltBarrier.EnumAttachPosition.class); public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> EAST = PropertyEnum.create("east", BlockSaltBarrier.EnumAttachPosition.class); public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> SOUTH = PropertyEnum.create("south", BlockSaltBarrier.EnumAttachPosition.class); public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> WEST = PropertyEnum.create("west", BlockSaltBarrier.EnumAttachPosition.class); private static final AxisAlignedBB[] SALT_BARRIER_AABB = new AxisAlignedBB[]{new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 1.0D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 1.0D, 0.0625D, 1.0D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 1.0D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.0625D, 1.0D)}; private final Set<BlockPos> blocksNeedingUpdate = Sets.newHashSet(); public BlockSaltBarrier() { super(LibBlockName.SALT_BARRIER, Material.CIRCUITS); this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, BlockSaltBarrier.EnumAttachPosition.NONE).withProperty(EAST, BlockSaltBarrier.EnumAttachPosition.NONE).withProperty(SOUTH, BlockSaltBarrier.EnumAttachPosition.NONE).withProperty(WEST, BlockSaltBarrier.EnumAttachPosition.NONE)); setSound(SoundType.CLOTH); } private static boolean canConnectTo(IBlockState blockState) { final Block block = blockState.getBlock(); return block == ModBlocks.salt_barrier; } private static boolean canConnectUpwardsTo(IBlockAccess worldIn, BlockPos pos) { return canConnectTo(worldIn.getBlockState(pos)); } private static int getAABBIndex(IBlockState state) { int i = 0; final boolean flag = state.getValue(NORTH) != BlockSaltBarrier.EnumAttachPosition.NONE; final boolean flag1 = state.getValue(EAST) != BlockSaltBarrier.EnumAttachPosition.NONE; final boolean flag2 = state.getValue(SOUTH) != BlockSaltBarrier.EnumAttachPosition.NONE; final boolean flag3 = state.getValue(WEST) != BlockSaltBarrier.EnumAttachPosition.NONE; if (flag || flag2 && !flag1 && !flag3) { i |= 1 << EnumFacing.NORTH.getHorizontalIndex(); } if (flag1 || flag3 && !flag && !flag2) { i |= 1 << EnumFacing.EAST.getHorizontalIndex(); } if (flag2 || flag && !flag1 && !flag3) { i |= 1 << EnumFacing.SOUTH.getHorizontalIndex(); } if (flag3 || flag1 && !flag && !flag2) { i |= 1 << EnumFacing.WEST.getHorizontalIndex(); } return i; } @SuppressWarnings("deprecation") @Override public IBlockState getStateFromMeta(int meta) { return this.getDefaultState(); } @Override public int getMetaFromState(IBlockState state) { return 0; } @SuppressWarnings("deprecation") @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { state = state.withProperty(WEST, this.getAttachPosition(worldIn, pos, EnumFacing.WEST)); state = state.withProperty(EAST, this.getAttachPosition(worldIn, pos, EnumFacing.EAST)); state = state.withProperty(NORTH, this.getAttachPosition(worldIn, pos, EnumFacing.NORTH)); state = state.withProperty(SOUTH, this.getAttachPosition(worldIn, pos, EnumFacing.SOUTH)); return state; } private BlockSaltBarrier.EnumAttachPosition getAttachPosition(IBlockAccess worldIn, BlockPos pos, EnumFacing direction) { final BlockPos blockpos = pos.offset(direction); final IBlockState iblockstate = worldIn.getBlockState(pos.offset(direction)); if (!canConnectTo(worldIn.getBlockState(blockpos)) && (iblockstate.isNormalCube() || !canConnectUpwardsTo(worldIn, blockpos.down()))) { final IBlockState iblockstate1 = worldIn.getBlockState(pos.up()); if (!iblockstate1.isNormalCube()) { final boolean flag = worldIn.getBlockState(blockpos).isSideSolid(worldIn, blockpos, EnumFacing.UP) || worldIn.getBlockState(blockpos).getBlock() == Blocks.GLOWSTONE; if (flag && canConnectUpwardsTo(worldIn, blockpos.up())) { if (iblockstate.isBlockNormalCube()) { return BlockSaltBarrier.EnumAttachPosition.UP; } return BlockSaltBarrier.EnumAttachPosition.SIDE; } } return BlockSaltBarrier.EnumAttachPosition.NONE; } else { return BlockSaltBarrier.EnumAttachPosition.SIDE; } } @SuppressWarnings("deprecation") @Override public IBlockState withRotation(IBlockState state, Rotation rot) { switch (rot) { case CLOCKWISE_180: return state.withProperty(NORTH, state.getValue(SOUTH)).withProperty(EAST, state.getValue(WEST)).withProperty(SOUTH, state.getValue(NORTH)).withProperty(WEST, state.getValue(EAST)); case COUNTERCLOCKWISE_90: return state.withProperty(NORTH, state.getValue(EAST)).withProperty(EAST, state.getValue(SOUTH)).withProperty(SOUTH, state.getValue(WEST)).withProperty(WEST, state.getValue(NORTH)); case CLOCKWISE_90: return state.withProperty(NORTH, state.getValue(WEST)).withProperty(EAST, state.getValue(NORTH)).withProperty(SOUTH, state.getValue(EAST)).withProperty(WEST, state.getValue(SOUTH)); default: return state; } } @SuppressWarnings("deprecation") @Override public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { switch (mirrorIn) { case LEFT_RIGHT: return state.withProperty(NORTH, state.getValue(SOUTH)).withProperty(SOUTH, state.getValue(NORTH)); case FRONT_BACK: return state.withProperty(EAST, state.getValue(WEST)).withProperty(WEST, state.getValue(EAST)); default: return super.withMirror(state, mirrorIn); } } @SuppressWarnings("deprecation") @Override public boolean isFullCube(IBlockState state) { return false; } @SuppressWarnings("deprecation") @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return SALT_BARRIER_AABB[getAABBIndex(state.getActualState(source, pos))]; } @SuppressWarnings("deprecation") @Override @Nullable public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return NULL_AABB; } @SuppressWarnings("deprecation") @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) { final double d0 = (double) pos.getX() + 0.5D + ((double) rand.nextFloat() - 0.5D) * 0.2D; final double d1 = (double) ((float) pos.getY() + 0.0625F); final double d2 = (double) pos.getZ() + 0.5D + ((double) rand.nextFloat() - 0.5D) * 0.2D; final float f = (float) 3 / 15.0F; final float f1 = f * 0.6F + 0.4F; final float f2 = Math.max(0.0F, f * f * 0.7F - 0.5F); final float f3 = Math.max(0.0F, f * f * 0.6F - 0.7F); worldIn.spawnParticle(EnumParticleTypes.ENCHANTMENT_TABLE, d0, d1, d2, (double) f1, (double) f2, (double) f3); } @SuppressWarnings("deprecation") @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos toPos) { if (!worldIn.isRemote) { if (this.canPlaceBlockAt(worldIn, pos)) { this.updateSurroundingSalt(worldIn, state); } else { this.dropBlockAsItem(worldIn, pos, state, 0); worldIn.setBlockToAir(pos); } } } @Override public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { this.updateSurroundingSalt(worldIn, state); for (EnumFacing enumfacing : EnumFacing.Plane.VERTICAL) { worldIn.notifyNeighborsOfStateChange(pos.offset(enumfacing), this, true); } for (EnumFacing enumfacing1 : EnumFacing.Plane.HORIZONTAL) { this.notifyBarrierNeighborsOfStateChange(worldIn, pos.offset(enumfacing1)); } for (EnumFacing enumfacing2 : EnumFacing.Plane.HORIZONTAL) { final BlockPos blockpos = pos.offset(enumfacing2); if (worldIn.getBlockState(blockpos).isNormalCube()) { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.up()); } else { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.down()); } } } } private IBlockState updateSurroundingSalt(World worldIn, IBlockState state) { final List<BlockPos> list = Lists.newArrayList(this.blocksNeedingUpdate); this.blocksNeedingUpdate.clear(); for (BlockPos blockpos : list) { worldIn.notifyNeighborsOfStateChange(blockpos, this, true); } return state; } private void notifyBarrierNeighborsOfStateChange(World worldIn, BlockPos pos) { if (worldIn.getBlockState(pos).getBlock() == this) { worldIn.notifyNeighborsOfStateChange(pos, this, true); for (EnumFacing enumfacing : EnumFacing.values()) { worldIn.notifyNeighborsOfStateChange(pos.offset(enumfacing), this, true); } } } @Override public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); if (!worldIn.isRemote) { for (EnumFacing enumfacing : EnumFacing.values()) { worldIn.notifyNeighborsOfStateChange(pos.offset(enumfacing), this, true); } this.updateSurroundingSalt(worldIn, state); for (EnumFacing enumfacing1 : EnumFacing.Plane.HORIZONTAL) { this.notifyBarrierNeighborsOfStateChange(worldIn, pos.offset(enumfacing1)); } for (EnumFacing enumfacing2 : EnumFacing.Plane.HORIZONTAL) { final BlockPos blockpos = pos.offset(enumfacing2); if (worldIn.getBlockState(blockpos).isNormalCube()) { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.up()); } else { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.down()); } } } } @SuppressWarnings("deprecation") @Override public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { if (entityIn instanceof EntityLivingBase && (((EntityLivingBase) entityIn).getCreatureAttribute() == EnumCreatureAttribute.UNDEAD)) { collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 10, 0)); } if (entityIn instanceof EntityLivingBase && (((EntityLivingBase) entityIn).getCreatureAttribute() == EnumCreatureAttribute.ARTHROPOD)) { entityIn.attackEntityFrom(DamageSource.MAGIC, 5); } if (entityIn instanceof EntityBlaze) { collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); } if (entityIn instanceof EntityEnderman) { collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); } if (entityIn instanceof EntityGhast) { collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); } if (entityIn instanceof EntityVex) { collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); } } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return ModItems.salt; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } @SuppressWarnings("deprecation") @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return worldIn.getBlockState(pos.down()).isTopSolid() || worldIn.getBlockState(pos.down()).getBlock() == Blocks.GLOWSTONE; } @SuppressWarnings("deprecation") @Override public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { return new ItemStack(ModItems.salt); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, NORTH, EAST, SOUTH, WEST); } private enum EnumAttachPosition implements IStringSerializable { UP("up"), SIDE("side"), NONE("none"); private final String name; EnumAttachPosition(String name) { this.name = name; } public String toString() { return this.getName(); } public String getName() { return this.name; } } }
src/main/java/com/witchworks/common/block/magic/BlockSaltBarrier.java
package com.witchworks.common.block.magic; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.witchworks.common.block.BlockMod; import com.witchworks.common.block.ModBlocks; import com.witchworks.common.item.ModItems; import com.witchworks.common.lib.LibBlockName; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.*; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.List; import java.util.Random; import java.util.Set; /** * This class was created by BerciTheBeast on 27.3.2017. * It's distributed as part of Witchworks under * the MIT license. */ @SuppressWarnings("WeakerAccess") public class BlockSaltBarrier extends BlockMod { public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> NORTH = PropertyEnum.create("north", BlockSaltBarrier.EnumAttachPosition.class); public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> EAST = PropertyEnum.create("east", BlockSaltBarrier.EnumAttachPosition.class); public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> SOUTH = PropertyEnum.create("south", BlockSaltBarrier.EnumAttachPosition.class); public static final PropertyEnum<BlockSaltBarrier.EnumAttachPosition> WEST = PropertyEnum.create("west", BlockSaltBarrier.EnumAttachPosition.class); private static final AxisAlignedBB[] SALT_BARRIER_AABB = new AxisAlignedBB[]{new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.8125D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.8125D, 0.0625D, 1.0D), new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.1875D, 1.0D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.1875D, 1.0D, 0.0625D, 1.0D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.1875D, 0.0D, 0.0D, 1.0D, 0.0625D, 1.0D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.0625D, 0.8125D), new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.0625D, 1.0D)}; private final Set<BlockPos> blocksNeedingUpdate = Sets.newHashSet(); public BlockSaltBarrier() { super(LibBlockName.SALT_BARRIER, Material.CIRCUITS); this.setDefaultState(this.blockState.getBaseState().withProperty(NORTH, BlockSaltBarrier.EnumAttachPosition.NONE).withProperty(EAST, BlockSaltBarrier.EnumAttachPosition.NONE).withProperty(SOUTH, BlockSaltBarrier.EnumAttachPosition.NONE).withProperty(WEST, BlockSaltBarrier.EnumAttachPosition.NONE)); setSound(SoundType.CLOTH); } private static boolean canConnectTo(IBlockState blockState) { final Block block = blockState.getBlock(); return block == ModBlocks.salt_barrier; } private static boolean canConnectUpwardsTo(IBlockAccess worldIn, BlockPos pos) { return canConnectTo(worldIn.getBlockState(pos)); } private static int getAABBIndex(IBlockState state) { int i = 0; final boolean flag = state.getValue(NORTH) != BlockSaltBarrier.EnumAttachPosition.NONE; final boolean flag1 = state.getValue(EAST) != BlockSaltBarrier.EnumAttachPosition.NONE; final boolean flag2 = state.getValue(SOUTH) != BlockSaltBarrier.EnumAttachPosition.NONE; final boolean flag3 = state.getValue(WEST) != BlockSaltBarrier.EnumAttachPosition.NONE; if (flag || flag2 && !flag1 && !flag3) { i |= 1 << EnumFacing.NORTH.getHorizontalIndex(); } if (flag1 || flag3 && !flag && !flag2) { i |= 1 << EnumFacing.EAST.getHorizontalIndex(); } if (flag2 || flag && !flag1 && !flag3) { i |= 1 << EnumFacing.SOUTH.getHorizontalIndex(); } if (flag3 || flag1 && !flag && !flag2) { i |= 1 << EnumFacing.WEST.getHorizontalIndex(); } return i; } @SuppressWarnings("deprecation") @Override public IBlockState getStateFromMeta(int meta) { return this.getDefaultState(); } @Override public int getMetaFromState(IBlockState state) { return 0; } @SuppressWarnings("deprecation") @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { state = state.withProperty(WEST, this.getAttachPosition(worldIn, pos, EnumFacing.WEST)); state = state.withProperty(EAST, this.getAttachPosition(worldIn, pos, EnumFacing.EAST)); state = state.withProperty(NORTH, this.getAttachPosition(worldIn, pos, EnumFacing.NORTH)); state = state.withProperty(SOUTH, this.getAttachPosition(worldIn, pos, EnumFacing.SOUTH)); return state; } private BlockSaltBarrier.EnumAttachPosition getAttachPosition(IBlockAccess worldIn, BlockPos pos, EnumFacing direction) { final BlockPos blockpos = pos.offset(direction); final IBlockState iblockstate = worldIn.getBlockState(pos.offset(direction)); if (!canConnectTo(worldIn.getBlockState(blockpos)) && (iblockstate.isNormalCube() || !canConnectUpwardsTo(worldIn, blockpos.down()))) { final IBlockState iblockstate1 = worldIn.getBlockState(pos.up()); if (!iblockstate1.isNormalCube()) { final boolean flag = worldIn.getBlockState(blockpos).isSideSolid(worldIn, blockpos, EnumFacing.UP) || worldIn.getBlockState(blockpos).getBlock() == Blocks.GLOWSTONE; if (flag && canConnectUpwardsTo(worldIn, blockpos.up())) { if (iblockstate.isBlockNormalCube()) { return BlockSaltBarrier.EnumAttachPosition.UP; } return BlockSaltBarrier.EnumAttachPosition.SIDE; } } return BlockSaltBarrier.EnumAttachPosition.NONE; } else { return BlockSaltBarrier.EnumAttachPosition.SIDE; } } @SuppressWarnings("deprecation") @Override public IBlockState withRotation(IBlockState state, Rotation rot) { switch (rot) { case CLOCKWISE_180: return state.withProperty(NORTH, state.getValue(SOUTH)).withProperty(EAST, state.getValue(WEST)).withProperty(SOUTH, state.getValue(NORTH)).withProperty(WEST, state.getValue(EAST)); case COUNTERCLOCKWISE_90: return state.withProperty(NORTH, state.getValue(EAST)).withProperty(EAST, state.getValue(SOUTH)).withProperty(SOUTH, state.getValue(WEST)).withProperty(WEST, state.getValue(NORTH)); case CLOCKWISE_90: return state.withProperty(NORTH, state.getValue(WEST)).withProperty(EAST, state.getValue(NORTH)).withProperty(SOUTH, state.getValue(EAST)).withProperty(WEST, state.getValue(SOUTH)); default: return state; } } @SuppressWarnings("deprecation") @Override public IBlockState withMirror(IBlockState state, Mirror mirrorIn) { switch (mirrorIn) { case LEFT_RIGHT: return state.withProperty(NORTH, state.getValue(SOUTH)).withProperty(SOUTH, state.getValue(NORTH)); case FRONT_BACK: return state.withProperty(EAST, state.getValue(WEST)).withProperty(WEST, state.getValue(EAST)); default: return super.withMirror(state, mirrorIn); } } @SuppressWarnings("deprecation") @Override public boolean isFullCube(IBlockState state) { return false; } @SuppressWarnings("deprecation") @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return SALT_BARRIER_AABB[getAABBIndex(state.getActualState(source, pos))]; } @SuppressWarnings("deprecation") @Override @Nullable public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return NULL_AABB; } @SuppressWarnings("deprecation") @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override @SideOnly(Side.CLIENT) public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) { final double d0 = (double) pos.getX() + 0.5D + ((double) rand.nextFloat() - 0.5D) * 0.2D; final double d1 = (double) ((float) pos.getY() + 0.0625F); final double d2 = (double) pos.getZ() + 0.5D + ((double) rand.nextFloat() - 0.5D) * 0.2D; final float f = (float) 3 / 15.0F; final float f1 = f * 0.6F + 0.4F; final float f2 = Math.max(0.0F, f * f * 0.7F - 0.5F); final float f3 = Math.max(0.0F, f * f * 0.6F - 0.7F); worldIn.spawnParticle(EnumParticleTypes.ENCHANTMENT_TABLE, d0, d1, d2, (double) f1, (double) f2, (double) f3); } @SuppressWarnings("deprecation") @Override public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos toPos) { if (!worldIn.isRemote) { if (this.canPlaceBlockAt(worldIn, pos)) { this.updateSurroundingSalt(worldIn, state); } else { this.dropBlockAsItem(worldIn, pos, state, 0); worldIn.setBlockToAir(pos); } } } @Override public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { this.updateSurroundingSalt(worldIn, state); for (EnumFacing enumfacing : EnumFacing.Plane.VERTICAL) { worldIn.notifyNeighborsOfStateChange(pos.offset(enumfacing), this, true); } for (EnumFacing enumfacing1 : EnumFacing.Plane.HORIZONTAL) { this.notifyBarrierNeighborsOfStateChange(worldIn, pos.offset(enumfacing1)); } for (EnumFacing enumfacing2 : EnumFacing.Plane.HORIZONTAL) { final BlockPos blockpos = pos.offset(enumfacing2); if (worldIn.getBlockState(blockpos).isNormalCube()) { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.up()); } else { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.down()); } } } } private IBlockState updateSurroundingSalt(World worldIn, IBlockState state) { final List<BlockPos> list = Lists.newArrayList(this.blocksNeedingUpdate); this.blocksNeedingUpdate.clear(); for (BlockPos blockpos : list) { worldIn.notifyNeighborsOfStateChange(blockpos, this, true); } return state; } private void notifyBarrierNeighborsOfStateChange(World worldIn, BlockPos pos) { if (worldIn.getBlockState(pos).getBlock() == this) { worldIn.notifyNeighborsOfStateChange(pos, this, true); for (EnumFacing enumfacing : EnumFacing.values()) { worldIn.notifyNeighborsOfStateChange(pos.offset(enumfacing), this, true); } } } @Override public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); if (!worldIn.isRemote) { for (EnumFacing enumfacing : EnumFacing.values()) { worldIn.notifyNeighborsOfStateChange(pos.offset(enumfacing), this, true); } this.updateSurroundingSalt(worldIn, state); for (EnumFacing enumfacing1 : EnumFacing.Plane.HORIZONTAL) { this.notifyBarrierNeighborsOfStateChange(worldIn, pos.offset(enumfacing1)); } for (EnumFacing enumfacing2 : EnumFacing.Plane.HORIZONTAL) { final BlockPos blockpos = pos.offset(enumfacing2); if (worldIn.getBlockState(blockpos).isNormalCube()) { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.up()); } else { this.notifyBarrierNeighborsOfStateChange(worldIn, blockpos.down()); } } } } @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { return ModItems.salt; } @Override @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.CUTOUT; } @SuppressWarnings("deprecation") @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return worldIn.getBlockState(pos.down()).isTopSolid() || worldIn.getBlockState(pos.down()).getBlock() == Blocks.GLOWSTONE; } @SuppressWarnings("deprecation") @Override public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state) { return new ItemStack(ModItems.salt); } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, NORTH, EAST, SOUTH, WEST); } private enum EnumAttachPosition implements IStringSerializable { UP("up"), SIDE("side"), NONE("none"); private final String name; EnumAttachPosition(String name) { this.name = name; } public String toString() { return this.getName(); } public String getName() { return this.name; } } }
Made salt barriers functional Finally figured out what Berci had issues with. Sorry Zabi.
src/main/java/com/witchworks/common/block/magic/BlockSaltBarrier.java
Made salt barriers functional
<ide><path>rc/main/java/com/witchworks/common/block/magic/BlockSaltBarrier.java <ide> import net.minecraft.block.properties.PropertyEnum; <ide> import net.minecraft.block.state.BlockStateContainer; <ide> import net.minecraft.block.state.IBlockState; <add>import net.minecraft.entity.Entity; <add>import net.minecraft.entity.EntityLivingBase; <add>import net.minecraft.entity.EnumCreatureAttribute; <add>import net.minecraft.entity.monster.EntityBlaze; <add>import net.minecraft.entity.monster.EntityEnderman; <add>import net.minecraft.entity.monster.EntityGhast; <add>import net.minecraft.entity.monster.EntityVex; <ide> import net.minecraft.init.Blocks; <ide> import net.minecraft.item.Item; <ide> import net.minecraft.item.ItemStack; <ide> } <ide> } <ide> <add> @SuppressWarnings("deprecation") <add> @Override <add> public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { <add> if (entityIn instanceof EntityLivingBase && (((EntityLivingBase) entityIn).getCreatureAttribute() == EnumCreatureAttribute.UNDEAD)) { <add> collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 10, 0)); <add> } <add> if (entityIn instanceof EntityLivingBase && (((EntityLivingBase) entityIn).getCreatureAttribute() == EnumCreatureAttribute.ARTHROPOD)) { <add> entityIn.attackEntityFrom(DamageSource.MAGIC, 5); <add> } <add> if (entityIn instanceof EntityBlaze) { <add> collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); <add> } <add> if (entityIn instanceof EntityEnderman) { <add> collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); <add> } <add> if (entityIn instanceof EntityGhast) { <add> collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); <add> } <add> if (entityIn instanceof EntityVex) { <add> collidingBoxes.add(new AxisAlignedBB(pos).expand(0, 255, 0)); <add> } <add> } <add> <add> <ide> @Override <ide> public Item getItemDropped(IBlockState state, Random rand, int fortune) { <ide> return ModItems.salt;
JavaScript
unlicense
f02edda2943c67725937997dd7e26b740b29f542
0
fvdm/nodejs-dnsimple,fvdm/nodejs-dnsimple
/* Name: DNSimple module for Node.js Author: Franklin van de Meent (https://frankl.in) Source: https://github.com/fvdm/nodejs-dnsimple Feedback: https://github.com/fvdm/nodejs-dnsimple/issues License: Unlicense (public domain) see UNLICENSE file Service name: DNSimple Service URL: https://dnsimple.com Service API: http://developer.dnsimple.com */ var https = require('https') var app = {} // ! - Defaults app.api = { hostname: 'api.dnsimple.com', email: null, token: null, domainToken: null, twoFactorOTP: null, // one time password (ie. Authy) twoFactorToken: null, // OTP exchange token password: null, timeout: 30000 } // ! DNS app.dns = { // ! dns.list list: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/records', function( error, records, meta ) { if( error ) { return callback( error, null, meta )} records.map( function( cur, i, arr ) { arr[i] = cur.record }) callback( null, records, meta ) }) }, // ! dns.show show: function( domainname, recordID, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/records/'+ recordID, function( error, record, meta ) { if( error ) { return callback( error, null, meta )} callback( null, record.record, meta ) }) }, // ! dns.add // REQUIRED: name, record_type, content // OPTIONAL: ttl, prio add: function( domainname, record, callback ) { var post = { record: record } app.talk( 'POST', 'domains/'+ domainname +'/records', post, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.record, meta ) }) }, // ! dns.update update: function( domainname, recordID, record, callback ) { var post = { record: record } app.talk( 'PUT', 'domains/'+ domainname +'/records/'+ recordID, post, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.record, meta ) }) }, // ! dns.delete delete: function( domainname, recordID, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/records/'+ recordID, function( err, data, meta ) { callback( err, meta.statusCode === 200, meta ) }) } } // ! DOMAINS app.domains = { // ! domains.list // Simple returns only array with domainnames list: function( simple, callback ) { if( !callback && typeof simple === 'function' ) { var callback = simple var simple = false } app.talk( 'GET', 'domains', function( error, domains, meta ) { if( error ) { return callback( error, null, meta )} domains.map( function( cur, i, arr ) { arr[i] = cur.domain }) if( simple ) { domains.map( function( cur, i, arr ) { arr[i] = cur.name }) } callback( null, domains, meta ) }) }, // ! domains.findByRegex findByRegex: function( regex, callback ) { var result = [] app.domains.list( false, function( error, domains, meta ) { if( error ) { return callback( error, null, meta )} var regexp = new RegExp( regex ) for( var i = 0; i < domains.length; i++ ) { if( domains[i].name.match( regexp ) ) { result.push( domains[i] ) } } callback( null, result, meta ) }) }, // ! domains.show show: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname, function( error, domain, meta ) { if( error ) { return callback( error, null, meta )} callback( null, domain.domain, meta ) }) }, // ! domains.add add: function( domainname, callback ) { var dom = { domain: { name: domainname } } app.talk( 'POST', 'domains', dom, function( error, domain, meta ) { if( error ) { return callback( error, null, meta )} callback( null, domain.domain, meta ) }) }, // ! domains.delete delete: function( domainname, callback ) { app.talk( 'DELETE', 'domains/'+ domainname, function( err, data, meta ) { callback( err, meta.statusCode === 200, meta ) }) }, // ! domains.resetToken resetToken: function( domainname, callback ) { app.talk( 'POST', 'domains/'+ domainname +'/token', function( err, data, meta ) { callback( err, data.domain || null, meta ) }) }, // ! domains.push push: function( domainname, email, regId, callback ) { var data = { push: { new_user_email: email, contact_id: regId }} app.talk( 'POST', 'domains/'+ domainname +'/push', data, callback ) }, // ! domains.vanitynameservers vanitynameservers: function( domainname, enable, callback ) { if( enable ) { app.talk( 'POST', 'domains/'+ domainname +'/vanity_name_servers', {auto_renewal:{}}, callback ) } else { app.talk( 'DELETE', 'domains/'+ domainname +'/vanity_name_servers', callback ) } }, // ! DOMAINS.MEMBERSHIPS memberships: { // ! domains.memberships.list list: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/memberships', function( error, memberships, meta ) { if( error ) { return callback( error, null, meta )} memberships.map( function( cur, i, arr ) { arr[i] = cur.membership }) callback( null, memberships, meta ) }) }, // ! domains.memberships.add add: function( domainname, email, callback ) { var data = {membership: {email: email}} app.talk( 'POST', 'domains/'+ domainname +'/memberships', data, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.membership || false callback( null, data, meta ) }) }, // ! domains.memberships.delete delete: function( domainname, member, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/memberships/'+ member, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 204 ? true : false callback( null, data, meta ) }) } }, // ! DOMAINS REGISTRATION // ! domains.check // Check availability check: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/check', {}, callback ) }, // ! domains.register // Register domainname - auto-payment! register: function( domainname, registrantID, extendedAttribute, callback ) { var vars = { domain: { name: domainname, registrant_id: registrantID } } // fix 3 & 4 params if( !callback && typeof extendedAttribute == 'function' ) { var callback = extendedAttribute } else if( typeof extendedAttribute == 'object' ) { vars.domain.extended_attribute = extendedAttribute } // send app.talk( 'POST', 'domain_registrations', vars, function( err, data, meta ) { if( err ) { return callback( err, null, data )} data = data.domain || false callback( null, data, meta ) }) }, // ! domains.transfer // Transfer domainname - auto-payment! transfer: function( domainname, registrantID, authinfo, callback ) { var vars = { domain: { name: domainname, registrant_id: registrantID } } // fix 3 & 4 params if( !callback && typeof authinfo == 'function' ) { var callback = authinfo } else if( typeof authinfo == 'string' ) { vars.transfer_order = { authinfo: authinfo } } // send app.talk( 'POST', 'domain_transfers', vars, callback ) }, // ! domains.transferAttribute // Transfer domainname with Extended Attributes - auto-payment! transferAttribute: function( domainname, registrantID, attr, authinfo, callback ) { var vars = { domain: { name: domainname, registrant_id: registrantID }, extended_attribute: attr } // fix 3 & 4 params if( !callback && typeof authinfo == 'function' ) { var callback = authinfo } else if( typeof authinfo == 'string' ) { vars.transfer_order = { authinfo: authinfo } } // send app.talk( 'POST', 'domain_transfers', vars, callback ) }, // ! domains.renew // Renew domainname registration - auto-payment! renew: function( domainname, whoisPrivacy, callback ) { var vars = { domain: { name: domainname } } // fix 2 & 3 params if( !callback && typeof whoisPrivacy == 'function' ) { var callback = whoisPrivacy } else { // string matching if( whoisPrivacy ) { vars.domain.renew_whois_privacy = 'true' } else { vars.domain.renew_whois_privacy = 'false' } } // send app.talk( 'POST', 'domain_renewals', vars, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.domain || false callback( null, data, meta ) }) }, // ! domains.autorenew // Set auto-renewal for domain autorenew: function( domainname, enable, callback ) { var method = enable ? 'POST' : 'DELETE' app.talk( method, 'domains/'+ domainname +'/auto_renewal', function( err, data, meta ) { data = data.domain || null callback( err, data, meta ) }) }, // ! domains.transferout // Prepare domain for transferring out transferout: function( domainname, callback ) { app.talk( 'POST', 'domains/'+ domainname +'/transfer_outs', callback ) }, // ! domains.nameservers // Set nameservers at registry nameservers: function( domainname, nameservers, callback ) { var ns = { name_servers: nameservers } app.talk( 'POST', 'domains/'+ domainname +'/name_servers', ns, callback ) }, // ! domains.whoisPrivacy whoisPrivacy: function( domainname, enable, callback ) { var method = enable ? 'POST' : 'DELETE' app.talk( method, 'domains/'+ domainname +'/whois_privacy', function( err, data, meta ) { data = data.whois_privacy || data if( method === 'DELETE' ) { data = meta.statusCode === 200 || meta.statusCode === 204 ? true : false } callback( err, data, meta ) }) }, // ! domains.nameserver_register nameserver_register: function( domainname, name, ip, callback ) { var vars = { name: name, ip: ip } app.talk( 'POST', 'domains/'+ domainname +'/registry_name_servers', vars, callback ) }, // ! domains.nameserver_deregister nameserver_deregister: function( domainname, name, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/registry_name_servers/'+ name, vars, callback ) }, // ! domains.zone // See http://developer.dnsimple.com/domains/zones/#zone zone: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/zone', function(err, data, meta) { if (err) { return callback(err, null, meta) } callback(null, data.zone, meta) }) }, // ! domains.importZone // See http://developer.dnsimple.com/domains/zones/#import importZone: function( domainname, zone, callback ) { var zone = { zone_import: { zone_data: zone }} app.talk( 'POST', 'domains/'+ domainname +'/zone_imports', zone, function(err, data, meta) { if (err) { return callback(err, null, meta) } data = data.zone_import || false callback(null, data, meta) }) }, // ! DOMAINS SERVICES // Services for domain services: { // ! domains.services.list // already applied list: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/applied_services', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} result.map( function( cur, i, arr ) { arr[i] = cur.service }) callback( null, result, meta ) }) }, // ! domains.services.available // available available: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/available_services', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} result.map( function( cur, i, arr ) { arr[i] = cur.service }) callback( null, result, meta ) }) }, // ! domains.services.add // apply one add: function( domainname, serviceID, settings, callback ) { if( typeof settings === 'function' ) { var callback = settings var settings = null } var service = { service: { id: serviceID } } if( settings ) { service.settings = settings } app.talk( 'POST', 'domains/'+ domainname +'/applied_services', service, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data[0] && data[0].service ? data[0].service : false callback( null, data, meta ) }) }, // ! domains.services.delete // delete one delete: function( domainname, serviceID, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/applied_services/'+ serviceID, callback ) } }, // ! domains.template // apply template -- alias for templates.apply template: function( domainname, templateID, callback ) { app.templates.apply( domainname, templateID, callback ) }, // ! EMAIL FORWARDS email_forwards: { } } // ! SERVICES app.services = { // ! services.list // List all supported services list: function( callback ) { app.talk( 'GET', 'services', function( error, list, meta ) { if( error ) { return callback( error, null, meta )} list.map( function( cur, i, arr ) { arr[i] = cur.service }) callback( null, list, meta ) }) }, // ! services.show // Get one service' details show: function( serviceID, callback ) { app.talk( 'GET', 'services/'+ serviceID, function( error, service, meta ) { if( error ) { return callback( error, null, meta )} callback( null, service.service, meta ) }) }, // ! services.config config: function( serviceName, callback ) { var complete = false function doCallback( err, res, meta ) { if( ! complete ) { complete = true callback( err, res || null, meta ) } } https.get( 'https://raw.githubusercontent.com/aetrion/dnsimple-services/master/services/'+ serviceName +'/config.json', function( response ) { var data = [] var size = 0 var error = null response.on( 'data', function(ch) { data.push(ch) size += ch.length }) response.on( 'end', function() { data = new Buffer.concat( data, size ).toString('utf8').trim() try { data = JSON.parse( data ) } catch(e) { error = new Error('not json') } if( response.statusCode >= 300 ) { error = new Error('http error') error.code = response.statusCode error.headers = response.headers error.body = data } doCallback( error, data, {service: 'github'} ) }) }) } } // ! TEMPLATES app.templates = { // ! templates.list // List all of the custom templates in the account list: function( callback ) { app.talk( 'GET', 'templates', function( error, list, meta ) { if( error ) { return callback( error, null, meta )} list.map( function( cur, i, arr ) { arr[i] = cur.dns_template }) callback( null, list, meta ) }) }, // ! templates.show // Get a specific template show: function( templateID, callback ) { app.talk( 'GET', 'templates/'+ templateID, function( error, template, meta ) { if( error ) { return callback( error, null, meta )} callback( null, template.dns_template, meta ) }) }, // ! templates.add // Create a custom template // REQUIRED: name, shortname // OPTIONAL: description add: function( template, callback ) { var set = { dns_template: template } app.talk( 'POST', 'templates', set, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.dns_template, meta ) }) }, // ! templates.delete // Delete the given template delete: function( templateID, callback ) { app.talk( 'DELETE', 'templates/'+ templateID, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 200 ? true : false callback( null, data, meta ) }) }, // ! templates.apply // Apply a template to a domain apply: function( domainname, templateID, callback ) { app.talk( 'POST', 'domains/'+ domainname +'/templates/'+ templateID +'/apply', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} var result = result.domain ? result.domain : result callback( null, result, meta ) }) }, // records records: { // ! templates.records.list // list records in template list: function( templateID, callback ) { app.talk( 'GET', 'templates/'+ templateID +'/records', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} result.map( function( cur, i, arr ) { arr[i] = cur.dns_template_record }) callback( null, result, meta ) }) }, // ! templates.records.show // Get one record for template show: function( templateID, recordID, callback ) { app.talk( 'GET', 'templates/'+ templateID +'/records/'+ recordID, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.dns_template_record, meta ) }) }, // ! templates.records.add // Add record to template // REQUIRED: name, record_type, content // OPTIONAL: ttl, prio add: function( templateID, record, callback ) { var rec = { dns_template_record: record } app.talk( 'POST', 'templates/'+ templateID +'/records', rec, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.dns_template_record, meta ) }) }, // ! templates.records.delete // Delete record from template delete: function( templateID, recordID, callback ) { app.talk( 'DELETE', 'templates/'+ templateID +'/records/'+ recordID, {}, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 200 ? true : false callback( null, data, meta ) }) } } } // ! CONTACTS app.contacts = { // ! contacts.list list: function( callback ) { app.talk( 'GET', 'contacts', function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data.map( function( cur, i, arr ) { arr[i] = cur.contact }) callback( null, data, meta ) }) }, // ! contacts.show show: function( contactID, callback ) { app.talk( 'GET', 'contacts/'+ contactID, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} callback( null, data.contact, meta ) }) }, // ! contacts.add // http://developer.dnsimple.com/contacts/#create-a-contact add: function( contact, callback ) { app.talk( 'POST', 'contacts', {contact: contact}, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.contact || false callback( null, data, meta ) }) }, // ! contacts.update // http://developer.dnsimple.com/contacts/#update-a-contact update: function( contactID, contact, callback ) { app.talk( 'PUT', 'contacts/'+ contactID, {contact: contact}, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.contact || false callback( null, data, meta ) }) }, // ! contacts.delete delete: function( contactID, callback ) { app.talk( 'DELETE', 'contacts/'+ contactID, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 204 ? true : false callback( null, data, meta ) }) } } // ! ACCOUNT // ! .subscription app.subscription = function( vars, callback ) { if( ! callback ) { app.talk( 'GET', 'subscription', function( err, data, meta ) { if( err ) { vars( err, null, meta ); return } vars( null, data.subscription, meta ) }) } else { var data = {subscription: vars} app.talk( 'PUT', 'subscription', data, function( err, res, meta ) { if( err ) { return callback( err, null, meta )} callback( null, res.subscription, meta ) }) } } // ! OTHER // ! .prices app.prices = function( callback ) { app.talk( 'GET', 'prices', function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data.map( function( cur, i, arr ) { arr[i] = cur.price }) callback( null, data, meta ) }) } // ! .user app.user = function( user, callback ) { var user = {user: user} app.talk( 'POST', 'users', user, function( err, data, meta ) { if( err ) { return callback( err, null, meta ) } var data = data.user || false callback( null, data, meta ) }) } // ! .extendedAttributes app.extendedAttributes = function( tld, callback ) { app.talk( 'GET', 'extended_attributes/'+ tld, callback ) } // MODULE // ! - Communicate app.talk = function( method, path, fields, callback ) { if( !callback && typeof fields === 'function' ) { var callback = fields var fields = {} } // prevent multiple callbacks var complete = false function doCallback( err, res, meta ) { if( !complete ) { complete = true callback( err || null, res || null, meta ) } } // credentials set? if( ! (app.api.email && app.api.token) && ! (app.api.email && app.api.password) && ! app.api.domainToken && ! app.api.twoFactorToken ) { doCallback( new Error('credentials missing') ) return } // prepare var querystr = JSON.stringify(fields) var headers = { 'Accept': 'application/json', 'User-Agent': 'Nodejs-DNSimple' } // token in headers if( app.api.token ) { headers['X-DNSimple-Token'] = app.api.email +':'+ app.api.token } if( app.api.domainToken ) { headers['X-DNSimple-Domain-Token'] = app.api.domainToken } // build request if( method.match( /(POST|PUT|DELETE)/ ) ) { headers['Content-Type'] = 'application/json' headers['Content-Length'] = querystr.length } var options = { host: app.api.hostname, port: 443, path: '/v1/'+ path, method: method, headers: headers } // password authentication if( ! app.api.twoFactorToken && ! app.api.token && ! app.api.domainToken && app.api.password && app.api.email ) { options.auth = app.api.email +':'+ app.api.password // two-factor authentication (2FA) if( app.api.twoFactorOTP ) { headers['X-DNSimple-2FA-Strict'] = 1 headers['X-DNSimple-OTP'] = app.api.twoFactorOTP } } if( app.api.twoFactorToken ) { options.auth = app.api.twoFactorToken +':x-2fa-basic' headers['X-DNSimple-2FA-Strict'] = 1 } // start request var request = https.request( options ) // response request.on( 'response', function( response ) { var meta = {statusCode: null} var data = [] var size = 0 response.on( 'data', function( chunk ) { data.push( chunk ) size += chunk.length }) response.on( 'close', function() { doCallback( new Error('connection dropped') ) }) // request finished response.on( 'end', function() { data = new Buffer.concat( data, size ).toString('utf8').trim() var failed = null meta.statusCode = response.statusCode meta.request_id = response.headers['x-request-id'] meta.runtime = response.headers['x-runtime'] if( typeof response.headers['x-dnsimple-otp-token'] === 'string' ) { meta.twoFactorToken = response.headers['x-dnsimple-otp-token'] } if( response.statusCode !== 204 ) { try { data = JSON.parse( data ); } catch(e) { doCallback(new Error('not json'), data); } } // overrides var noError = false // status ok, no data if( data == '' && meta.statusCode < 300 ) { noError = true } // domain check 404 = free if( path.match(/^domains\/.+\/check$/) && meta.statusCode === 404 ) { noError = true } // check HTTP status code if( noError || (!failed && response.statusCode < 300) ) { doCallback( null, data, meta ) } else { if( response.statusCode == 401 && response.headers['x-dnsimple-otp'] == 'required' ) { var error = new Error('twoFactorOTP required') } else { var error = failed || new Error('API error') } error.code = response.statusCode error.error = data.message || data.error || (data.errors && data instanceof Object && Object.keys(data.errors)[0] ? data.errors[Object.keys(data.errors)[0]] : null) || null error.data = data doCallback( error, null, meta ) } }) }) // timeout request.on( 'socket', function( socket ) { if( app.api.timeout ) { socket.setTimeout( app.api.timeout ) socket.on( 'timeout', function() { doCallback( new Error('request timeout') ) request.abort() }) } }) // error request.on( 'error', function( error ) { if( error.code === 'ECONNRESET' ) { var er = new Error('request timeout') } else { var er = new Error('request failed') } er.error = error doCallback( er ) }) // run it if( method.match( /(POST|PUT|DELETE)/ ) ) { request.end( querystr ) } else { request.end() } } // wrap it up module.exports = function( setup ) { for( var i in setup ) { app.api[ i ] = setup[ i ] } return app }
dnsimple.js
/* Name: DNSimple module for Node.js Author: Franklin van de Meent (https://frankl.in) Source: https://github.com/fvdm/nodejs-dnsimple Feedback: https://github.com/fvdm/nodejs-dnsimple/issues License: Unlicense (public domain) see UNLICENSE file Service name: DNSimple Service URL: https://dnsimple.com Service API: http://developer.dnsimple.com */ var https = require('https') var app = {} // ! - Defaults app.api = { hostname: 'api.dnsimple.com', email: null, token: null, domainToken: null, twoFactorOTP: null, // one time password (ie. Authy) twoFactorToken: null, // OTP exchange token password: null, timeout: 30000 } // ! DNS app.dns = { // ! dns.list list: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/records', function( error, records, meta ) { if( error ) { return callback( error, null, meta )} records.map( function( cur, i, arr ) { arr[i] = cur.record }) callback( null, records, meta ) }) }, // ! dns.show show: function( domainname, recordID, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/records/'+ recordID, function( error, record, meta ) { if( error ) { return callback( error, null, meta )} callback( null, record.record, meta ) }) }, // ! dns.add // REQUIRED: name, record_type, content // OPTIONAL: ttl, prio add: function( domainname, record, callback ) { var post = { record: record } app.talk( 'POST', 'domains/'+ domainname +'/records', post, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.record, meta ) }) }, // ! dns.update update: function( domainname, recordID, record, callback ) { var post = { record: record } app.talk( 'PUT', 'domains/'+ domainname +'/records/'+ recordID, post, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.record, meta ) }) }, // ! dns.delete delete: function( domainname, recordID, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/records/'+ recordID, function( err, data, meta ) { callback( err, meta.statusCode === 200, meta ) }) } } // ! DOMAINS app.domains = { // ! domains.list // Simple returns only array with domainnames list: function( simple, callback ) { if( !callback && typeof simple === 'function' ) { var callback = simple var simple = false } app.talk( 'GET', 'domains', function( error, domains, meta ) { if( error ) { return callback( error, null, meta )} domains.map( function( cur, i, arr ) { arr[i] = cur.domain }) if( simple ) { domains.map( function( cur, i, arr ) { arr[i] = cur.name }) } callback( null, domains, meta ) }) }, // ! domains.findByRegex findByRegex: function( regex, callback ) { var result = [] app.domains.list( false, function( error, domains, meta ) { if( error ) { return callback( error, null, meta )} var regexp = new RegExp( regex ) for( var i = 0; i < domains.length; i++ ) { if( domains[i].name.match( regexp ) ) { result.push( domains[i] ) } } callback( null, result, meta ) }) }, // ! domains.show show: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname, function( error, domain, meta ) { if( error ) { return callback( error, null, meta )} callback( null, domain.domain, meta ) }) }, // ! domains.add add: function( domainname, callback ) { var dom = { domain: { name: domainname } } app.talk( 'POST', 'domains', dom, function( error, domain, meta ) { if( error ) { return callback( error, null, meta )} callback( null, domain.domain, meta ) }) }, // ! domains.delete delete: function( domainname, callback ) { app.talk( 'DELETE', 'domains/'+ domainname, function( err, data, meta ) { callback( err, meta.statusCode === 200, meta ) }) }, // ! domains.resetToken resetToken: function( domainname, callback ) { app.talk( 'POST', 'domains/'+ domainname +'/token', function( err, data, meta ) { callback( err, data.domain || null, meta ) }) }, // ! domains.push push: function( domainname, email, regId, callback ) { var data = { push: { new_user_email: email, contact_id: regId }} app.talk( 'POST', 'domains/'+ domainname +'/push', data, callback ) }, // ! domains.vanitynameservers vanitynameservers: function( domainname, enable, callback ) { if( enable ) { app.talk( 'POST', 'domains/'+ domainname +'/vanity_name_servers', {auto_renewal:{}}, callback ) } else { app.talk( 'DELETE', 'domains/'+ domainname +'/vanity_name_servers', callback ) } }, // ! DOMAINS.MEMBERSHIPS memberships: { // ! domains.memberships.list list: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/memberships', function( error, memberships, meta ) { if( error ) { return callback( error, null, meta )} memberships.map( function( cur, i, arr ) { arr[i] = cur.membership }) callback( null, memberships, meta ) }) }, // ! domains.memberships.add add: function( domainname, email, callback ) { var data = {membership: {email: email}} app.talk( 'POST', 'domains/'+ domainname +'/memberships', data, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.membership || false callback( null, data, meta ) }) }, // ! domains.memberships.delete delete: function( domainname, member, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/memberships/'+ member, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 204 ? true : false callback( null, data, meta ) }) } }, // ! DOMAINS REGISTRATION // ! domains.check // Check availability check: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/check', {}, callback ) }, // ! domains.register // Register domainname - auto-payment! register: function( domainname, registrantID, extendedAttribute, callback ) { var vars = { domain: { name: domainname, registrant_id: registrantID } } // fix 3 & 4 params if( !callback && typeof extendedAttribute == 'function' ) { var callback = extendedAttribute } else if( typeof extendedAttribute == 'object' ) { vars.domain.extended_attribute = extendedAttribute } // send app.talk( 'POST', 'domain_registrations', vars, function( err, data, meta ) { if( err ) { return callback( err, null, data )} data = data.domain || false callback( null, data, meta ) }) }, // ! domains.transfer // Transfer domainname - auto-payment! transfer: function( domainname, registrantID, authinfo, callback ) { var vars = { domain: { name: domainname, registrant_id: registrantID } } // fix 3 & 4 params if( !callback && typeof authinfo == 'function' ) { var callback = authinfo } else if( typeof authinfo == 'string' ) { vars.transfer_order = { authinfo: authinfo } } // send app.talk( 'POST', 'domain_transfers', vars, callback ) }, // ! domains.transferAttribute // Transfer domainname with Extended Attributes - auto-payment! transferAttribute: function( domainname, registrantID, attr, authinfo, callback ) { var vars = { domain: { name: domainname, registrant_id: registrantID }, extended_attribute: attr } // fix 3 & 4 params if( !callback && typeof authinfo == 'function' ) { var callback = authinfo } else if( typeof authinfo == 'string' ) { vars.transfer_order = { authinfo: authinfo } } // send app.talk( 'POST', 'domain_transfers', vars, callback ) }, // ! domains.renew // Renew domainname registration - auto-payment! renew: function( domainname, whoisPrivacy, callback ) { var vars = { domain: { name: domainname } } // fix 2 & 3 params if( !callback && typeof whoisPrivacy == 'function' ) { var callback = whoisPrivacy } else { // string matching if( whoisPrivacy ) { vars.domain.renew_whois_privacy = 'true' } else { vars.domain.renew_whois_privacy = 'false' } } // send app.talk( 'POST', 'domain_renewals', vars, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.domain || false callback( null, data, meta ) }) }, // ! domains.autorenew // Set auto-renewal for domain autorenew: function( domainname, enable, callback ) { var method = enable ? 'POST' : 'DELETE' app.talk( method, 'domains/'+ domainname +'/auto_renewal', function( err, data, meta ) { data = data.domain || null callback( err, data, meta ) }) }, // ! domains.transferout // Prepare domain for transferring out transferout: function( domainname, callback ) { app.talk( 'POST', 'domains/'+ domainname +'/transfer_outs', callback ) }, // ! domains.nameservers // Set nameservers at registry nameservers: function( domainname, nameservers, callback ) { var ns = { name_servers: nameservers } app.talk( 'POST', 'domains/'+ domainname +'/name_servers', ns, callback ) }, // ! domains.whoisPrivacy whoisPrivacy: function( domainname, enable, callback ) { var method = enable ? 'POST' : 'DELETE' app.talk( method, 'domains/'+ domainname +'/whois_privacy', function( err, data, meta ) { data = data.whois_privacy || data if( method === 'DELETE' ) { data = meta.statusCode === 200 || meta.statusCode === 204 ? true : false } callback( err, data, meta ) }) }, // ! domains.nameserver_register nameserver_register: function( domainname, name, ip, callback ) { var vars = { name: name, ip: ip } app.talk( 'POST', 'domains/'+ domainname +'/registry_name_servers', vars, callback ) }, // ! domains.nameserver_deregister nameserver_deregister: function( domainname, name, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/registry_name_servers/'+ name, vars, callback ) }, // ! domains.zone // See http://developer.dnsimple.com/domains/zones/#zone zone: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/zone', function(err, data, meta) { if (err) { return callback(err, null, meta) } callback(null, data.zone, meta) }) }, // ! domains.importZone // See http://developer.dnsimple.com/domains/zones/#import importZone: function( domainname, zone, callback ) { var zone = { zone_import: { zone_data: zone }} app.talk( 'POST', 'domains/'+ domainname +'/zone_imports', zone, function(err, data, meta) { if (err) { return callback(err, null, meta) } data = data.zone_import || false callback(null, data, meta) }) }, // ! DOMAINS SERVICES // Services for domain services: { // ! domains.services.list // already applied list: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/applied_services', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} result.map( function( cur, i, arr ) { arr[i] = cur.service }) callback( null, result, meta ) }) }, // ! domains.services.available // available available: function( domainname, callback ) { app.talk( 'GET', 'domains/'+ domainname +'/available_services', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} result.map( function( cur, i, arr ) { arr[i] = cur.service }) callback( null, result, meta ) }) }, // ! domains.services.add // apply one add: function( domainname, serviceID, settings, callback ) { if( typeof settings === 'function' ) { var callback = settings var settings = null } var service = { service: { id: serviceID } } if( settings ) { service.settings = settings } app.talk( 'POST', 'domains/'+ domainname +'/applied_services', service, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data[0] && data[0].service ? data[0].service : false callback( null, data, meta ) }) }, // ! domains.services.delete // delete one delete: function( domainname, serviceID, callback ) { app.talk( 'DELETE', 'domains/'+ domainname +'/applied_services/'+ serviceID, callback ) } }, // ! domains.template // apply template -- alias for templates.apply template: function( domainname, templateID, callback ) { app.templates.apply( domainname, templateID, callback ) } } // ! SERVICES app.services = { // ! services.list // List all supported services list: function( callback ) { app.talk( 'GET', 'services', function( error, list, meta ) { if( error ) { return callback( error, null, meta )} list.map( function( cur, i, arr ) { arr[i] = cur.service }) callback( null, list, meta ) }) }, // ! services.show // Get one service' details show: function( serviceID, callback ) { app.talk( 'GET', 'services/'+ serviceID, function( error, service, meta ) { if( error ) { return callback( error, null, meta )} callback( null, service.service, meta ) }) }, // ! services.config config: function( serviceName, callback ) { var complete = false function doCallback( err, res, meta ) { if( ! complete ) { complete = true callback( err, res || null, meta ) } } https.get( 'https://raw.githubusercontent.com/aetrion/dnsimple-services/master/services/'+ serviceName +'/config.json', function( response ) { var data = [] var size = 0 var error = null response.on( 'data', function(ch) { data.push(ch) size += ch.length }) response.on( 'end', function() { data = new Buffer.concat( data, size ).toString('utf8').trim() try { data = JSON.parse( data ) } catch(e) { error = new Error('not json') } if( response.statusCode >= 300 ) { error = new Error('http error') error.code = response.statusCode error.headers = response.headers error.body = data } doCallback( error, data, {service: 'github'} ) }) }) } } // ! TEMPLATES app.templates = { // ! templates.list // List all of the custom templates in the account list: function( callback ) { app.talk( 'GET', 'templates', function( error, list, meta ) { if( error ) { return callback( error, null, meta )} list.map( function( cur, i, arr ) { arr[i] = cur.dns_template }) callback( null, list, meta ) }) }, // ! templates.show // Get a specific template show: function( templateID, callback ) { app.talk( 'GET', 'templates/'+ templateID, function( error, template, meta ) { if( error ) { return callback( error, null, meta )} callback( null, template.dns_template, meta ) }) }, // ! templates.add // Create a custom template // REQUIRED: name, shortname // OPTIONAL: description add: function( template, callback ) { var set = { dns_template: template } app.talk( 'POST', 'templates', set, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.dns_template, meta ) }) }, // ! templates.delete // Delete the given template delete: function( templateID, callback ) { app.talk( 'DELETE', 'templates/'+ templateID, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 200 ? true : false callback( null, data, meta ) }) }, // ! templates.apply // Apply a template to a domain apply: function( domainname, templateID, callback ) { app.talk( 'POST', 'domains/'+ domainname +'/templates/'+ templateID +'/apply', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} var result = result.domain ? result.domain : result callback( null, result, meta ) }) }, // records records: { // ! templates.records.list // list records in template list: function( templateID, callback ) { app.talk( 'GET', 'templates/'+ templateID +'/records', function( error, result, meta ) { if( error ) { return callback( error, null, meta )} result.map( function( cur, i, arr ) { arr[i] = cur.dns_template_record }) callback( null, result, meta ) }) }, // ! templates.records.show // Get one record for template show: function( templateID, recordID, callback ) { app.talk( 'GET', 'templates/'+ templateID +'/records/'+ recordID, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.dns_template_record, meta ) }) }, // ! templates.records.add // Add record to template // REQUIRED: name, record_type, content // OPTIONAL: ttl, prio add: function( templateID, record, callback ) { var rec = { dns_template_record: record } app.talk( 'POST', 'templates/'+ templateID +'/records', rec, function( error, result, meta ) { if( error ) { return callback( error, null, meta )} callback( null, result.dns_template_record, meta ) }) }, // ! templates.records.delete // Delete record from template delete: function( templateID, recordID, callback ) { app.talk( 'DELETE', 'templates/'+ templateID +'/records/'+ recordID, {}, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 200 ? true : false callback( null, data, meta ) }) } } } // ! CONTACTS app.contacts = { // ! contacts.list list: function( callback ) { app.talk( 'GET', 'contacts', function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data.map( function( cur, i, arr ) { arr[i] = cur.contact }) callback( null, data, meta ) }) }, // ! contacts.show show: function( contactID, callback ) { app.talk( 'GET', 'contacts/'+ contactID, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} callback( null, data.contact, meta ) }) }, // ! contacts.add // http://developer.dnsimple.com/contacts/#create-a-contact add: function( contact, callback ) { app.talk( 'POST', 'contacts', {contact: contact}, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.contact || false callback( null, data, meta ) }) }, // ! contacts.update // http://developer.dnsimple.com/contacts/#update-a-contact update: function( contactID, contact, callback ) { app.talk( 'PUT', 'contacts/'+ contactID, {contact: contact}, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = data.contact || false callback( null, data, meta ) }) }, // ! contacts.delete delete: function( contactID, callback ) { app.talk( 'DELETE', 'contacts/'+ contactID, function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data = meta.statusCode === 204 ? true : false callback( null, data, meta ) }) } } // ! ACCOUNT // ! .subscription app.subscription = function( vars, callback ) { if( ! callback ) { app.talk( 'GET', 'subscription', function( err, data, meta ) { if( err ) { vars( err, null, meta ); return } vars( null, data.subscription, meta ) }) } else { var data = {subscription: vars} app.talk( 'PUT', 'subscription', data, function( err, res, meta ) { if( err ) { return callback( err, null, meta )} callback( null, res.subscription, meta ) }) } } // ! OTHER // ! .prices app.prices = function( callback ) { app.talk( 'GET', 'prices', function( err, data, meta ) { if( err ) { return callback( err, null, meta )} data.map( function( cur, i, arr ) { arr[i] = cur.price }) callback( null, data, meta ) }) } // ! .user app.user = function( user, callback ) { var user = {user: user} app.talk( 'POST', 'users', user, function( err, data, meta ) { if( err ) { return callback( err, null, meta ) } var data = data.user || false callback( null, data, meta ) }) } // ! .extendedAttributes app.extendedAttributes = function( tld, callback ) { app.talk( 'GET', 'extended_attributes/'+ tld, callback ) } // MODULE // ! - Communicate app.talk = function( method, path, fields, callback ) { if( !callback && typeof fields === 'function' ) { var callback = fields var fields = {} } // prevent multiple callbacks var complete = false function doCallback( err, res, meta ) { if( !complete ) { complete = true callback( err || null, res || null, meta ) } } // credentials set? if( ! (app.api.email && app.api.token) && ! (app.api.email && app.api.password) && ! app.api.domainToken && ! app.api.twoFactorToken ) { doCallback( new Error('credentials missing') ) return } // prepare var querystr = JSON.stringify(fields) var headers = { 'Accept': 'application/json', 'User-Agent': 'Nodejs-DNSimple' } // token in headers if( app.api.token ) { headers['X-DNSimple-Token'] = app.api.email +':'+ app.api.token } if( app.api.domainToken ) { headers['X-DNSimple-Domain-Token'] = app.api.domainToken } // build request if( method.match( /(POST|PUT|DELETE)/ ) ) { headers['Content-Type'] = 'application/json' headers['Content-Length'] = querystr.length } var options = { host: app.api.hostname, port: 443, path: '/v1/'+ path, method: method, headers: headers } // password authentication if( ! app.api.twoFactorToken && ! app.api.token && ! app.api.domainToken && app.api.password && app.api.email ) { options.auth = app.api.email +':'+ app.api.password // two-factor authentication (2FA) if( app.api.twoFactorOTP ) { headers['X-DNSimple-2FA-Strict'] = 1 headers['X-DNSimple-OTP'] = app.api.twoFactorOTP } } if( app.api.twoFactorToken ) { options.auth = app.api.twoFactorToken +':x-2fa-basic' headers['X-DNSimple-2FA-Strict'] = 1 } // start request var request = https.request( options ) // response request.on( 'response', function( response ) { var meta = {statusCode: null} var data = [] var size = 0 response.on( 'data', function( chunk ) { data.push( chunk ) size += chunk.length }) response.on( 'close', function() { doCallback( new Error('connection dropped') ) }) // request finished response.on( 'end', function() { data = new Buffer.concat( data, size ).toString('utf8').trim() var failed = null meta.statusCode = response.statusCode meta.request_id = response.headers['x-request-id'] meta.runtime = response.headers['x-runtime'] if( typeof response.headers['x-dnsimple-otp-token'] === 'string' ) { meta.twoFactorToken = response.headers['x-dnsimple-otp-token'] } if( response.statusCode !== 204 ) { try { data = JSON.parse( data ); } catch(e) { doCallback(new Error('not json'), data); } } // overrides var noError = false // status ok, no data if( data == '' && meta.statusCode < 300 ) { noError = true } // domain check 404 = free if( path.match(/^domains\/.+\/check$/) && meta.statusCode === 404 ) { noError = true } // check HTTP status code if( noError || (!failed && response.statusCode < 300) ) { doCallback( null, data, meta ) } else { if( response.statusCode == 401 && response.headers['x-dnsimple-otp'] == 'required' ) { var error = new Error('twoFactorOTP required') } else { var error = failed || new Error('API error') } error.code = response.statusCode error.error = data.message || data.error || (data.errors && data instanceof Object && Object.keys(data.errors)[0] ? data.errors[Object.keys(data.errors)[0]] : null) || null error.data = data doCallback( error, null, meta ) } }) }) // timeout request.on( 'socket', function( socket ) { if( app.api.timeout ) { socket.setTimeout( app.api.timeout ) socket.on( 'timeout', function() { doCallback( new Error('request timeout') ) request.abort() }) } }) // error request.on( 'error', function( error ) { if( error.code === 'ECONNRESET' ) { var er = new Error('request timeout') } else { var er = new Error('request failed') } er.error = error doCallback( er ) }) // run it if( method.match( /(POST|PUT|DELETE)/ ) ) { request.end( querystr ) } else { request.end() } } // wrap it up module.exports = function( setup ) { for( var i in setup ) { app.api[ i ] = setup[ i ] } return app }
Added section Email Forwards
dnsimple.js
Added section Email Forwards
<ide><path>nsimple.js <ide> // apply template -- alias for templates.apply <ide> template: function( domainname, templateID, callback ) { <ide> app.templates.apply( domainname, templateID, callback ) <add> }, <add> <add> // ! EMAIL FORWARDS <add> email_forwards: { <ide> } <ide> } <ide>
Java
apache-2.0
006b969392caa9897fa6313e759c652490d72ce2
0
peterdettman/bitcoinj,natzei/bitcoinj,peterdettman/bitcoinj,natzei/bitcoinj,bitcoinj/bitcoinj,yenliangl/bitcoinj,bitcoinj/bitcoinj,yenliangl/bitcoinj
/* * Copyright 2012 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.*; import com.google.common.util.concurrent.*; import org.bitcoinj.core.listeners.*; import org.bitcoinj.script.ScriptException; import org.bitcoinj.store.*; import org.bitcoinj.utils.*; import org.bitcoinj.wallet.Wallet; import org.slf4j.*; import javax.annotation.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; import static com.google.common.base.Preconditions.*; /** * <p>An AbstractBlockChain holds a series of {@link Block} objects, links them together, and knows how to verify that * the chain follows the rules of the {@link NetworkParameters} for this chain.</p> * * <p>It can be connected to a {@link Wallet}, and also {@link TransactionReceivedInBlockListener}s that can receive transactions and * notifications of re-organizations.</p> * * <p>An AbstractBlockChain implementation must be connected to a {@link BlockStore} implementation. The chain object * by itself doesn't store any data, that's delegated to the store. Which store you use is a decision best made by * reading the getting started guide, but briefly, fully validating block chains need fully validating stores. In * the lightweight SPV mode, a {@link SPVBlockStore} is the right choice.</p> * * <p>This class implements an abstract class which makes it simple to create a BlockChain that does/doesn't do full * verification. It verifies headers and is implements most of what is required to implement SPV mode, but * also provides callback hooks which can be used to do full verification.</p> * * <p>There are two subclasses of AbstractBlockChain that are useful: {@link BlockChain}, which is the simplest * class and implements <i>simplified payment verification</i>. This is a lightweight and efficient mode that does * not verify the contents of blocks, just their headers. A {@link FullPrunedBlockChain} paired with a * {@link H2FullPrunedBlockStore} implements full verification, which is equivalent to * Bitcoin Core. To learn more about the alternative security models, please consult the articles on the * website.</p> * * <b>Theory</b> * * <p>The 'chain' is actually a tree although in normal operation it operates mostly as a list of {@link Block}s. * When multiple new head blocks are found simultaneously, there are multiple stories of the economy competing to become * the one true consensus. This can happen naturally when two miners solve a block within a few seconds of each other, * or it can happen when the chain is under attack.</p> * * <p>A reference to the head block of the best known chain is stored. If you can reach the genesis block by repeatedly * walking through the prevBlock pointers, then we say this is a full chain. If you cannot reach the genesis block * we say it is an orphan chain. Orphan chains can occur when blocks are solved and received during the initial block * chain download, or if we connect to a peer that doesn't send us blocks in order.</p> * * <p>A reorganize occurs when the blocks that make up the best known chain change. Note that simply adding a * new block to the top of the best chain isn't a reorganize, but that a reorganize is always triggered by adding * a new block that connects to some other (non best head) block. By "best" we mean the chain representing the largest * amount of work done.</p> * * <p>Every so often the block chain passes a difficulty transition point. At that time, all the blocks in the last * 2016 blocks are examined and a new difficulty target is calculated from them.</p> */ public abstract class AbstractBlockChain { private static final Logger log = LoggerFactory.getLogger(AbstractBlockChain.class); protected final ReentrantLock lock = Threading.lock(AbstractBlockChain.class); /** Keeps a map of block hashes to StoredBlocks. */ private final BlockStore blockStore; /** * Tracks the top of the best known chain.<p> * * Following this one down to the genesis block produces the story of the economy from the creation of Bitcoin * until the present day. The chain head can change if a new set of blocks is received that results in a chain of * greater work than the one obtained by following this one down. In that case a reorganize is triggered, * potentially invalidating transactions in our wallet. */ protected StoredBlock chainHead; // TODO: Scrap this and use a proper read/write for all of the block chain objects. // The chainHead field is read/written synchronized with this object rather than BlockChain. However writing is // also guaranteed to happen whilst BlockChain is synchronized (see setChainHead). The goal of this is to let // clients quickly access the chain head even whilst the block chain is downloading and thus the BlockChain is // locked most of the time. private final Object chainHeadLock = new Object(); protected final NetworkParameters params; private final CopyOnWriteArrayList<ListenerRegistration<NewBestBlockListener>> newBestBlockListeners; private final CopyOnWriteArrayList<ListenerRegistration<ReorganizeListener>> reorganizeListeners; private final CopyOnWriteArrayList<ListenerRegistration<TransactionReceivedInBlockListener>> transactionReceivedListeners; // Holds a block header and, optionally, a list of tx hashes or block's transactions class OrphanBlock { final Block block; final List<Sha256Hash> filteredTxHashes; final Map<Sha256Hash, Transaction> filteredTxn; OrphanBlock(Block block, @Nullable List<Sha256Hash> filteredTxHashes, @Nullable Map<Sha256Hash, Transaction> filteredTxn) { final boolean filtered = filteredTxHashes != null && filteredTxn != null; Preconditions.checkArgument((block.getTransactions() == null && filtered) || (block.getTransactions() != null && !filtered)); this.block = block; this.filteredTxHashes = filteredTxHashes; this.filteredTxn = filteredTxn; } } // Holds blocks that we have received but can't plug into the chain yet, eg because they were created whilst we // were downloading the block chain. private final LinkedHashMap<Sha256Hash, OrphanBlock> orphanBlocks = new LinkedHashMap<>(); /** False positive estimation uses a double exponential moving average. */ public static final double FP_ESTIMATOR_ALPHA = 0.0001; /** False positive estimation uses a double exponential moving average. */ public static final double FP_ESTIMATOR_BETA = 0.01; private double falsePositiveRate; private double falsePositiveTrend; private double previousFalsePositiveRate; private final VersionTally versionTally; /** See {@link #AbstractBlockChain(Context, List, BlockStore)} */ public AbstractBlockChain(NetworkParameters params, List<? extends Wallet> transactionReceivedListeners, BlockStore blockStore) throws BlockStoreException { this(Context.getOrCreate(params), transactionReceivedListeners, blockStore); } /** * Constructs a BlockChain connected to the given list of listeners (eg, wallets) and a store. */ public AbstractBlockChain(Context context, List<? extends Wallet> wallets, BlockStore blockStore) throws BlockStoreException { this.blockStore = blockStore; chainHead = blockStore.getChainHead(); log.info("chain head is at height {}:\n{}", chainHead.getHeight(), chainHead.getHeader()); this.params = context.getParams(); this.newBestBlockListeners = new CopyOnWriteArrayList<>(); this.reorganizeListeners = new CopyOnWriteArrayList<>(); this.transactionReceivedListeners = new CopyOnWriteArrayList<>(); for (NewBestBlockListener l : wallets) addNewBestBlockListener(Threading.SAME_THREAD, l); for (ReorganizeListener l : wallets) addReorganizeListener(Threading.SAME_THREAD, l); for (TransactionReceivedInBlockListener l : wallets) addTransactionReceivedListener(Threading.SAME_THREAD, l); this.versionTally = new VersionTally(context.getParams()); this.versionTally.initialize(blockStore, chainHead); } /** * Add a wallet to the BlockChain. Note that the wallet will be unaffected by any blocks received while it * was not part of this BlockChain. This method is useful if the wallet has just been created, and its keys * have never been in use, or if the wallet has been loaded along with the BlockChain. Note that adding multiple * wallets is not well tested! */ public final void addWallet(Wallet wallet) { addNewBestBlockListener(Threading.SAME_THREAD, wallet); addReorganizeListener(Threading.SAME_THREAD, wallet); addTransactionReceivedListener(Threading.SAME_THREAD, wallet); int walletHeight = wallet.getLastBlockSeenHeight(); int chainHeight = getBestChainHeight(); if (walletHeight != chainHeight && walletHeight > 0) { log.warn("Wallet/chain height mismatch: {} vs {}", walletHeight, chainHeight); log.warn("Hashes: {} vs {}", wallet.getLastBlockSeenHash(), getChainHead().getHeader().getHash()); // This special case happens when the VM crashes because of a transaction received. It causes the updated // block store to persist, but not the wallet. In order to fix the issue, we roll back the block store to // the wallet height to make it look like as if the block has never been received. if (walletHeight < chainHeight) { try { rollbackBlockStore(walletHeight); log.info("Rolled back block store to height {}.", walletHeight); } catch (BlockStoreException x) { log.warn("Rollback of block store failed, continuing with mismatched heights. This can happen due to a replay."); } } } } /** Removes a wallet from the chain. */ public void removeWallet(Wallet wallet) { removeNewBestBlockListener(wallet); removeReorganizeListener(wallet); removeTransactionReceivedListener(wallet); } /** * Adds a {@link NewBestBlockListener} listener to the chain. */ public void addNewBestBlockListener(NewBestBlockListener listener) { addNewBestBlockListener(Threading.USER_THREAD, listener); } /** * Adds a {@link NewBestBlockListener} listener to the chain. */ public final void addNewBestBlockListener(Executor executor, NewBestBlockListener listener) { newBestBlockListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds a generic {@link ReorganizeListener} listener to the chain. */ public void addReorganizeListener(ReorganizeListener listener) { addReorganizeListener(Threading.USER_THREAD, listener); } /** * Adds a generic {@link ReorganizeListener} listener to the chain. */ public final void addReorganizeListener(Executor executor, ReorganizeListener listener) { reorganizeListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds a generic {@link TransactionReceivedInBlockListener} listener to the chain. */ public void addTransactionReceivedListener(TransactionReceivedInBlockListener listener) { addTransactionReceivedListener(Threading.USER_THREAD, listener); } /** * Adds a generic {@link TransactionReceivedInBlockListener} listener to the chain. */ public final void addTransactionReceivedListener(Executor executor, TransactionReceivedInBlockListener listener) { transactionReceivedListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Removes the given {@link NewBestBlockListener} from the chain. */ public void removeNewBestBlockListener(NewBestBlockListener listener) { ListenerRegistration.removeFromList(listener, newBestBlockListeners); } /** * Removes the given {@link ReorganizeListener} from the chain. */ public void removeReorganizeListener(ReorganizeListener listener) { ListenerRegistration.removeFromList(listener, reorganizeListeners); } /** * Removes the given {@link TransactionReceivedInBlockListener} from the chain. */ public void removeTransactionReceivedListener(TransactionReceivedInBlockListener listener) { ListenerRegistration.removeFromList(listener, transactionReceivedListeners); } /** * Returns the {@link BlockStore} the chain was constructed with. You can use this to iterate over the chain. */ public BlockStore getBlockStore() { return blockStore; } /** * Adds/updates the given {@link Block} with the block store. * This version is used when the transactions have not been verified. * @param storedPrev The {@link StoredBlock} which immediately precedes block. * @param block The {@link Block} to add/update. * @return the newly created {@link StoredBlock} */ protected abstract StoredBlock addToBlockStore(StoredBlock storedPrev, Block block) throws BlockStoreException, VerificationException; /** * Adds/updates the given {@link StoredBlock} with the block store. * This version is used when the transactions have already been verified to properly spend txOutputChanges. * @param storedPrev The {@link StoredBlock} which immediately precedes block. * @param header The {@link StoredBlock} to add/update. * @param txOutputChanges The total sum of all changes made by this block to the set of open transaction outputs * (from a call to connectTransactions), if in fully verifying mode (null otherwise). * @return the newly created {@link StoredBlock} */ protected abstract StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, @Nullable TransactionOutputChanges txOutputChanges) throws BlockStoreException, VerificationException; /** * Rollback the block store to a given height. This is currently only supported by {@link BlockChain} instances. * * @throws BlockStoreException * if the operation fails or is unsupported. */ protected abstract void rollbackBlockStore(int height) throws BlockStoreException; /** * Called before setting chain head in memory. * Should write the new head to block store and then commit any database transactions * that were started by disconnectTransactions/connectTransactions. */ protected abstract void doSetChainHead(StoredBlock chainHead) throws BlockStoreException; /** * Called if we (possibly) previously called disconnectTransaction/connectTransactions, * but will not be calling preSetChainHead as a block failed verification. * Can be used to abort database transactions that were started by * disconnectTransactions/connectTransactions. */ protected abstract void notSettingChainHead() throws BlockStoreException; /** * For a standard BlockChain, this should return blockStore.get(hash), * for a FullPrunedBlockChain blockStore.getOnceUndoableStoredBlock(hash) */ protected abstract StoredBlock getStoredBlockInCurrentScope(Sha256Hash hash) throws BlockStoreException; /** * Processes a received block and tries to add it to the chain. If there's something wrong with the block an * exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false. * If the block can be connected to the chain, returns true. * Accessing block's transactions in another thread while this method runs may result in undefined behavior. */ public boolean add(Block block) throws VerificationException, PrunedException { try { return add(block, true, null, null); } catch (BlockStoreException e) { // TODO: Figure out a better way to propagate this exception to the user. throw new RuntimeException(e); } catch (VerificationException e) { try { notSettingChainHead(); } catch (BlockStoreException e1) { throw new RuntimeException(e1); } throw new VerificationException("Could not verify block:\n" + block.toString(), e); } } /** * Processes a received block and tries to add it to the chain. If there's something wrong with the block an * exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false. * If the block can be connected to the chain, returns true. */ public boolean add(FilteredBlock block) throws VerificationException, PrunedException { try { // The block has a list of hashes of transactions that matched the Bloom filter, and a list of associated // Transaction objects. There may be fewer Transaction objects than hashes, this is expected. It can happen // in the case where we were already around to witness the initial broadcast, so we downloaded the // transaction and sent it to the wallet before this point (the wallet may have thrown it away if it was // a false positive, as expected in any Bloom filtering scheme). The filteredTxn list here will usually // only be full of data when we are catching up to the head of the chain and thus haven't witnessed any // of the transactions. return add(block.getBlockHeader(), true, block.getTransactionHashes(), block.getAssociatedTransactions()); } catch (BlockStoreException e) { // TODO: Figure out a better way to propagate this exception to the user. throw new RuntimeException(e); } catch (VerificationException e) { try { notSettingChainHead(); } catch (BlockStoreException e1) { throw new RuntimeException(e1); } throw new VerificationException("Could not verify block " + block.getHash().toString() + "\n" + block.toString(), e); } } /** * Whether or not we are maintaining a set of unspent outputs and are verifying all transactions. * Also indicates that all calls to add() should provide a block containing transactions */ protected abstract boolean shouldVerifyTransactions(); /** * Connect each transaction in block.transactions, verifying them as we go and removing spent outputs * If an error is encountered in a transaction, no changes should be made to the underlying BlockStore. * and a VerificationException should be thrown. * Only called if(shouldVerifyTransactions()) * @throws VerificationException if an attempt was made to spend an already-spent output, or if a transaction incorrectly solved an output script. * @throws BlockStoreException if the block store had an underlying error. * @return The full set of all changes made to the set of open transaction outputs. */ protected abstract TransactionOutputChanges connectTransactions(int height, Block block) throws VerificationException, BlockStoreException; /** * Load newBlock from BlockStore and connect its transactions, returning changes to the set of unspent transactions. * If an error is encountered in a transaction, no changes should be made to the underlying BlockStore. * Only called if(shouldVerifyTransactions()) * @throws PrunedException if newBlock does not exist as a {@link StoredUndoableBlock} in the block store. * @throws VerificationException if an attempt was made to spend an already-spent output, or if a transaction incorrectly solved an output script. * @throws BlockStoreException if the block store had an underlying error or newBlock does not exist in the block store at all. * @return The full set of all changes made to the set of open transaction outputs. */ protected abstract TransactionOutputChanges connectTransactions(StoredBlock newBlock) throws VerificationException, BlockStoreException, PrunedException; // filteredTxHashList contains all transactions, filteredTxn just a subset private boolean add(Block block, boolean tryConnecting, @Nullable List<Sha256Hash> filteredTxHashList, @Nullable Map<Sha256Hash, Transaction> filteredTxn) throws BlockStoreException, VerificationException, PrunedException { // TODO: Use read/write locks to ensure that during chain download properties are still low latency. lock.lock(); try { // Quick check for duplicates to avoid an expensive check further down (in findSplit). This can happen a lot // when connecting orphan transactions due to the dumb brute force algorithm we use. if (block.equals(getChainHead().getHeader())) { return true; } if (tryConnecting && orphanBlocks.containsKey(block.getHash())) { return false; } // If we want to verify transactions (ie we are running with full blocks), verify that block has transactions if (shouldVerifyTransactions() && block.getTransactions() == null) throw new VerificationException("Got a block header while running in full-block mode"); // Check for already-seen block, but only for full pruned mode, where the DB is // more likely able to handle these queries quickly. if (shouldVerifyTransactions() && blockStore.get(block.getHash()) != null) { return true; } final StoredBlock storedPrev; final int height; final EnumSet<Block.VerifyFlag> flags; // Prove the block is internally valid: hash is lower than target, etc. This only checks the block contents // if there is a tx sending or receiving coins using an address in one of our wallets. And those transactions // are only lightly verified: presence in a valid connecting block is taken as proof of validity. See the // article here for more details: https://bitcoinj.github.io/security-model try { block.verifyHeader(); storedPrev = getStoredBlockInCurrentScope(block.getPrevBlockHash()); if (storedPrev != null) { height = storedPrev.getHeight() + 1; } else { height = Block.BLOCK_HEIGHT_UNKNOWN; } flags = params.getBlockVerificationFlags(block, versionTally, height); if (shouldVerifyTransactions()) block.verifyTransactions(height, flags); } catch (VerificationException e) { log.error("Failed to verify block: ", e); log.error(block.getHashAsString()); throw e; } // Try linking it to a place in the currently known blocks. if (storedPrev == null) { // We can't find the previous block. Probably we are still in the process of downloading the chain and a // block was solved whilst we were doing it. We put it to one side and try to connect it later when we // have more blocks. checkState(tryConnecting, "bug in tryConnectingOrphans"); log.warn("Block does not connect: {} prev {}", block.getHashAsString(), block.getPrevBlockHash()); orphanBlocks.put(block.getHash(), new OrphanBlock(block, filteredTxHashList, filteredTxn)); if (tryConnecting) tryConnectingOrphans(); return false; } else { checkState(lock.isHeldByCurrentThread()); // It connects to somewhere on the chain. Not necessarily the top of the best known chain. params.checkDifficultyTransitions(storedPrev, block, blockStore); connectBlock(block, storedPrev, shouldVerifyTransactions(), filteredTxHashList, filteredTxn); if (tryConnecting) tryConnectingOrphans(); return true; } } finally { lock.unlock(); } } /** * Returns the hashes of the currently stored orphan blocks and then deletes them from this objects storage. * Used by Peer when a filter exhaustion event has occurred and thus any orphan blocks that have been downloaded * might be inaccurate/incomplete. */ public Set<Sha256Hash> drainOrphanBlocks() { lock.lock(); try { Set<Sha256Hash> hashes = new HashSet<>(orphanBlocks.keySet()); orphanBlocks.clear(); return hashes; } finally { lock.unlock(); } } // expensiveChecks enables checks that require looking at blocks further back in the chain // than the previous one when connecting (eg median timestamp check) // It could be exposed, but for now we just set it to shouldVerifyTransactions() private void connectBlock(final Block block, StoredBlock storedPrev, boolean expensiveChecks, @Nullable final List<Sha256Hash> filteredTxHashList, @Nullable final Map<Sha256Hash, Transaction> filteredTxn) throws BlockStoreException, VerificationException, PrunedException { checkState(lock.isHeldByCurrentThread()); boolean filtered = filteredTxHashList != null && filteredTxn != null; // Check that we aren't connecting a block that fails a checkpoint check if (!params.passesCheckpoint(storedPrev.getHeight() + 1, block.getHash())) throw new VerificationException("Block failed checkpoint lockin at " + (storedPrev.getHeight() + 1)); if (shouldVerifyTransactions()) { for (Transaction tx : block.getTransactions()) if (!tx.isFinal(storedPrev.getHeight() + 1, block.getTimeSeconds())) throw new VerificationException("Block contains non-final transaction"); } StoredBlock head = getChainHead(); if (storedPrev.equals(head)) { if (filtered && filteredTxn.size() > 0) { log.debug("Block {} connects to top of best chain with {} transaction(s) of which we were sent {}", block.getHashAsString(), filteredTxHashList.size(), filteredTxn.size()); for (Sha256Hash hash : filteredTxHashList) log.debug(" matched tx {}", hash); } if (expensiveChecks && block.getTimeSeconds() <= getMedianTimestampOfRecentBlocks(head, blockStore)) throw new VerificationException("Block's timestamp is too early"); // BIP 66 & 65: Enforce block version 3/4 once they are a supermajority of blocks // NOTE: This requires 1,000 blocks since the last checkpoint (on main // net, less on test) in order to be applied. It is also limited to // stopping addition of new v2/3 blocks to the tip of the chain. if (block.getVersion() == Block.BLOCK_VERSION_BIP34 || block.getVersion() == Block.BLOCK_VERSION_BIP66) { final Integer count = versionTally.getCountAtOrAbove(block.getVersion() + 1); if (count != null && count >= params.getMajorityRejectBlockOutdated()) { throw new VerificationException.BlockVersionOutOfDate(block.getVersion()); } } // This block connects to the best known block, it is a normal continuation of the system. TransactionOutputChanges txOutChanges = null; if (shouldVerifyTransactions()) txOutChanges = connectTransactions(storedPrev.getHeight() + 1, block); StoredBlock newStoredBlock = addToBlockStore(storedPrev, block.getTransactions() == null ? block : block.cloneAsHeader(), txOutChanges); versionTally.add(block.getVersion()); setChainHead(newStoredBlock); if (log.isDebugEnabled()) log.debug("Chain is now {} blocks high, running listeners", newStoredBlock.getHeight()); informListenersForNewBlock(block, NewBlockType.BEST_CHAIN, filteredTxHashList, filteredTxn, newStoredBlock); } else { // This block connects to somewhere other than the top of the best known chain. We treat these differently. // // Note that we send the transactions to the wallet FIRST, even if we're about to re-organize this block // to become the new best chain head. This simplifies handling of the re-org in the Wallet class. StoredBlock newBlock = storedPrev.build(block); boolean haveNewBestChain = newBlock.moreWorkThan(head); if (haveNewBestChain) { log.info("Block is causing a re-organize"); } else { StoredBlock splitPoint = findSplit(newBlock, head, blockStore); if (splitPoint != null && splitPoint.equals(newBlock)) { // newStoredBlock is a part of the same chain, there's no fork. This happens when we receive a block // that we already saw and linked into the chain previously, which isn't the chain head. // Re-processing it is confusing for the wallet so just skip. log.warn("Saw duplicated block in best chain at height {}: {}", newBlock.getHeight(), newBlock.getHeader().getHash()); return; } if (splitPoint == null) { // This should absolutely never happen // (lets not write the full block to disk to keep any bugs which allow this to happen // from writing unreasonable amounts of data to disk) throw new VerificationException("Block forks the chain but splitPoint is null"); } else { // We aren't actually spending any transactions (yet) because we are on a fork addToBlockStore(storedPrev, block); int splitPointHeight = splitPoint.getHeight(); String splitPointHash = splitPoint.getHeader().getHashAsString(); log.info("Block forks the chain at height {}/block {}, but it did not cause a reorganize:\n{}", splitPointHeight, splitPointHash, newBlock.getHeader().getHashAsString()); } } // We may not have any transactions if we received only a header, which can happen during fast catchup. // If we do, send them to the wallet but state that they are on a side chain so it knows not to try and // spend them until they become activated. if (block.getTransactions() != null || filtered) { informListenersForNewBlock(block, NewBlockType.SIDE_CHAIN, filteredTxHashList, filteredTxn, newBlock); } if (haveNewBestChain) handleNewBestChain(storedPrev, newBlock, block, expensiveChecks); } } private void informListenersForNewBlock(final Block block, final NewBlockType newBlockType, @Nullable final List<Sha256Hash> filteredTxHashList, @Nullable final Map<Sha256Hash, Transaction> filteredTxn, final StoredBlock newStoredBlock) throws VerificationException { // Notify the listeners of the new block, so the depth and workDone of stored transactions can be updated // (in the case of the listener being a wallet). Wallets need to know how deep each transaction is so // coinbases aren't used before maturity. boolean first = true; Set<Sha256Hash> falsePositives = new HashSet<>(); if (filteredTxHashList != null) falsePositives.addAll(filteredTxHashList); for (final ListenerRegistration<TransactionReceivedInBlockListener> registration : transactionReceivedListeners) { if (registration.executor == Threading.SAME_THREAD) { informListenerForNewTransactions(block, newBlockType, filteredTxHashList, filteredTxn, newStoredBlock, first, registration.listener, falsePositives); } else { // Listener wants to be run on some other thread, so marshal it across here. final boolean notFirst = !first; registration.executor.execute(new Runnable() { @Override public void run() { try { // We can't do false-positive handling when executing on another thread Set<Sha256Hash> ignoredFalsePositives = new HashSet<>(); informListenerForNewTransactions(block, newBlockType, filteredTxHashList, filteredTxn, newStoredBlock, notFirst, registration.listener, ignoredFalsePositives); } catch (VerificationException e) { log.error("Block chain listener threw exception: ", e); // Don't attempt to relay this back to the original peer thread if this was an async // listener invocation. // TODO: Make exception reporting a global feature and use it here. } } }); } first = false; } for (final ListenerRegistration<NewBestBlockListener> registration : newBestBlockListeners) { if (registration.executor == Threading.SAME_THREAD) { if (newBlockType == NewBlockType.BEST_CHAIN) registration.listener.notifyNewBestBlock(newStoredBlock); } else { // Listener wants to be run on some other thread, so marshal it across here. registration.executor.execute(new Runnable() { @Override public void run() { try { if (newBlockType == NewBlockType.BEST_CHAIN) registration.listener.notifyNewBestBlock(newStoredBlock); } catch (VerificationException e) { log.error("Block chain listener threw exception: ", e); // Don't attempt to relay this back to the original peer thread if this was an async // listener invocation. // TODO: Make exception reporting a global feature and use it here. } } }); } first = false; } trackFalsePositives(falsePositives.size()); } private static void informListenerForNewTransactions(Block block, NewBlockType newBlockType, @Nullable List<Sha256Hash> filteredTxHashList, @Nullable Map<Sha256Hash, Transaction> filteredTxn, StoredBlock newStoredBlock, boolean first, TransactionReceivedInBlockListener listener, Set<Sha256Hash> falsePositives) throws VerificationException { if (block.getTransactions() != null) { // If this is not the first wallet, ask for the transactions to be duplicated before being given // to the wallet when relevant. This ensures that if we have two connected wallets and a tx that // is relevant to both of them, they don't end up accidentally sharing the same object (which can // result in temporary in-memory corruption during re-orgs). See bug 257. We only duplicate in // the case of multiple wallets to avoid an unnecessary efficiency hit in the common case. sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getTransactions(), !first, falsePositives); } else if (filteredTxHashList != null) { checkNotNull(filteredTxn); // We must send transactions to listeners in the order they appeared in the block - thus we iterate over the // set of hashes and call sendTransactionsToListener with individual txn when they have not already been // seen in loose broadcasts - otherwise notifyTransactionIsInBlock on the hash. int relativityOffset = 0; for (Sha256Hash hash : filteredTxHashList) { Transaction tx = filteredTxn.get(hash); if (tx != null) { sendTransactionsToListener(newStoredBlock, newBlockType, listener, relativityOffset, Collections.singletonList(tx), !first, falsePositives); } else { if (listener.notifyTransactionIsInBlock(hash, newStoredBlock, newBlockType, relativityOffset)) { falsePositives.remove(hash); } } relativityOffset++; } } } /** * Gets the median timestamp of the last 11 blocks */ private static long getMedianTimestampOfRecentBlocks(StoredBlock storedBlock, BlockStore store) throws BlockStoreException { long[] timestamps = new long[11]; int unused = 9; timestamps[10] = storedBlock.getHeader().getTimeSeconds(); while (unused >= 0 && (storedBlock = storedBlock.getPrev(store)) != null) timestamps[unused--] = storedBlock.getHeader().getTimeSeconds(); Arrays.sort(timestamps, unused+1, 11); return timestamps[unused + (11-unused)/2]; } /** * Disconnect each transaction in the block (after reading it from the block store) * Only called if(shouldVerifyTransactions()) * @throws PrunedException if block does not exist as a {@link StoredUndoableBlock} in the block store. * @throws BlockStoreException if the block store had an underlying error or block does not exist in the block store at all. */ protected abstract void disconnectTransactions(StoredBlock block) throws PrunedException, BlockStoreException; /** * Called as part of connecting a block when the new block results in a different chain having higher total work. * * if (shouldVerifyTransactions) * Either newChainHead needs to be in the block store as a FullStoredBlock, or (block != null && block.transactions != null) */ private void handleNewBestChain(StoredBlock storedPrev, StoredBlock newChainHead, Block block, boolean expensiveChecks) throws BlockStoreException, VerificationException, PrunedException { checkState(lock.isHeldByCurrentThread()); // This chain has overtaken the one we currently believe is best. Reorganize is required. // // Firstly, calculate the block at which the chain diverged. We only need to examine the // chain from beyond this block to find differences. StoredBlock head = getChainHead(); final StoredBlock splitPoint = findSplit(newChainHead, head, blockStore); log.info("Re-organize after split at height {}", splitPoint.getHeight()); log.info("Old chain head: {}", head.getHeader().getHashAsString()); log.info("New chain head: {}", newChainHead.getHeader().getHashAsString()); log.info("Split at block: {}", splitPoint.getHeader().getHashAsString()); // Then build a list of all blocks in the old part of the chain and the new part. final LinkedList<StoredBlock> oldBlocks = getPartialChain(head, splitPoint, blockStore); final LinkedList<StoredBlock> newBlocks = getPartialChain(newChainHead, splitPoint, blockStore); // Disconnect each transaction in the previous best chain that is no longer in the new best chain StoredBlock storedNewHead = splitPoint; if (shouldVerifyTransactions()) { for (StoredBlock oldBlock : oldBlocks) { try { disconnectTransactions(oldBlock); } catch (PrunedException e) { // We threw away the data we need to re-org this deep! We need to go back to a peer with full // block contents and ask them for the relevant data then rebuild the indexs. Or we could just // give up and ask the human operator to help get us unstuck (eg, rescan from the genesis block). // TODO: Retry adding this block when we get a block with hash e.getHash() throw e; } } StoredBlock cursor; // Walk in ascending chronological order. for (Iterator<StoredBlock> it = newBlocks.descendingIterator(); it.hasNext();) { cursor = it.next(); Block cursorBlock = cursor.getHeader(); if (expensiveChecks && cursorBlock.getTimeSeconds() <= getMedianTimestampOfRecentBlocks(cursor.getPrev(blockStore), blockStore)) throw new VerificationException("Block's timestamp is too early during reorg"); TransactionOutputChanges txOutChanges; if (cursor != newChainHead || block == null) txOutChanges = connectTransactions(cursor); else txOutChanges = connectTransactions(newChainHead.getHeight(), block); storedNewHead = addToBlockStore(storedNewHead, cursorBlock.cloneAsHeader(), txOutChanges); } } else { // (Finally) write block to block store storedNewHead = addToBlockStore(storedPrev, newChainHead.getHeader()); } // Now inform the listeners. This is necessary so the set of currently active transactions (that we can spend) // can be updated to take into account the re-organize. We might also have received new coins we didn't have // before and our previous spends might have been undone. for (final ListenerRegistration<ReorganizeListener> registration : reorganizeListeners) { if (registration.executor == Threading.SAME_THREAD) { // Short circuit the executor so we can propagate any exceptions. // TODO: Do we really need to do this or should it be irrelevant? registration.listener.reorganize(splitPoint, oldBlocks, newBlocks); } else { registration.executor.execute(new Runnable() { @Override public void run() { try { registration.listener.reorganize(splitPoint, oldBlocks, newBlocks); } catch (VerificationException e) { log.error("Block chain listener threw exception during reorg", e); } } }); } } // Update the pointer to the best known block. setChainHead(storedNewHead); } /** * Returns the set of contiguous blocks between 'higher' and 'lower'. Higher is included, lower is not. */ private static LinkedList<StoredBlock> getPartialChain(StoredBlock higher, StoredBlock lower, BlockStore store) throws BlockStoreException { checkArgument(higher.getHeight() > lower.getHeight(), "higher and lower are reversed"); LinkedList<StoredBlock> results = new LinkedList<>(); StoredBlock cursor = higher; do { results.add(cursor); cursor = checkNotNull(cursor.getPrev(store), "Ran off the end of the chain"); } while (!cursor.equals(lower)); return results; } /** * Locates the point in the chain at which newStoredBlock and chainHead diverge. Returns null if no split point was * found (ie they are not part of the same chain). Returns newChainHead or chainHead if they don't actually diverge * but are part of the same chain. */ private static StoredBlock findSplit(StoredBlock newChainHead, StoredBlock oldChainHead, BlockStore store) throws BlockStoreException { StoredBlock currentChainCursor = oldChainHead; StoredBlock newChainCursor = newChainHead; // Loop until we find the block both chains have in common. Example: // // A -> B -> C -> D // \--> E -> F -> G // // findSplit will return block B. oldChainHead = D and newChainHead = G. while (!currentChainCursor.equals(newChainCursor)) { if (currentChainCursor.getHeight() > newChainCursor.getHeight()) { currentChainCursor = currentChainCursor.getPrev(store); checkNotNull(currentChainCursor, "Attempt to follow an orphan chain"); } else { newChainCursor = newChainCursor.getPrev(store); checkNotNull(newChainCursor, "Attempt to follow an orphan chain"); } } return currentChainCursor; } /** * @return the height of the best known chain, convenience for {@code getChainHead().getHeight()}. */ public final int getBestChainHeight() { return getChainHead().getHeight(); } public enum NewBlockType { BEST_CHAIN, SIDE_CHAIN } private static void sendTransactionsToListener(StoredBlock block, NewBlockType blockType, TransactionReceivedInBlockListener listener, int relativityOffset, List<Transaction> transactions, boolean clone, Set<Sha256Hash> falsePositives) throws VerificationException { for (Transaction tx : transactions) { try { falsePositives.remove(tx.getTxId()); if (clone) tx = tx.params.getDefaultSerializer().makeTransaction(tx.bitcoinSerialize()); listener.receiveFromBlock(tx, block, blockType, relativityOffset++); } catch (ScriptException e) { // We don't want scripts we don't understand to break the block chain so just note that this tx was // not scanned here and continue. log.warn("Failed to parse a script: " + e.toString()); } catch (ProtocolException e) { // Failed to duplicate tx, should never happen. throw new RuntimeException(e); } } } protected void setChainHead(StoredBlock chainHead) throws BlockStoreException { doSetChainHead(chainHead); synchronized (chainHeadLock) { this.chainHead = chainHead; } } /** * For each block in orphanBlocks, see if we can now fit it on top of the chain and if so, do so. */ private void tryConnectingOrphans() throws VerificationException, BlockStoreException, PrunedException { checkState(lock.isHeldByCurrentThread()); // For each block in our orphan list, try and fit it onto the head of the chain. If we succeed remove it // from the list and keep going. If we changed the head of the list at the end of the round try again until // we can't fit anything else on the top. // // This algorithm is kind of crappy, we should do a topo-sort then just connect them in order, but for small // numbers of orphan blocks it does OK. int blocksConnectedThisRound; do { blocksConnectedThisRound = 0; Iterator<OrphanBlock> iter = orphanBlocks.values().iterator(); while (iter.hasNext()) { OrphanBlock orphanBlock = iter.next(); // Look up the blocks previous. StoredBlock prev = getStoredBlockInCurrentScope(orphanBlock.block.getPrevBlockHash()); if (prev == null) { // This is still an unconnected/orphan block. if (log.isDebugEnabled()) log.debug("Orphan block {} is not connectable right now", orphanBlock.block.getHash()); continue; } // Otherwise we can connect it now. // False here ensures we don't recurse infinitely downwards when connecting huge chains. log.info("Connected orphan {}", orphanBlock.block.getHash()); add(orphanBlock.block, false, orphanBlock.filteredTxHashes, orphanBlock.filteredTxn); iter.remove(); blocksConnectedThisRound++; } if (blocksConnectedThisRound > 0) { log.info("Connected {} orphan blocks.", blocksConnectedThisRound); } } while (blocksConnectedThisRound > 0); } /** * Returns the block at the head of the current best chain. This is the block which represents the greatest * amount of cumulative work done. */ public StoredBlock getChainHead() { synchronized (chainHeadLock) { return chainHead; } } /** * An orphan block is one that does not connect to the chain anywhere (ie we can't find its parent, therefore * it's an orphan). Typically this occurs when we are downloading the chain and didn't reach the head yet, and/or * if a block is solved whilst we are downloading. It's possible that we see a small amount of orphan blocks which * chain together, this method tries walking backwards through the known orphan blocks to find the bottom-most. * * @return from or one of froms parents, or null if "from" does not identify an orphan block */ @Nullable public Block getOrphanRoot(Sha256Hash from) { lock.lock(); try { OrphanBlock cursor = orphanBlocks.get(from); if (cursor == null) return null; OrphanBlock tmp; while ((tmp = orphanBlocks.get(cursor.block.getPrevBlockHash())) != null) { cursor = tmp; } return cursor.block; } finally { lock.unlock(); } } /** Returns true if the given block is currently in the orphan blocks list. */ public boolean isOrphan(Sha256Hash block) { lock.lock(); try { return orphanBlocks.containsKey(block); } finally { lock.unlock(); } } /** * Returns an estimate of when the given block will be reached, assuming a perfect 10 minute average for each * block. This is useful for turning transaction lock times into human readable times. Note that a height in * the past will still be estimated, even though the time of solving is actually known (we won't scan backwards * through the chain to obtain the right answer). */ public Date estimateBlockTime(int height) { synchronized (chainHeadLock) { long offset = height - chainHead.getHeight(); long headTime = chainHead.getHeader().getTimeSeconds(); long estimated = (headTime * 1000) + (1000L * 60L * 10L * offset); return new Date(estimated); } } /** * Returns a future that completes when the block chain has reached the given height. Yields the * {@link StoredBlock} of the block that reaches that height first. The future completes on a peer thread. */ public ListenableFuture<StoredBlock> getHeightFuture(final int height) { final SettableFuture<StoredBlock> result = SettableFuture.create(); addNewBestBlockListener(Threading.SAME_THREAD, new NewBestBlockListener() { @Override public void notifyNewBestBlock(StoredBlock block) throws VerificationException { if (block.getHeight() >= height) { removeNewBestBlockListener(this); result.set(block); } } }); return result; } /** * The false positive rate is the average over all blockchain transactions of: * * - 1.0 if the transaction was false-positive (was irrelevant to all listeners) * - 0.0 if the transaction was relevant or filtered out */ public double getFalsePositiveRate() { return falsePositiveRate; } /* * We completed handling of a filtered block. Update false-positive estimate based * on the total number of transactions in the original block. * * count includes filtered transactions, transactions that were passed in and were relevant * and transactions that were false positives (i.e. includes all transactions in the block). */ protected void trackFilteredTransactions(int count) { // Track non-false-positives in batch. Each non-false-positive counts as // 0.0 towards the estimate. // // This is slightly off because we are applying false positive tracking before non-FP tracking, // which counts FP as if they came at the beginning of the block. Assuming uniform FP // spread in a block, this will somewhat underestimate the FP rate (5% for 1000 tx block). double alphaDecay = Math.pow(1 - FP_ESTIMATOR_ALPHA, count); // new_rate = alpha_decay * new_rate falsePositiveRate = alphaDecay * falsePositiveRate; double betaDecay = Math.pow(1 - FP_ESTIMATOR_BETA, count); // trend = beta * (new_rate - old_rate) + beta_decay * trend falsePositiveTrend = FP_ESTIMATOR_BETA * count * (falsePositiveRate - previousFalsePositiveRate) + betaDecay * falsePositiveTrend; // new_rate += alpha_decay * trend falsePositiveRate += alphaDecay * falsePositiveTrend; // Stash new_rate in old_rate previousFalsePositiveRate = falsePositiveRate; } /* Irrelevant transactions were received. Update false-positive estimate. */ void trackFalsePositives(int count) { // Track false positives in batch by adding alpha to the false positive estimate once per count. // Each false positive counts as 1.0 towards the estimate. falsePositiveRate += FP_ESTIMATOR_ALPHA * count; if (count > 0 && log.isDebugEnabled()) log.debug("{} false positives, current rate = {} trend = {}", count, falsePositiveRate, falsePositiveTrend); } /** Resets estimates of false positives. Used when the filter is sent to the peer. */ public void resetFalsePositiveEstimate() { falsePositiveRate = 0; falsePositiveTrend = 0; previousFalsePositiveRate = 0; } protected VersionTally getVersionTally() { return versionTally; } }
core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java
/* * Copyright 2012 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.*; import com.google.common.util.concurrent.*; import org.bitcoinj.core.listeners.*; import org.bitcoinj.script.ScriptException; import org.bitcoinj.store.*; import org.bitcoinj.utils.*; import org.bitcoinj.wallet.Wallet; import org.slf4j.*; import javax.annotation.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; import static com.google.common.base.Preconditions.*; /** * <p>An AbstractBlockChain holds a series of {@link Block} objects, links them together, and knows how to verify that * the chain follows the rules of the {@link NetworkParameters} for this chain.</p> * * <p>It can be connected to a {@link Wallet}, and also {@link TransactionReceivedInBlockListener}s that can receive transactions and * notifications of re-organizations.</p> * * <p>An AbstractBlockChain implementation must be connected to a {@link BlockStore} implementation. The chain object * by itself doesn't store any data, that's delegated to the store. Which store you use is a decision best made by * reading the getting started guide, but briefly, fully validating block chains need fully validating stores. In * the lightweight SPV mode, a {@link SPVBlockStore} is the right choice.</p> * * <p>This class implements an abstract class which makes it simple to create a BlockChain that does/doesn't do full * verification. It verifies headers and is implements most of what is required to implement SPV mode, but * also provides callback hooks which can be used to do full verification.</p> * * <p>There are two subclasses of AbstractBlockChain that are useful: {@link BlockChain}, which is the simplest * class and implements <i>simplified payment verification</i>. This is a lightweight and efficient mode that does * not verify the contents of blocks, just their headers. A {@link FullPrunedBlockChain} paired with a * {@link H2FullPrunedBlockStore} implements full verification, which is equivalent to * Bitcoin Core. To learn more about the alternative security models, please consult the articles on the * website.</p> * * <b>Theory</b> * * <p>The 'chain' is actually a tree although in normal operation it operates mostly as a list of {@link Block}s. * When multiple new head blocks are found simultaneously, there are multiple stories of the economy competing to become * the one true consensus. This can happen naturally when two miners solve a block within a few seconds of each other, * or it can happen when the chain is under attack.</p> * * <p>A reference to the head block of the best known chain is stored. If you can reach the genesis block by repeatedly * walking through the prevBlock pointers, then we say this is a full chain. If you cannot reach the genesis block * we say it is an orphan chain. Orphan chains can occur when blocks are solved and received during the initial block * chain download, or if we connect to a peer that doesn't send us blocks in order.</p> * * <p>A reorganize occurs when the blocks that make up the best known chain change. Note that simply adding a * new block to the top of the best chain isn't a reorganize, but that a reorganize is always triggered by adding * a new block that connects to some other (non best head) block. By "best" we mean the chain representing the largest * amount of work done.</p> * * <p>Every so often the block chain passes a difficulty transition point. At that time, all the blocks in the last * 2016 blocks are examined and a new difficulty target is calculated from them.</p> */ public abstract class AbstractBlockChain { private static final Logger log = LoggerFactory.getLogger(AbstractBlockChain.class); protected final ReentrantLock lock = Threading.lock(AbstractBlockChain.class); /** Keeps a map of block hashes to StoredBlocks. */ private final BlockStore blockStore; /** * Tracks the top of the best known chain.<p> * * Following this one down to the genesis block produces the story of the economy from the creation of Bitcoin * until the present day. The chain head can change if a new set of blocks is received that results in a chain of * greater work than the one obtained by following this one down. In that case a reorganize is triggered, * potentially invalidating transactions in our wallet. */ protected StoredBlock chainHead; // TODO: Scrap this and use a proper read/write for all of the block chain objects. // The chainHead field is read/written synchronized with this object rather than BlockChain. However writing is // also guaranteed to happen whilst BlockChain is synchronized (see setChainHead). The goal of this is to let // clients quickly access the chain head even whilst the block chain is downloading and thus the BlockChain is // locked most of the time. private final Object chainHeadLock = new Object(); protected final NetworkParameters params; private final CopyOnWriteArrayList<ListenerRegistration<NewBestBlockListener>> newBestBlockListeners; private final CopyOnWriteArrayList<ListenerRegistration<ReorganizeListener>> reorganizeListeners; private final CopyOnWriteArrayList<ListenerRegistration<TransactionReceivedInBlockListener>> transactionReceivedListeners; // Holds a block header and, optionally, a list of tx hashes or block's transactions class OrphanBlock { final Block block; final List<Sha256Hash> filteredTxHashes; final Map<Sha256Hash, Transaction> filteredTxn; OrphanBlock(Block block, @Nullable List<Sha256Hash> filteredTxHashes, @Nullable Map<Sha256Hash, Transaction> filteredTxn) { final boolean filtered = filteredTxHashes != null && filteredTxn != null; Preconditions.checkArgument((block.getTransactions() == null && filtered) || (block.getTransactions() != null && !filtered)); this.block = block; this.filteredTxHashes = filteredTxHashes; this.filteredTxn = filteredTxn; } } // Holds blocks that we have received but can't plug into the chain yet, eg because they were created whilst we // were downloading the block chain. private final LinkedHashMap<Sha256Hash, OrphanBlock> orphanBlocks = new LinkedHashMap<>(); /** False positive estimation uses a double exponential moving average. */ public static final double FP_ESTIMATOR_ALPHA = 0.0001; /** False positive estimation uses a double exponential moving average. */ public static final double FP_ESTIMATOR_BETA = 0.01; private double falsePositiveRate; private double falsePositiveTrend; private double previousFalsePositiveRate; private final VersionTally versionTally; /** See {@link #AbstractBlockChain(Context, List, BlockStore)} */ public AbstractBlockChain(NetworkParameters params, List<? extends Wallet> transactionReceivedListeners, BlockStore blockStore) throws BlockStoreException { this(Context.getOrCreate(params), transactionReceivedListeners, blockStore); } /** * Constructs a BlockChain connected to the given list of listeners (eg, wallets) and a store. */ public AbstractBlockChain(Context context, List<? extends Wallet> wallets, BlockStore blockStore) throws BlockStoreException { this.blockStore = blockStore; chainHead = blockStore.getChainHead(); log.info("chain head is at height {}:\n{}", chainHead.getHeight(), chainHead.getHeader()); this.params = context.getParams(); this.newBestBlockListeners = new CopyOnWriteArrayList<>(); this.reorganizeListeners = new CopyOnWriteArrayList<>(); this.transactionReceivedListeners = new CopyOnWriteArrayList<>(); for (NewBestBlockListener l : wallets) addNewBestBlockListener(Threading.SAME_THREAD, l); for (ReorganizeListener l : wallets) addReorganizeListener(Threading.SAME_THREAD, l); for (TransactionReceivedInBlockListener l : wallets) addTransactionReceivedListener(Threading.SAME_THREAD, l); this.versionTally = new VersionTally(context.getParams()); this.versionTally.initialize(blockStore, chainHead); } /** * Add a wallet to the BlockChain. Note that the wallet will be unaffected by any blocks received while it * was not part of this BlockChain. This method is useful if the wallet has just been created, and its keys * have never been in use, or if the wallet has been loaded along with the BlockChain. Note that adding multiple * wallets is not well tested! */ public final void addWallet(Wallet wallet) { addNewBestBlockListener(Threading.SAME_THREAD, wallet); addReorganizeListener(Threading.SAME_THREAD, wallet); addTransactionReceivedListener(Threading.SAME_THREAD, wallet); int walletHeight = wallet.getLastBlockSeenHeight(); int chainHeight = getBestChainHeight(); if (walletHeight != chainHeight && walletHeight > 0) { log.warn("Wallet/chain height mismatch: {} vs {}", walletHeight, chainHeight); log.warn("Hashes: {} vs {}", wallet.getLastBlockSeenHash(), getChainHead().getHeader().getHash()); // This special case happens when the VM crashes because of a transaction received. It causes the updated // block store to persist, but not the wallet. In order to fix the issue, we roll back the block store to // the wallet height to make it look like as if the block has never been received. if (walletHeight < chainHeight) { try { rollbackBlockStore(walletHeight); log.info("Rolled back block store to height {}.", walletHeight); } catch (BlockStoreException x) { log.warn("Rollback of block store failed, continuing with mismatched heights. This can happen due to a replay."); } } } } /** Removes a wallet from the chain. */ public void removeWallet(Wallet wallet) { removeNewBestBlockListener(wallet); removeReorganizeListener(wallet); removeTransactionReceivedListener(wallet); } /** * Adds a {@link NewBestBlockListener} listener to the chain. */ public void addNewBestBlockListener(NewBestBlockListener listener) { addNewBestBlockListener(Threading.USER_THREAD, listener); } /** * Adds a {@link NewBestBlockListener} listener to the chain. */ public final void addNewBestBlockListener(Executor executor, NewBestBlockListener listener) { newBestBlockListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds a generic {@link ReorganizeListener} listener to the chain. */ public void addReorganizeListener(ReorganizeListener listener) { addReorganizeListener(Threading.USER_THREAD, listener); } /** * Adds a generic {@link ReorganizeListener} listener to the chain. */ public final void addReorganizeListener(Executor executor, ReorganizeListener listener) { reorganizeListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds a generic {@link TransactionReceivedInBlockListener} listener to the chain. */ public void addTransactionReceivedListener(TransactionReceivedInBlockListener listener) { addTransactionReceivedListener(Threading.USER_THREAD, listener); } /** * Adds a generic {@link TransactionReceivedInBlockListener} listener to the chain. */ public final void addTransactionReceivedListener(Executor executor, TransactionReceivedInBlockListener listener) { transactionReceivedListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Removes the given {@link NewBestBlockListener} from the chain. */ public void removeNewBestBlockListener(NewBestBlockListener listener) { ListenerRegistration.removeFromList(listener, newBestBlockListeners); } /** * Removes the given {@link ReorganizeListener} from the chain. */ public void removeReorganizeListener(ReorganizeListener listener) { ListenerRegistration.removeFromList(listener, reorganizeListeners); } /** * Removes the given {@link TransactionReceivedInBlockListener} from the chain. */ public void removeTransactionReceivedListener(TransactionReceivedInBlockListener listener) { ListenerRegistration.removeFromList(listener, transactionReceivedListeners); } /** * Returns the {@link BlockStore} the chain was constructed with. You can use this to iterate over the chain. */ public BlockStore getBlockStore() { return blockStore; } /** * Adds/updates the given {@link Block} with the block store. * This version is used when the transactions have not been verified. * @param storedPrev The {@link StoredBlock} which immediately precedes block. * @param block The {@link Block} to add/update. * @return the newly created {@link StoredBlock} */ protected abstract StoredBlock addToBlockStore(StoredBlock storedPrev, Block block) throws BlockStoreException, VerificationException; /** * Adds/updates the given {@link StoredBlock} with the block store. * This version is used when the transactions have already been verified to properly spend txOutputChanges. * @param storedPrev The {@link StoredBlock} which immediately precedes block. * @param header The {@link StoredBlock} to add/update. * @param txOutputChanges The total sum of all changes made by this block to the set of open transaction outputs * (from a call to connectTransactions), if in fully verifying mode (null otherwise). * @return the newly created {@link StoredBlock} */ protected abstract StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, @Nullable TransactionOutputChanges txOutputChanges) throws BlockStoreException, VerificationException; /** * Rollback the block store to a given height. This is currently only supported by {@link BlockChain} instances. * * @throws BlockStoreException * if the operation fails or is unsupported. */ protected abstract void rollbackBlockStore(int height) throws BlockStoreException; /** * Called before setting chain head in memory. * Should write the new head to block store and then commit any database transactions * that were started by disconnectTransactions/connectTransactions. */ protected abstract void doSetChainHead(StoredBlock chainHead) throws BlockStoreException; /** * Called if we (possibly) previously called disconnectTransaction/connectTransactions, * but will not be calling preSetChainHead as a block failed verification. * Can be used to abort database transactions that were started by * disconnectTransactions/connectTransactions. */ protected abstract void notSettingChainHead() throws BlockStoreException; /** * For a standard BlockChain, this should return blockStore.get(hash), * for a FullPrunedBlockChain blockStore.getOnceUndoableStoredBlock(hash) */ protected abstract StoredBlock getStoredBlockInCurrentScope(Sha256Hash hash) throws BlockStoreException; /** * Processes a received block and tries to add it to the chain. If there's something wrong with the block an * exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false. * If the block can be connected to the chain, returns true. * Accessing block's transactions in another thread while this method runs may result in undefined behavior. */ public boolean add(Block block) throws VerificationException, PrunedException { try { return add(block, true, null, null); } catch (BlockStoreException e) { // TODO: Figure out a better way to propagate this exception to the user. throw new RuntimeException(e); } catch (VerificationException e) { try { notSettingChainHead(); } catch (BlockStoreException e1) { throw new RuntimeException(e1); } throw new VerificationException("Could not verify block:\n" + block.toString(), e); } } /** * Processes a received block and tries to add it to the chain. If there's something wrong with the block an * exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false. * If the block can be connected to the chain, returns true. */ public boolean add(FilteredBlock block) throws VerificationException, PrunedException { try { // The block has a list of hashes of transactions that matched the Bloom filter, and a list of associated // Transaction objects. There may be fewer Transaction objects than hashes, this is expected. It can happen // in the case where we were already around to witness the initial broadcast, so we downloaded the // transaction and sent it to the wallet before this point (the wallet may have thrown it away if it was // a false positive, as expected in any Bloom filtering scheme). The filteredTxn list here will usually // only be full of data when we are catching up to the head of the chain and thus haven't witnessed any // of the transactions. return add(block.getBlockHeader(), true, block.getTransactionHashes(), block.getAssociatedTransactions()); } catch (BlockStoreException e) { // TODO: Figure out a better way to propagate this exception to the user. throw new RuntimeException(e); } catch (VerificationException e) { try { notSettingChainHead(); } catch (BlockStoreException e1) { throw new RuntimeException(e1); } throw new VerificationException("Could not verify block " + block.getHash().toString() + "\n" + block.toString(), e); } } /** * Whether or not we are maintaining a set of unspent outputs and are verifying all transactions. * Also indicates that all calls to add() should provide a block containing transactions */ protected abstract boolean shouldVerifyTransactions(); /** * Connect each transaction in block.transactions, verifying them as we go and removing spent outputs * If an error is encountered in a transaction, no changes should be made to the underlying BlockStore. * and a VerificationException should be thrown. * Only called if(shouldVerifyTransactions()) * @throws VerificationException if an attempt was made to spend an already-spent output, or if a transaction incorrectly solved an output script. * @throws BlockStoreException if the block store had an underlying error. * @return The full set of all changes made to the set of open transaction outputs. */ protected abstract TransactionOutputChanges connectTransactions(int height, Block block) throws VerificationException, BlockStoreException; /** * Load newBlock from BlockStore and connect its transactions, returning changes to the set of unspent transactions. * If an error is encountered in a transaction, no changes should be made to the underlying BlockStore. * Only called if(shouldVerifyTransactions()) * @throws PrunedException if newBlock does not exist as a {@link StoredUndoableBlock} in the block store. * @throws VerificationException if an attempt was made to spend an already-spent output, or if a transaction incorrectly solved an output script. * @throws BlockStoreException if the block store had an underlying error or newBlock does not exist in the block store at all. * @return The full set of all changes made to the set of open transaction outputs. */ protected abstract TransactionOutputChanges connectTransactions(StoredBlock newBlock) throws VerificationException, BlockStoreException, PrunedException; // filteredTxHashList contains all transactions, filteredTxn just a subset private boolean add(Block block, boolean tryConnecting, @Nullable List<Sha256Hash> filteredTxHashList, @Nullable Map<Sha256Hash, Transaction> filteredTxn) throws BlockStoreException, VerificationException, PrunedException { // TODO: Use read/write locks to ensure that during chain download properties are still low latency. lock.lock(); try { // Quick check for duplicates to avoid an expensive check further down (in findSplit). This can happen a lot // when connecting orphan transactions due to the dumb brute force algorithm we use. if (block.equals(getChainHead().getHeader())) { return true; } if (tryConnecting && orphanBlocks.containsKey(block.getHash())) { return false; } // If we want to verify transactions (ie we are running with full blocks), verify that block has transactions if (shouldVerifyTransactions() && block.getTransactions() == null) throw new VerificationException("Got a block header while running in full-block mode"); // Check for already-seen block, but only for full pruned mode, where the DB is // more likely able to handle these queries quickly. if (shouldVerifyTransactions() && blockStore.get(block.getHash()) != null) { return true; } final StoredBlock storedPrev; final int height; final EnumSet<Block.VerifyFlag> flags; // Prove the block is internally valid: hash is lower than target, etc. This only checks the block contents // if there is a tx sending or receiving coins using an address in one of our wallets. And those transactions // are only lightly verified: presence in a valid connecting block is taken as proof of validity. See the // article here for more details: https://bitcoinj.github.io/security-model try { block.verifyHeader(); storedPrev = getStoredBlockInCurrentScope(block.getPrevBlockHash()); if (storedPrev != null) { height = storedPrev.getHeight() + 1; } else { height = Block.BLOCK_HEIGHT_UNKNOWN; } flags = params.getBlockVerificationFlags(block, versionTally, height); if (shouldVerifyTransactions()) block.verifyTransactions(height, flags); } catch (VerificationException e) { log.error("Failed to verify block: ", e); log.error(block.getHashAsString()); throw e; } // Try linking it to a place in the currently known blocks. if (storedPrev == null) { // We can't find the previous block. Probably we are still in the process of downloading the chain and a // block was solved whilst we were doing it. We put it to one side and try to connect it later when we // have more blocks. checkState(tryConnecting, "bug in tryConnectingOrphans"); log.warn("Block does not connect: {} prev {}", block.getHashAsString(), block.getPrevBlockHash()); orphanBlocks.put(block.getHash(), new OrphanBlock(block, filteredTxHashList, filteredTxn)); if (tryConnecting) tryConnectingOrphans(); return false; } else { checkState(lock.isHeldByCurrentThread()); // It connects to somewhere on the chain. Not necessarily the top of the best known chain. params.checkDifficultyTransitions(storedPrev, block, blockStore); connectBlock(block, storedPrev, shouldVerifyTransactions(), filteredTxHashList, filteredTxn); if (tryConnecting) tryConnectingOrphans(); return true; } } finally { lock.unlock(); } } /** * Returns the hashes of the currently stored orphan blocks and then deletes them from this objects storage. * Used by Peer when a filter exhaustion event has occurred and thus any orphan blocks that have been downloaded * might be inaccurate/incomplete. */ public Set<Sha256Hash> drainOrphanBlocks() { lock.lock(); try { Set<Sha256Hash> hashes = new HashSet<>(orphanBlocks.keySet()); orphanBlocks.clear(); return hashes; } finally { lock.unlock(); } } // expensiveChecks enables checks that require looking at blocks further back in the chain // than the previous one when connecting (eg median timestamp check) // It could be exposed, but for now we just set it to shouldVerifyTransactions() private void connectBlock(final Block block, StoredBlock storedPrev, boolean expensiveChecks, @Nullable final List<Sha256Hash> filteredTxHashList, @Nullable final Map<Sha256Hash, Transaction> filteredTxn) throws BlockStoreException, VerificationException, PrunedException { checkState(lock.isHeldByCurrentThread()); boolean filtered = filteredTxHashList != null && filteredTxn != null; // Check that we aren't connecting a block that fails a checkpoint check if (!params.passesCheckpoint(storedPrev.getHeight() + 1, block.getHash())) throw new VerificationException("Block failed checkpoint lockin at " + (storedPrev.getHeight() + 1)); if (shouldVerifyTransactions()) { for (Transaction tx : block.getTransactions()) if (!tx.isFinal(storedPrev.getHeight() + 1, block.getTimeSeconds())) throw new VerificationException("Block contains non-final transaction"); } StoredBlock head = getChainHead(); if (storedPrev.equals(head)) { if (filtered && filteredTxn.size() > 0) { log.debug("Block {} connects to top of best chain with {} transaction(s) of which we were sent {}", block.getHashAsString(), filteredTxHashList.size(), filteredTxn.size()); for (Sha256Hash hash : filteredTxHashList) log.debug(" matched tx {}", hash); } if (expensiveChecks && block.getTimeSeconds() <= getMedianTimestampOfRecentBlocks(head, blockStore)) throw new VerificationException("Block's timestamp is too early"); // BIP 66 & 65: Enforce block version 3/4 once they are a supermajority of blocks // NOTE: This requires 1,000 blocks since the last checkpoint (on main // net, less on test) in order to be applied. It is also limited to // stopping addition of new v2/3 blocks to the tip of the chain. if (block.getVersion() == Block.BLOCK_VERSION_BIP34 || block.getVersion() == Block.BLOCK_VERSION_BIP66) { final Integer count = versionTally.getCountAtOrAbove(block.getVersion() + 1); if (count != null && count >= params.getMajorityRejectBlockOutdated()) { throw new VerificationException.BlockVersionOutOfDate(block.getVersion()); } } // This block connects to the best known block, it is a normal continuation of the system. TransactionOutputChanges txOutChanges = null; if (shouldVerifyTransactions()) txOutChanges = connectTransactions(storedPrev.getHeight() + 1, block); StoredBlock newStoredBlock = addToBlockStore(storedPrev, block.getTransactions() == null ? block : block.cloneAsHeader(), txOutChanges); versionTally.add(block.getVersion()); setChainHead(newStoredBlock); if (log.isDebugEnabled()) log.debug("Chain is now {} blocks high, running listeners", newStoredBlock.getHeight()); informListenersForNewBlock(block, NewBlockType.BEST_CHAIN, filteredTxHashList, filteredTxn, newStoredBlock); } else { // This block connects to somewhere other than the top of the best known chain. We treat these differently. // // Note that we send the transactions to the wallet FIRST, even if we're about to re-organize this block // to become the new best chain head. This simplifies handling of the re-org in the Wallet class. StoredBlock newBlock = storedPrev.build(block); boolean haveNewBestChain = newBlock.moreWorkThan(head); if (haveNewBestChain) { log.info("Block is causing a re-organize"); } else { StoredBlock splitPoint = findSplit(newBlock, head, blockStore); if (splitPoint != null && splitPoint.equals(newBlock)) { // newStoredBlock is a part of the same chain, there's no fork. This happens when we receive a block // that we already saw and linked into the chain previously, which isn't the chain head. // Re-processing it is confusing for the wallet so just skip. log.warn("Saw duplicated block in best chain at height {}: {}", newBlock.getHeight(), newBlock.getHeader().getHash()); return; } if (splitPoint == null) { // This should absolutely never happen // (lets not write the full block to disk to keep any bugs which allow this to happen // from writing unreasonable amounts of data to disk) throw new VerificationException("Block forks the chain but splitPoint is null"); } else { // We aren't actually spending any transactions (yet) because we are on a fork addToBlockStore(storedPrev, block); int splitPointHeight = splitPoint.getHeight(); String splitPointHash = splitPoint.getHeader().getHashAsString(); log.info("Block forks the chain at height {}/block {}, but it did not cause a reorganize:\n{}", splitPointHeight, splitPointHash, newBlock.getHeader().getHashAsString()); } } // We may not have any transactions if we received only a header, which can happen during fast catchup. // If we do, send them to the wallet but state that they are on a side chain so it knows not to try and // spend them until they become activated. if (block.getTransactions() != null || filtered) { informListenersForNewBlock(block, NewBlockType.SIDE_CHAIN, filteredTxHashList, filteredTxn, newBlock); } if (haveNewBestChain) handleNewBestChain(storedPrev, newBlock, block, expensiveChecks); } } private void informListenersForNewBlock(final Block block, final NewBlockType newBlockType, @Nullable final List<Sha256Hash> filteredTxHashList, @Nullable final Map<Sha256Hash, Transaction> filteredTxn, final StoredBlock newStoredBlock) throws VerificationException { // Notify the listeners of the new block, so the depth and workDone of stored transactions can be updated // (in the case of the listener being a wallet). Wallets need to know how deep each transaction is so // coinbases aren't used before maturity. boolean first = true; Set<Sha256Hash> falsePositives = new HashSet<>(); if (filteredTxHashList != null) falsePositives.addAll(filteredTxHashList); for (final ListenerRegistration<TransactionReceivedInBlockListener> registration : transactionReceivedListeners) { if (registration.executor == Threading.SAME_THREAD) { informListenerForNewTransactions(block, newBlockType, filteredTxHashList, filteredTxn, newStoredBlock, first, registration.listener, falsePositives); } else { // Listener wants to be run on some other thread, so marshal it across here. final boolean notFirst = !first; registration.executor.execute(new Runnable() { @Override public void run() { try { // We can't do false-positive handling when executing on another thread Set<Sha256Hash> ignoredFalsePositives = new HashSet<>(); informListenerForNewTransactions(block, newBlockType, filteredTxHashList, filteredTxn, newStoredBlock, notFirst, registration.listener, ignoredFalsePositives); } catch (VerificationException e) { log.error("Block chain listener threw exception: ", e); // Don't attempt to relay this back to the original peer thread if this was an async // listener invocation. // TODO: Make exception reporting a global feature and use it here. } } }); } first = false; } for (final ListenerRegistration<NewBestBlockListener> registration : newBestBlockListeners) { if (registration.executor == Threading.SAME_THREAD) { if (newBlockType == NewBlockType.BEST_CHAIN) registration.listener.notifyNewBestBlock(newStoredBlock); } else { // Listener wants to be run on some other thread, so marshal it across here. registration.executor.execute(new Runnable() { @Override public void run() { try { if (newBlockType == NewBlockType.BEST_CHAIN) registration.listener.notifyNewBestBlock(newStoredBlock); } catch (VerificationException e) { log.error("Block chain listener threw exception: ", e); // Don't attempt to relay this back to the original peer thread if this was an async // listener invocation. // TODO: Make exception reporting a global feature and use it here. } } }); } first = false; } trackFalsePositives(falsePositives.size()); } private static void informListenerForNewTransactions(Block block, NewBlockType newBlockType, @Nullable List<Sha256Hash> filteredTxHashList, @Nullable Map<Sha256Hash, Transaction> filteredTxn, StoredBlock newStoredBlock, boolean first, TransactionReceivedInBlockListener listener, Set<Sha256Hash> falsePositives) throws VerificationException { if (block.getTransactions() != null) { // If this is not the first wallet, ask for the transactions to be duplicated before being given // to the wallet when relevant. This ensures that if we have two connected wallets and a tx that // is relevant to both of them, they don't end up accidentally sharing the same object (which can // result in temporary in-memory corruption during re-orgs). See bug 257. We only duplicate in // the case of multiple wallets to avoid an unnecessary efficiency hit in the common case. sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getTransactions(), !first, falsePositives); } else if (filteredTxHashList != null) { checkNotNull(filteredTxn); // We must send transactions to listeners in the order they appeared in the block - thus we iterate over the // set of hashes and call sendTransactionsToListener with individual txn when they have not already been // seen in loose broadcasts - otherwise notifyTransactionIsInBlock on the hash. int relativityOffset = 0; for (Sha256Hash hash : filteredTxHashList) { Transaction tx = filteredTxn.get(hash); if (tx != null) { sendTransactionsToListener(newStoredBlock, newBlockType, listener, relativityOffset, Collections.singletonList(tx), !first, falsePositives); } else { if (listener.notifyTransactionIsInBlock(hash, newStoredBlock, newBlockType, relativityOffset)) { falsePositives.remove(hash); } } relativityOffset++; } } } /** * Gets the median timestamp of the last 11 blocks */ private static long getMedianTimestampOfRecentBlocks(StoredBlock storedBlock, BlockStore store) throws BlockStoreException { long[] timestamps = new long[11]; int unused = 9; timestamps[10] = storedBlock.getHeader().getTimeSeconds(); while (unused >= 0 && (storedBlock = storedBlock.getPrev(store)) != null) timestamps[unused--] = storedBlock.getHeader().getTimeSeconds(); Arrays.sort(timestamps, unused+1, 11); return timestamps[unused + (11-unused)/2]; } /** * Disconnect each transaction in the block (after reading it from the block store) * Only called if(shouldVerifyTransactions()) * @throws PrunedException if block does not exist as a {@link StoredUndoableBlock} in the block store. * @throws BlockStoreException if the block store had an underlying error or block does not exist in the block store at all. */ protected abstract void disconnectTransactions(StoredBlock block) throws PrunedException, BlockStoreException; /** * Called as part of connecting a block when the new block results in a different chain having higher total work. * * if (shouldVerifyTransactions) * Either newChainHead needs to be in the block store as a FullStoredBlock, or (block != null && block.transactions != null) */ private void handleNewBestChain(StoredBlock storedPrev, StoredBlock newChainHead, Block block, boolean expensiveChecks) throws BlockStoreException, VerificationException, PrunedException { checkState(lock.isHeldByCurrentThread()); // This chain has overtaken the one we currently believe is best. Reorganize is required. // // Firstly, calculate the block at which the chain diverged. We only need to examine the // chain from beyond this block to find differences. StoredBlock head = getChainHead(); final StoredBlock splitPoint = findSplit(newChainHead, head, blockStore); log.info("Re-organize after split at height {}", splitPoint.getHeight()); log.info("Old chain head: {}", head.getHeader().getHashAsString()); log.info("New chain head: {}", newChainHead.getHeader().getHashAsString()); log.info("Split at block: {}", splitPoint.getHeader().getHashAsString()); // Then build a list of all blocks in the old part of the chain and the new part. final LinkedList<StoredBlock> oldBlocks = getPartialChain(head, splitPoint, blockStore); final LinkedList<StoredBlock> newBlocks = getPartialChain(newChainHead, splitPoint, blockStore); // Disconnect each transaction in the previous best chain that is no longer in the new best chain StoredBlock storedNewHead = splitPoint; if (shouldVerifyTransactions()) { for (StoredBlock oldBlock : oldBlocks) { try { disconnectTransactions(oldBlock); } catch (PrunedException e) { // We threw away the data we need to re-org this deep! We need to go back to a peer with full // block contents and ask them for the relevant data then rebuild the indexs. Or we could just // give up and ask the human operator to help get us unstuck (eg, rescan from the genesis block). // TODO: Retry adding this block when we get a block with hash e.getHash() throw e; } } StoredBlock cursor; // Walk in ascending chronological order. for (Iterator<StoredBlock> it = newBlocks.descendingIterator(); it.hasNext();) { cursor = it.next(); Block cursorBlock = cursor.getHeader(); if (expensiveChecks && cursorBlock.getTimeSeconds() <= getMedianTimestampOfRecentBlocks(cursor.getPrev(blockStore), blockStore)) throw new VerificationException("Block's timestamp is too early during reorg"); TransactionOutputChanges txOutChanges; if (cursor != newChainHead || block == null) txOutChanges = connectTransactions(cursor); else txOutChanges = connectTransactions(newChainHead.getHeight(), block); storedNewHead = addToBlockStore(storedNewHead, cursorBlock.cloneAsHeader(), txOutChanges); } } else { // (Finally) write block to block store storedNewHead = addToBlockStore(storedPrev, newChainHead.getHeader()); } // Now inform the listeners. This is necessary so the set of currently active transactions (that we can spend) // can be updated to take into account the re-organize. We might also have received new coins we didn't have // before and our previous spends might have been undone. for (final ListenerRegistration<ReorganizeListener> registration : reorganizeListeners) { if (registration.executor == Threading.SAME_THREAD) { // Short circuit the executor so we can propagate any exceptions. // TODO: Do we really need to do this or should it be irrelevant? registration.listener.reorganize(splitPoint, oldBlocks, newBlocks); } else { registration.executor.execute(new Runnable() { @Override public void run() { try { registration.listener.reorganize(splitPoint, oldBlocks, newBlocks); } catch (VerificationException e) { log.error("Block chain listener threw exception during reorg", e); } } }); } } // Update the pointer to the best known block. setChainHead(storedNewHead); } /** * Returns the set of contiguous blocks between 'higher' and 'lower'. Higher is included, lower is not. */ private static LinkedList<StoredBlock> getPartialChain(StoredBlock higher, StoredBlock lower, BlockStore store) throws BlockStoreException { checkArgument(higher.getHeight() > lower.getHeight(), "higher and lower are reversed"); LinkedList<StoredBlock> results = new LinkedList<>(); StoredBlock cursor = higher; while (true) { results.add(cursor); cursor = checkNotNull(cursor.getPrev(store), "Ran off the end of the chain"); if (cursor.equals(lower)) break; } return results; } /** * Locates the point in the chain at which newStoredBlock and chainHead diverge. Returns null if no split point was * found (ie they are not part of the same chain). Returns newChainHead or chainHead if they don't actually diverge * but are part of the same chain. */ private static StoredBlock findSplit(StoredBlock newChainHead, StoredBlock oldChainHead, BlockStore store) throws BlockStoreException { StoredBlock currentChainCursor = oldChainHead; StoredBlock newChainCursor = newChainHead; // Loop until we find the block both chains have in common. Example: // // A -> B -> C -> D // \--> E -> F -> G // // findSplit will return block B. oldChainHead = D and newChainHead = G. while (!currentChainCursor.equals(newChainCursor)) { if (currentChainCursor.getHeight() > newChainCursor.getHeight()) { currentChainCursor = currentChainCursor.getPrev(store); checkNotNull(currentChainCursor, "Attempt to follow an orphan chain"); } else { newChainCursor = newChainCursor.getPrev(store); checkNotNull(newChainCursor, "Attempt to follow an orphan chain"); } } return currentChainCursor; } /** * @return the height of the best known chain, convenience for {@code getChainHead().getHeight()}. */ public final int getBestChainHeight() { return getChainHead().getHeight(); } public enum NewBlockType { BEST_CHAIN, SIDE_CHAIN } private static void sendTransactionsToListener(StoredBlock block, NewBlockType blockType, TransactionReceivedInBlockListener listener, int relativityOffset, List<Transaction> transactions, boolean clone, Set<Sha256Hash> falsePositives) throws VerificationException { for (Transaction tx : transactions) { try { falsePositives.remove(tx.getTxId()); if (clone) tx = tx.params.getDefaultSerializer().makeTransaction(tx.bitcoinSerialize()); listener.receiveFromBlock(tx, block, blockType, relativityOffset++); } catch (ScriptException e) { // We don't want scripts we don't understand to break the block chain so just note that this tx was // not scanned here and continue. log.warn("Failed to parse a script: " + e.toString()); } catch (ProtocolException e) { // Failed to duplicate tx, should never happen. throw new RuntimeException(e); } } } protected void setChainHead(StoredBlock chainHead) throws BlockStoreException { doSetChainHead(chainHead); synchronized (chainHeadLock) { this.chainHead = chainHead; } } /** * For each block in orphanBlocks, see if we can now fit it on top of the chain and if so, do so. */ private void tryConnectingOrphans() throws VerificationException, BlockStoreException, PrunedException { checkState(lock.isHeldByCurrentThread()); // For each block in our orphan list, try and fit it onto the head of the chain. If we succeed remove it // from the list and keep going. If we changed the head of the list at the end of the round try again until // we can't fit anything else on the top. // // This algorithm is kind of crappy, we should do a topo-sort then just connect them in order, but for small // numbers of orphan blocks it does OK. int blocksConnectedThisRound; do { blocksConnectedThisRound = 0; Iterator<OrphanBlock> iter = orphanBlocks.values().iterator(); while (iter.hasNext()) { OrphanBlock orphanBlock = iter.next(); // Look up the blocks previous. StoredBlock prev = getStoredBlockInCurrentScope(orphanBlock.block.getPrevBlockHash()); if (prev == null) { // This is still an unconnected/orphan block. if (log.isDebugEnabled()) log.debug("Orphan block {} is not connectable right now", orphanBlock.block.getHash()); continue; } // Otherwise we can connect it now. // False here ensures we don't recurse infinitely downwards when connecting huge chains. log.info("Connected orphan {}", orphanBlock.block.getHash()); add(orphanBlock.block, false, orphanBlock.filteredTxHashes, orphanBlock.filteredTxn); iter.remove(); blocksConnectedThisRound++; } if (blocksConnectedThisRound > 0) { log.info("Connected {} orphan blocks.", blocksConnectedThisRound); } } while (blocksConnectedThisRound > 0); } /** * Returns the block at the head of the current best chain. This is the block which represents the greatest * amount of cumulative work done. */ public StoredBlock getChainHead() { synchronized (chainHeadLock) { return chainHead; } } /** * An orphan block is one that does not connect to the chain anywhere (ie we can't find its parent, therefore * it's an orphan). Typically this occurs when we are downloading the chain and didn't reach the head yet, and/or * if a block is solved whilst we are downloading. It's possible that we see a small amount of orphan blocks which * chain together, this method tries walking backwards through the known orphan blocks to find the bottom-most. * * @return from or one of froms parents, or null if "from" does not identify an orphan block */ @Nullable public Block getOrphanRoot(Sha256Hash from) { lock.lock(); try { OrphanBlock cursor = orphanBlocks.get(from); if (cursor == null) return null; OrphanBlock tmp; while ((tmp = orphanBlocks.get(cursor.block.getPrevBlockHash())) != null) { cursor = tmp; } return cursor.block; } finally { lock.unlock(); } } /** Returns true if the given block is currently in the orphan blocks list. */ public boolean isOrphan(Sha256Hash block) { lock.lock(); try { return orphanBlocks.containsKey(block); } finally { lock.unlock(); } } /** * Returns an estimate of when the given block will be reached, assuming a perfect 10 minute average for each * block. This is useful for turning transaction lock times into human readable times. Note that a height in * the past will still be estimated, even though the time of solving is actually known (we won't scan backwards * through the chain to obtain the right answer). */ public Date estimateBlockTime(int height) { synchronized (chainHeadLock) { long offset = height - chainHead.getHeight(); long headTime = chainHead.getHeader().getTimeSeconds(); long estimated = (headTime * 1000) + (1000L * 60L * 10L * offset); return new Date(estimated); } } /** * Returns a future that completes when the block chain has reached the given height. Yields the * {@link StoredBlock} of the block that reaches that height first. The future completes on a peer thread. */ public ListenableFuture<StoredBlock> getHeightFuture(final int height) { final SettableFuture<StoredBlock> result = SettableFuture.create(); addNewBestBlockListener(Threading.SAME_THREAD, new NewBestBlockListener() { @Override public void notifyNewBestBlock(StoredBlock block) throws VerificationException { if (block.getHeight() >= height) { removeNewBestBlockListener(this); result.set(block); } } }); return result; } /** * The false positive rate is the average over all blockchain transactions of: * * - 1.0 if the transaction was false-positive (was irrelevant to all listeners) * - 0.0 if the transaction was relevant or filtered out */ public double getFalsePositiveRate() { return falsePositiveRate; } /* * We completed handling of a filtered block. Update false-positive estimate based * on the total number of transactions in the original block. * * count includes filtered transactions, transactions that were passed in and were relevant * and transactions that were false positives (i.e. includes all transactions in the block). */ protected void trackFilteredTransactions(int count) { // Track non-false-positives in batch. Each non-false-positive counts as // 0.0 towards the estimate. // // This is slightly off because we are applying false positive tracking before non-FP tracking, // which counts FP as if they came at the beginning of the block. Assuming uniform FP // spread in a block, this will somewhat underestimate the FP rate (5% for 1000 tx block). double alphaDecay = Math.pow(1 - FP_ESTIMATOR_ALPHA, count); // new_rate = alpha_decay * new_rate falsePositiveRate = alphaDecay * falsePositiveRate; double betaDecay = Math.pow(1 - FP_ESTIMATOR_BETA, count); // trend = beta * (new_rate - old_rate) + beta_decay * trend falsePositiveTrend = FP_ESTIMATOR_BETA * count * (falsePositiveRate - previousFalsePositiveRate) + betaDecay * falsePositiveTrend; // new_rate += alpha_decay * trend falsePositiveRate += alphaDecay * falsePositiveTrend; // Stash new_rate in old_rate previousFalsePositiveRate = falsePositiveRate; } /* Irrelevant transactions were received. Update false-positive estimate. */ void trackFalsePositives(int count) { // Track false positives in batch by adding alpha to the false positive estimate once per count. // Each false positive counts as 1.0 towards the estimate. falsePositiveRate += FP_ESTIMATOR_ALPHA * count; if (count > 0 && log.isDebugEnabled()) log.debug("{} false positives, current rate = {} trend = {}", count, falsePositiveRate, falsePositiveTrend); } /** Resets estimates of false positives. Used when the filter is sent to the peer. */ public void resetFalsePositiveEstimate() { falsePositiveRate = 0; falsePositiveTrend = 0; previousFalsePositiveRate = 0; } protected VersionTally getVersionTally() { return versionTally; } }
AbstractBlockChain: Make a loop more readable.
core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java
AbstractBlockChain: Make a loop more readable.
<ide><path>ore/src/main/java/org/bitcoinj/core/AbstractBlockChain.java <ide> checkArgument(higher.getHeight() > lower.getHeight(), "higher and lower are reversed"); <ide> LinkedList<StoredBlock> results = new LinkedList<>(); <ide> StoredBlock cursor = higher; <del> while (true) { <add> do { <ide> results.add(cursor); <ide> cursor = checkNotNull(cursor.getPrev(store), "Ran off the end of the chain"); <del> if (cursor.equals(lower)) break; <del> } <add> } while (!cursor.equals(lower)); <ide> return results; <ide> } <ide>
Java
mit
e2fc720845da6261a53525cd9f3318f2ed62ec68
0
yeokm1/craft-support-email-intent
package com.yeokhengmeng.craftsupportemailintent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.FeatureInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.util.Log; import com.yeokhengmeng.craftsupportemailintent.GetInfoSummary.ExecShell.SHELL_CMD; public class GetInfoSummary extends GetInfoAbstract { public GetInfoSummary(Context context) { super(context); } public String getBoard(){ return android.os.Build.BOARD; } @TargetApi(Build.VERSION_CODES.FROYO) public String getBootloader(){ if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ return android.os.Build.BOOTLOADER; } else { return UNKNOWN; } } public String getBrand(){ return android.os.Build.BRAND; } public String getCPU_ABI(){ return android.os.Build.CPU_ABI; } @TargetApi(Build.VERSION_CODES.FROYO) public String getCPU_ABI2(){ if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ return android.os.Build.CPU_ABI2; } else { return UNKNOWN; } } public String getDevice(){ return android.os.Build.DEVICE; } public String getFingerprint(){ return android.os.Build.FINGERPRINT; } public String getDisplay(){ return android.os.Build.DISPLAY; } public String getBuildTime(){ long date = android.os.Build.TIME; Date dateFormat = new Date(date); return dateFormat.toString(); } @TargetApi(Build.VERSION_CODES.FROYO) public String getHardware(){ if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ return android.os.Build.HARDWARE; } else { return UNKNOWN; } } public String getHost(){ return android.os.Build.HOST; } public String getID(){ return android.os.Build.ID; } public String getManufacturer(){ return android.os.Build.MANUFACTURER; } public String getModel(){ return android.os.Build.MODEL; } public String getProduct(){ return android.os.Build.PRODUCT; } //May return null @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public String getRadio(){ String radio; if(getVersion() >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){ radio = android.os.Build.getRadioVersion(); } else if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ radio = android.os.Build.RADIO; } else { radio = UNKNOWN; } if(radio == null){ return UNKNOWN; } else { return radio; } } public String getTags(){ return android.os.Build.TAGS; } public String getType(){ return android.os.Build.TYPE; } public String getVersionCodename(){ return android.os.Build.VERSION.CODENAME; } public String getVersionIncremental(){ return android.os.Build.VERSION.INCREMENTAL; } public String getVersionRelease(){ return android.os.Build.VERSION.RELEASE; } public FeatureInfo[] getFeatureArray(){ return context.getPackageManager().getSystemAvailableFeatures(); } public String getAvailableFeatures(){ FeatureInfo[] features = getFeatureArray(); String featureString = "\n"; for(FeatureInfo feature : features){ featureString += feature.name + "\n"; } return featureString; } public boolean isPlayStoreInstalled() { String[] packageNames = {"com.google.market","com.google.vending" , "com.android.vending" }; PackageManager packageManager = context.getPackageManager(); List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES); for (PackageInfo packageInfo : packages) { String currentPackageName = packageInfo.packageName; for(String gNames : packageNames){ if(currentPackageName.equals(gNames)){ return true; } } } return false; } @SuppressWarnings("unused") public boolean isGoogleMapsInstalled(){ try { ApplicationInfo info = context.getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0 ); return true; } catch(PackageManager.NameNotFoundException e) { return false; } } public boolean isDeviceRooted() { return checkRootMethod1() || checkRootMethod2() || checkRootMethod3(); } private boolean checkRootMethod1() { String buildTags = android.os.Build.TAGS; return buildTags != null && buildTags.contains("test-keys"); } private boolean checkRootMethod2() { try { File file = new File("/system/app/Superuser.apk"); return file.exists(); } catch (Exception e) { return false; } } private boolean checkRootMethod3() { return new ExecShell().executeCommand(SHELL_CMD.check_su_binary)!=null; } /** @author Kevin Kowalewski */ public static class ExecShell { private static String LOG_TAG = ExecShell.class.getName(); public static enum SHELL_CMD { check_su_binary(new String[] { "/system/xbin/which", "su" }); String[] command; SHELL_CMD(String[] command) { this.command = command; } } public ArrayList<String> executeCommand(SHELL_CMD shellCmd) { String line = null; ArrayList<String> fullResponse = new ArrayList<String>(); Process localProcess = null; try { localProcess = Runtime.getRuntime().exec(shellCmd.command); } catch (Exception e) { return null; } new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader( localProcess.getInputStream())); try { while ((line = in.readLine()) != null) { Log.d(LOG_TAG, "--> Line received: " + line); fullResponse.add(line); } } catch (Exception e) { e.printStackTrace(); } Log.d(LOG_TAG, "--> Full response was: " + fullResponse); return fullResponse; } } public String getKernelVersion(){ String kernelVersion = System.getProperty("os.version"); if(kernelVersion == null){ return UNKNOWN; } else { return kernelVersion; } } @Override public String getBasicDetailsOnly() { String phoneDetails = "<<Phone Summary>>\n"; ArrayList<String> details = new ArrayList<String>(); details.add("Manufacturer: " + getManufacturer()); details.add("Model: " + getModel()); details.add("Product: " + getProduct()); details.add("Android Version: " + getVersion()); details.add("Version Release: " + getVersionRelease()); details.add("Build Display: " + getDisplay()); details.add("Build Time: " + getBuildTime()); details.add("Kernel Version: " + getKernelVersion()); details.add("Play Store Installed: " + isPlayStoreInstalled()); details.add("Google Maps Installed: " + isGoogleMapsInstalled()); details.add("Rooted: " + isDeviceRooted()); for(String detail : details){ phoneDetails += detail + "\n"; } return phoneDetails; } @Override public String getAllDetails() { String phoneDetails = getBasicDetailsOnly(); ArrayList<String> details = new ArrayList<String>(); details.add("Board: " + getBoard()); details.add("Bootloader: " + getBootloader()); details.add("CPU_ABI: " + getCPU_ABI()); details.add("CPU_ABI2: " + getCPU_ABI2()); details.add("Device: " + getDevice()); details.add("Fingerprint: " + getFingerprint()); details.add("Hardware: " + getHardware()); details.add("Host: " + getHost()); details.add("ID: " + getID()); details.add("Radio (Baseband): " + getRadio()); details.add("Tags: " + getTags()); details.add("Type: " + getType()); details.add("Version Codename: " + getVersionCodename()); details.add("Version Incremental: " + getVersionIncremental()); details.add("Features: " + getAvailableFeatures()); for(String detail : details){ phoneDetails += detail + "\n"; } return phoneDetails; } }
craft-support-email-intent/src/com/yeokhengmeng/craftsupportemailintent/GetInfoSummary.java
package com.yeokhengmeng.craftsupportemailintent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.FeatureInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.util.Log; import com.yeokhengmeng.craftsupportemailintent.GetInfoSummary.ExecShell.SHELL_CMD; public class GetInfoSummary extends GetInfoAbstract { public GetInfoSummary(Context context) { super(context); } public String getBoard(){ return android.os.Build.BOARD; } @TargetApi(Build.VERSION_CODES.FROYO) public String getBootloader(){ if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ return android.os.Build.BOOTLOADER; } else { return UNKNOWN; } } public String getBrand(){ return android.os.Build.BRAND; } public String getCPU_ABI(){ return android.os.Build.CPU_ABI; } @TargetApi(Build.VERSION_CODES.FROYO) public String getCPU_ABI2(){ if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ return android.os.Build.CPU_ABI2; } else { return UNKNOWN; } } public String getDevice(){ return android.os.Build.DEVICE; } public String getFingerprint(){ return android.os.Build.FINGERPRINT; } @TargetApi(Build.VERSION_CODES.FROYO) public String getHardware(){ if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ return android.os.Build.HARDWARE; } else { return UNKNOWN; } } public String getHost(){ return android.os.Build.HOST; } public String getID(){ return android.os.Build.ID; } public String getManufacturer(){ return android.os.Build.MANUFACTURER; } public String getModel(){ return android.os.Build.MODEL; } public String getProduct(){ return android.os.Build.PRODUCT; } //May return null @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public String getRadio(){ String radio; if(getVersion() >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH){ radio = android.os.Build.getRadioVersion(); } else if(getVersion() >= android.os.Build.VERSION_CODES.FROYO){ radio = android.os.Build.RADIO; } else { radio = UNKNOWN; } if(radio == null){ return UNKNOWN; } else { return radio; } } public String getTags(){ return android.os.Build.TAGS; } public String getType(){ return android.os.Build.TYPE; } public String getVersionCodename(){ return android.os.Build.VERSION.CODENAME; } public String getVersionIncremental(){ return android.os.Build.VERSION.INCREMENTAL; } public String getVersionRelease(){ return android.os.Build.VERSION.RELEASE; } public FeatureInfo[] getFeatureArray(){ return context.getPackageManager().getSystemAvailableFeatures(); } public String getAvailableFeatures(){ FeatureInfo[] features = getFeatureArray(); String featureString = "\n"; for(FeatureInfo feature : features){ featureString += feature.name + "\n"; } return featureString; } public boolean isPlayStoreInstalled() { String[] packageNames = {"com.google.market","com.google.vending" , "com.android.vending" }; PackageManager packageManager = context.getPackageManager(); List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES); for (PackageInfo packageInfo : packages) { String currentPackageName = packageInfo.packageName; for(String gNames : packageNames){ if(currentPackageName.equals(gNames)){ return true; } } } return false; } @SuppressWarnings("unused") public boolean isGoogleMapsInstalled(){ try { ApplicationInfo info = context.getPackageManager().getApplicationInfo("com.google.android.apps.maps", 0 ); return true; } catch(PackageManager.NameNotFoundException e) { return false; } } public boolean isDeviceRooted() { return checkRootMethod1() || checkRootMethod2() || checkRootMethod3(); } private boolean checkRootMethod1() { String buildTags = android.os.Build.TAGS; return buildTags != null && buildTags.contains("test-keys"); } private boolean checkRootMethod2() { try { File file = new File("/system/app/Superuser.apk"); return file.exists(); } catch (Exception e) { return false; } } private boolean checkRootMethod3() { return new ExecShell().executeCommand(SHELL_CMD.check_su_binary)!=null; } /** @author Kevin Kowalewski */ public static class ExecShell { private static String LOG_TAG = ExecShell.class.getName(); public static enum SHELL_CMD { check_su_binary(new String[] { "/system/xbin/which", "su" }); String[] command; SHELL_CMD(String[] command) { this.command = command; } } public ArrayList<String> executeCommand(SHELL_CMD shellCmd) { String line = null; ArrayList<String> fullResponse = new ArrayList<String>(); Process localProcess = null; try { localProcess = Runtime.getRuntime().exec(shellCmd.command); } catch (Exception e) { return null; } new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader( localProcess.getInputStream())); try { while ((line = in.readLine()) != null) { Log.d(LOG_TAG, "--> Line received: " + line); fullResponse.add(line); } } catch (Exception e) { e.printStackTrace(); } Log.d(LOG_TAG, "--> Full response was: " + fullResponse); return fullResponse; } } @Override public String getBasicDetailsOnly() { String phoneDetails = "<<Phone Summary>>\n"; ArrayList<String> details = new ArrayList<String>(); details.add("Manufacturer: " + getManufacturer()); details.add("Model: " + getModel()); details.add("Product: " + getProduct()); details.add("Android Version: " + getVersion()); details.add("Version Release: " + getVersionRelease()); details.add("Play Store Installed: " + isPlayStoreInstalled()); details.add("Google Maps Installed: " + isGoogleMapsInstalled()); details.add("Rooted: " + isDeviceRooted()); for(String detail : details){ phoneDetails += detail + "\n"; } return phoneDetails; } @Override public String getAllDetails() { String phoneDetails = getBasicDetailsOnly(); ArrayList<String> details = new ArrayList<String>(); details.add("Board: " + getBoard()); details.add("Bootloader: " + getBootloader()); details.add("CPU_ABI: " + getCPU_ABI()); details.add("CPU_ABI2: " + getCPU_ABI2()); details.add("Device: " + getDevice()); details.add("Fingerprint: " + getFingerprint()); details.add("Hardware: " + getHardware()); details.add("Host: " + getHost()); details.add("ID: " + getID()); details.add("Radio: " + getRadio()); details.add("Tags: " + getTags()); details.add("Type: " + getType()); details.add("Version Codename: " + getVersionCodename()); details.add("Version Incremental: " + getVersionIncremental()); details.add("Features: " + getAvailableFeatures()); for(String detail : details){ phoneDetails += detail + "\n"; } return phoneDetails; } }
More information obtained
craft-support-email-intent/src/com/yeokhengmeng/craftsupportemailintent/GetInfoSummary.java
More information obtained
<ide><path>raft-support-email-intent/src/com/yeokhengmeng/craftsupportemailintent/GetInfoSummary.java <ide> import java.io.InputStreamReader; <ide> import java.io.OutputStreamWriter; <ide> import java.util.ArrayList; <add>import java.util.Date; <ide> import java.util.List; <ide> <ide> import android.annotation.TargetApi; <ide> <ide> public String getFingerprint(){ <ide> return android.os.Build.FINGERPRINT; <add> } <add> <add> public String getDisplay(){ <add> return android.os.Build.DISPLAY; <add> } <add> <add> public String getBuildTime(){ <add> long date = android.os.Build.TIME; <add> Date dateFormat = new Date(date); <add> return dateFormat.toString(); <ide> } <ide> <ide> @TargetApi(Build.VERSION_CODES.FROYO) <ide> return fullResponse; <ide> } <ide> } <add> <add> public String getKernelVersion(){ <add> String kernelVersion = System.getProperty("os.version"); <add> if(kernelVersion == null){ <add> return UNKNOWN; <add> } else { <add> return kernelVersion; <add> } <add> } <ide> <ide> <ide> @Override <ide> details.add("Product: " + getProduct()); <ide> details.add("Android Version: " + getVersion()); <ide> details.add("Version Release: " + getVersionRelease()); <add> details.add("Build Display: " + getDisplay()); <add> details.add("Build Time: " + getBuildTime()); <add> details.add("Kernel Version: " + getKernelVersion()); <ide> details.add("Play Store Installed: " + isPlayStoreInstalled()); <ide> details.add("Google Maps Installed: " + isGoogleMapsInstalled()); <ide> details.add("Rooted: " + isDeviceRooted()); <ide> details.add("Hardware: " + getHardware()); <ide> details.add("Host: " + getHost()); <ide> details.add("ID: " + getID()); <del> details.add("Radio: " + getRadio()); <add> details.add("Radio (Baseband): " + getRadio()); <ide> details.add("Tags: " + getTags()); <ide> details.add("Type: " + getType()); <ide> details.add("Version Codename: " + getVersionCodename());
Java
apache-2.0
eafe56aeff8d795db291421675ba4cbd080b98a6
0
martin-stone/hsv-alpha-color-picker-android,martin-stone/hsv-alpha-color-picker-android
/* * Copyright (C) 2015 Martin Stone * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rarepebble.colorpicker; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Bundle; import android.preference.DialogPreference; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; public class ColorPreference extends DialogPreference { private final String selectNoneButtonText; private Integer defaultColor; private final String noneSelectedSummaryText; private final CharSequence summaryText; private final boolean showAlpha; private final boolean showHex; private final boolean showPreview; private View thumbnail; public ColorPreference(Context context) { this(context, null); } public ColorPreference(Context context, AttributeSet attrs) { super(context, attrs); summaryText = super.getSummary(); if (attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ColorPicker, 0, 0); selectNoneButtonText = a.getString(R.styleable.ColorPicker_colorpicker_selectNoneButtonText); noneSelectedSummaryText = a.getString(R.styleable.ColorPicker_colorpicker_noneSelectedSummaryText); showAlpha = a.getBoolean(R.styleable.ColorPicker_colorpicker_showAlpha, true); showHex = a.getBoolean(R.styleable.ColorPicker_colorpicker_showHex, true); showPreview = a.getBoolean(R.styleable.ColorPicker_colorpicker_showPreview, true); } else { selectNoneButtonText = null; noneSelectedSummaryText = null; showAlpha = true; showHex = true; showPreview = true; } } @Override protected void onBindView(View view) { thumbnail = addThumbnail(view); showColor(getPersistedIntDefaultOrNull()); // Only call after showColor sets any summary text: super.onBindView(view); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { if (a.peekValue(index) != null && a.peekValue(index).type == TypedValue.TYPE_STRING) { defaultColor = Color.parseColor(standardiseColorDigits(a.getString(index))); } else { defaultColor = a.getColor(index, Color.GRAY); } return defaultColor; } private static String standardiseColorDigits(String s) { if (s.charAt(0) == '#' && s.length() <= "#argb".length()) { // Convert #[a]rgb to #[aa]rrggbb String ss = "#"; for (int i = 1; i < s.length(); ++i) { ss += s.charAt(i); ss += s.charAt(i); } return ss; } else { return s; } } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { setColor(restorePersistedValue ? getColor() : defaultColor); } private View addThumbnail(View view) { LinearLayout widgetFrameView = ((LinearLayout)view.findViewById(android.R.id.widget_frame)); widgetFrameView.setVisibility(View.VISIBLE); widgetFrameView.removeAllViews(); LayoutInflater.from(getContext()).inflate( isEnabled() ? R.layout.color_preference_thumbnail : R.layout.color_preference_thumbnail_disabled, widgetFrameView); return widgetFrameView.findViewById(R.id.thumbnail); } private Integer getPersistedIntDefaultOrNull() { return getSharedPreferences().contains(getKey()) ? Integer.valueOf(getPersistedInt(Color.GRAY)) : defaultColor; } private void showColor(Integer color) { Integer thumbColor = color == null ? defaultColor : color; if (thumbnail != null) { thumbnail.setVisibility(thumbColor == null ? View.GONE : View.VISIBLE); thumbnail.findViewById(R.id.colorPreview).setBackgroundColor(thumbColor == null ? 0 : thumbColor); } if (noneSelectedSummaryText != null) { setSummary(thumbColor == null ? noneSelectedSummaryText : summaryText); } } @Override protected void onPrepareDialogBuilder(AlertDialog.Builder builder) { super.onPrepareDialogBuilder(builder); final ColorPickerView picker = new ColorPickerView(getContext()); picker.setColor(getPersistedInt(defaultColor == null ? Color.GRAY : defaultColor)); picker.showAlpha(showAlpha); picker.showHex(showHex); picker.showPreview(showPreview); builder .setTitle(null) .setView(picker) .setPositiveButton(getPositiveButtonText(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final int color = picker.getColor(); if (callChangeListener(color)) { setColor(color); } } }); if (selectNoneButtonText != null) { builder.setNeutralButton(selectNoneButtonText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callChangeListener(null)) { setColor(null); } } }); } } @Override protected void showDialog(Bundle state) { super.showDialog(state); // Nexus 7 needs the keyboard hiding explicitly. // A flag on the activity in the manifest doesn't // apply to the dialog, so needs to be in code: Window window = getDialog().getWindow(); window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); } private void removeSetting() { if (shouldPersist()) { getSharedPreferences() .edit() .remove(getKey()) .commit(); } } public void setColor(Integer color) { if (color == null) { removeSetting(); } else { persistInt(color); } showColor(color); } public Integer getColor() { return getPersistedIntDefaultOrNull(); } }
colorpicker/src/main/java/com/rarepebble/colorpicker/ColorPreference.java
/* * Copyright (C) 2015 Martin Stone * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rarepebble.colorpicker; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.graphics.Color; import android.os.Bundle; import android.preference.DialogPreference; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; public class ColorPreference extends DialogPreference { private final String selectNoneButtonText; private Integer defaultColor; private final String noneSelectedSummaryText; private final CharSequence summaryText; private final boolean showAlpha; private final boolean showHex; private final boolean showPreview; private View thumbnail; public ColorPreference(Context context) { this(context, null); } public ColorPreference(Context context, AttributeSet attrs) { super(context, attrs); summaryText = super.getSummary(); if (attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ColorPicker, 0, 0); selectNoneButtonText = a.getString(R.styleable.ColorPicker_colorpicker_selectNoneButtonText); noneSelectedSummaryText = a.getString(R.styleable.ColorPicker_colorpicker_noneSelectedSummaryText); showAlpha = a.getBoolean(R.styleable.ColorPicker_colorpicker_showAlpha, true); showHex = a.getBoolean(R.styleable.ColorPicker_colorpicker_showHex, true); showPreview = a.getBoolean(R.styleable.ColorPicker_colorpicker_showPreview, true); } else { selectNoneButtonText = null; noneSelectedSummaryText = null; showAlpha = true; showHex = true; showPreview = true; } } @Override protected void onBindView(View view) { thumbnail = addThumbnail(view); showColor(getPersistedIntDefaultOrNull()); // Only call after showColor sets any summary text: super.onBindView(view); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { if (a.peekValue(index) != null && a.peekValue(index).type == TypedValue.TYPE_STRING) { defaultColor = Color.parseColor(standardiseColorDigits(a.getString(index))); } else { defaultColor = a.getColor(index, Color.GRAY); } return defaultColor; } private static String standardiseColorDigits(String s) { if (s.charAt(0) == '#' && s.length() <= "#argb".length()) { // Convert #[a]rgb to #[aa]rrggbb String ss = "#"; for (int i = 1; i < s.length(); ++i) { ss += s.charAt(i); ss += s.charAt(i); } return ss; } else { return s; } } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { setColor(restorePersistedValue ? getColor() : defaultColor); } private View addThumbnail(View view) { LinearLayout widgetFrameView = ((LinearLayout)view.findViewById(android.R.id.widget_frame)); widgetFrameView.setVisibility(View.VISIBLE); widgetFrameView.removeAllViews(); LayoutInflater.from(getContext()).inflate( isEnabled() ? R.layout.color_preference_thumbnail : R.layout.color_preference_thumbnail_disabled, widgetFrameView); return widgetFrameView.findViewById(R.id.thumbnail); } private Integer getPersistedIntDefaultOrNull() { return getSharedPreferences().contains(getKey()) ? Integer.valueOf(getPersistedInt(Color.GRAY)) : defaultColor; } private void showColor(Integer color) { Integer thumbColor = color == null ? defaultColor : color; if (thumbnail != null) { thumbnail.setVisibility(thumbColor == null ? View.GONE : View.VISIBLE); thumbnail.findViewById(R.id.colorPreview).setBackgroundColor(thumbColor == null ? 0 : thumbColor); } if (noneSelectedSummaryText != null) { setSummary(thumbColor == null ? noneSelectedSummaryText : summaryText); } } @Override protected void onPrepareDialogBuilder(AlertDialog.Builder builder) { super.onPrepareDialogBuilder(builder); final ColorPickerView picker = new ColorPickerView(getContext()); picker.setColor(getPersistedInt(defaultColor == null ? Color.GRAY : defaultColor)); picker.showAlpha(showAlpha); picker.showHex(showHex); builder .setTitle(null) .setView(picker) .setPositiveButton(getPositiveButtonText(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final int color = picker.getColor(); if (callChangeListener(color)) { setColor(color); } } }); if (selectNoneButtonText != null) { builder.setNeutralButton(selectNoneButtonText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callChangeListener(null)) { setColor(null); } } }); } } @Override protected void showDialog(Bundle state) { super.showDialog(state); // Nexus 7 needs the keyboard hiding explicitly. // A flag on the activity in the manifest doesn't // apply to the dialog, so needs to be in code: Window window = getDialog().getWindow(); window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); } private void removeSetting() { if (shouldPersist()) { getSharedPreferences() .edit() .remove(getKey()) .commit(); } } public void setColor(Integer color) { if (color == null) { removeSetting(); } else { persistInt(color); } showColor(color); } public Integer getColor() { return getPersistedIntDefaultOrNull(); } }
Fix implementation for hiding the color preview in ColorPreference.
colorpicker/src/main/java/com/rarepebble/colorpicker/ColorPreference.java
Fix implementation for hiding the color preview in ColorPreference.
<ide><path>olorpicker/src/main/java/com/rarepebble/colorpicker/ColorPreference.java <ide> picker.setColor(getPersistedInt(defaultColor == null ? Color.GRAY : defaultColor)); <ide> picker.showAlpha(showAlpha); <ide> picker.showHex(showHex); <add> picker.showPreview(showPreview); <ide> builder <ide> .setTitle(null) <ide> .setView(picker)
Java
agpl-3.0
c6b955d821bd9fdb00c3473e55eada98ea5580dc
0
retest/recheck,retest/recheck
package de.retest.recheck.ignore; import static de.retest.recheck.configuration.ProjectConfiguration.FILTER_FOLDER; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import de.retest.recheck.configuration.ProjectConfiguration; import lombok.extern.slf4j.Slf4j; @Slf4j public class SearchFilterFiles { public static final String FILTER_EXTENSION = ".filter"; private static final String BASIC_FILTER_DIR = "/filter/"; private static final String WEB_FILTER_DIR = BASIC_FILTER_DIR + "web/"; private static final List<String> defaultWebFilter = Arrays.asList( WEB_FILTER_DIR + "positioning.filter", WEB_FILTER_DIR + "style-attributes.filter", WEB_FILTER_DIR + "invisible-attributes.filter" ); private SearchFilterFiles() {} /** * @return The default filter files from the JAR. */ public static List<Pair<String, FilterLoader>> getDefaultFilterFiles() { return defaultWebFilter.stream() // .map( SearchFilterFiles.class::getResource ) // .filter( Objects::nonNull ) // .map( URL::toExternalForm ) // .map( URI::create ) // .map( SearchFilterFiles::loadFilterFromUri ) // .filter( Objects::nonNull ) // .collect( Collectors.toList() ); } private static Pair<String, FilterLoader> loadFilterFromUri( final URI uri ) { try { final Path path = Paths.get( uri ); return Pair.of( getFileName( path ), FilterLoader.load( path ) ); } catch ( final FileSystemNotFoundException e ) { return createFileSystemAndLoadFilter( uri ); } } private static Pair<String, FilterLoader> createFileSystemAndLoadFilter( final URI uri ) { try ( final FileSystem fs = FileSystems.newFileSystem( uri, Collections.emptyMap() ) ) { final Path path = fs.provider().getPath( uri ); return Pair.of( getFileName( path ), FilterLoader.provide( path ) ); } catch ( final IOException e ) { log.error( "Could not load Filter at '{}'", uri, e ); return null; } } /** * @return The project filter files from the filter folder. */ public static List<Pair<String, FilterLoader>> getProjectFilterFiles() { return ProjectConfiguration.getInstance().getProjectConfigFolder() // .map( path -> path.resolve( FILTER_FOLDER ) ) // .map( SearchFilterFiles::loadFiltersFromDirectory ) // .orElse( Collections.emptyList() ); } private static List<Pair<String, FilterLoader>> loadFiltersFromDirectory( final Path directory ) { try ( final Stream<Path> paths = Files.walk( directory ) ) { return paths.filter( Files::isRegularFile ) // .filter( file -> file.toString().endsWith( FILTER_EXTENSION ) ) // .map( path -> Pair.of( getFileName( path ), FilterLoader.load( path ) ) ) // .collect( Collectors.toList() ); // } catch ( final NoSuchFileException e ) { log.warn( "No filter folder found at '{}': {}", directory, e.getMessage() ); } catch ( final IOException e ) { log.error( "Exception accessing project filter folder '{}'.", directory, e ); } return Collections.emptyList(); } /** * @return Mapping from file names to filter. In the case of duplicates, project filters are preferred. */ public static Map<String, Filter> toFileNameFilterMapping() { final List<Pair<String, FilterLoader>> projectFilterFiles = getProjectFilterFiles(); final List<Pair<String, FilterLoader>> defaultFilterFiles = getDefaultFilterFiles(); return Stream.concat( projectFilterFiles.stream(), defaultFilterFiles.stream() ) // .collect( Collectors.toMap( // Use the file name as key. Pair::getLeft, // Use the loaded filter as value. pair -> { final FilterLoader loader = pair.getRight(); try { return loader.load(); } catch ( final IOException e ) { log.error( "Could not load Filter for '{}'.", pair.getLeft(), e ); return Filter.FILTER_NOTHING; } }, // Prefer project over default filters (due to concat order). ( projectFilter, defaultFilter ) -> projectFilter ) ); } private static String getFileName( final Path path ) { return path.getFileName().toString(); } }
src/main/java/de/retest/recheck/ignore/SearchFilterFiles.java
package de.retest.recheck.ignore; import static de.retest.recheck.configuration.ProjectConfiguration.FILTER_FOLDER; import java.io.IOException; import java.net.URI; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystemNotFoundException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.tuple.Pair; import de.retest.recheck.configuration.ProjectConfiguration; import lombok.extern.slf4j.Slf4j; @Slf4j public class SearchFilterFiles { public static final String FILTER_EXTENSION = ".filter"; private static final String BASIC_FILTER_DIR = "/filter/"; private static final String WEB_FILTER_DIR = BASIC_FILTER_DIR + "web/"; private static final List<String> defaultWebFilter = Arrays.asList( WEB_FILTER_DIR + "positioning.filter", WEB_FILTER_DIR + "style-attributes.filter", WEB_FILTER_DIR + "invisible-attributes.filter" ); private SearchFilterFiles() {} /** * @return The default filter files from the JAR. */ public static List<Pair<String, FilterLoader>> getDefaultFilterFiles() { return defaultWebFilter.stream() // .map( SearchFilterFiles.class::getResource ) // .filter( Objects::nonNull ) // .map( URL::toExternalForm ) // .map( URI::create ) // .map( SearchFilterFiles::loadFilterFromUri ) // .filter( Objects::nonNull ) // .collect( Collectors.toList() ); } private static Pair<String, FilterLoader> loadFilterFromUri( final URI uri ) { try { final Path path = Paths.get( uri ); return Pair.of( getFileName( path ), FilterLoader.load( path ) ); } catch ( final FileSystemNotFoundException e ) { return createFileSystemAndLoadFilter( uri ); } } private static Pair<String, FilterLoader> createFileSystemAndLoadFilter( final URI uri ) { try ( final FileSystem fs = FileSystems.newFileSystem( uri, Collections.emptyMap() ) ) { final Path path = fs.provider().getPath( uri ); return Pair.of( getFileName( path ), FilterLoader.provide( path ) ); } catch ( final IOException e ) { log.error( "Could not load Filter at '{}'", uri, e ); return null; } } /** * @return The project filter files from the filter folder. */ public static List<Pair<String, FilterLoader>> getProjectFilterFiles() { return ProjectConfiguration.getInstance().getProjectConfigFolder() // .map( path -> path.resolve( FILTER_FOLDER ) ) // .map( SearchFilterFiles::loadFiltersFromDirectory ) // .orElse( Collections.emptyList() ); } private static List<Pair<String, FilterLoader>> loadFiltersFromDirectory( final Path directory ) { try ( final Stream<Path> paths = Files.walk( directory ) ) { return paths.filter( Files::isRegularFile ) // .filter( file -> file.toString().endsWith( FILTER_EXTENSION ) ) // .map( path -> Pair.of( getFileName( path ), FilterLoader.load( path ) ) ) // .collect( Collectors.toList() ); // } catch ( final IOException e ) { log.error( "Exception accessing project filter folder '{}'.", directory, e ); return Collections.emptyList(); } } /** * @return Mapping from file names to filter. In the case of duplicates, project filters are preferred. */ public static Map<String, Filter> toFileNameFilterMapping() { final List<Pair<String, FilterLoader>> projectFilterFiles = getProjectFilterFiles(); final List<Pair<String, FilterLoader>> defaultFilterFiles = getDefaultFilterFiles(); return Stream.concat( projectFilterFiles.stream(), defaultFilterFiles.stream() ) // .collect( Collectors.toMap( // Use the file name as key. Pair::getLeft, // Use the loaded filter as value. pair -> { final FilterLoader loader = pair.getRight(); try { return loader.load(); } catch ( final IOException e ) { log.error( "Could not load Filter for '{}'.", pair.getLeft(), e ); return Filter.FILTER_NOTHING; } }, // Prefer project over default filters (due to concat order). ( projectFilter, defaultFilter ) -> projectFilter ) ); } private static String getFileName( final Path path ) { return path.getFileName().toString(); } }
Do not log irrelevant exceptions, like a missing optional file ERROR [AWT-EventQueue-0] [de.retest.recheck.ignore.SearchFilterFiles] - Exception accessing project filter folder '/Users/roessler/.retest/filter'. java.nio.file.NoSuchFileException: /Users/roessler/.retest/filter at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86) at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102) at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107) at sun.nio.fs.UnixFileAttributeViews$Basic.readAttributes(UnixFileAttributeViews.java:55) at sun.nio.fs.UnixFileSystemProvider.readAttributes(UnixFileSystemProvider.java:144) at java.nio.file.Files.readAttributes(Files.java:1737) at java.nio.file.FileTreeWalker.getAttributes(FileTreeWalker.java:219) at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:276) at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322) at java.nio.file.FileTreeIterator.<init>(FileTreeIterator.java:72) at java.nio.file.Files.walk(Files.java:3574) at java.nio.file.Files.walk(Files.java:3625) at de.retest.recheck.ignore.SearchFilterFiles.loadFiltersFromDirectory(SearchFilterFiles.java:82)
src/main/java/de/retest/recheck/ignore/SearchFilterFiles.java
Do not log irrelevant exceptions, like a missing optional file
<ide><path>rc/main/java/de/retest/recheck/ignore/SearchFilterFiles.java <ide> import java.nio.file.FileSystemNotFoundException; <ide> import java.nio.file.FileSystems; <ide> import java.nio.file.Files; <add>import java.nio.file.NoSuchFileException; <ide> import java.nio.file.Path; <ide> import java.nio.file.Paths; <ide> import java.util.Arrays; <ide> .filter( file -> file.toString().endsWith( FILTER_EXTENSION ) ) // <ide> .map( path -> Pair.of( getFileName( path ), FilterLoader.load( path ) ) ) // <ide> .collect( Collectors.toList() ); // <add> } catch ( final NoSuchFileException e ) { <add> log.warn( "No filter folder found at '{}': {}", directory, e.getMessage() ); <ide> } catch ( final IOException e ) { <ide> log.error( "Exception accessing project filter folder '{}'.", directory, e ); <del> return Collections.emptyList(); <ide> } <add> return Collections.emptyList(); <ide> } <ide> <ide> /**
Java
apache-2.0
23a93a832a670cf737bb8237fa92bd70460f6f40
0
ChetnaChaudhari/logging-log4j2,neuro-sys/logging-log4j2,xnslong/logging-log4j2,xnslong/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,lburgazzoli/apache-logging-log4j2,lburgazzoli/logging-log4j2,apache/logging-log4j2,renchunxiao/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,pisfly/logging-log4j2,renchunxiao/logging-log4j2,jinxuan/logging-log4j2,neuro-sys/logging-log4j2,lqbweb/logging-log4j2,GFriedrich/logging-log4j2,MagicWiz/log4j2,lburgazzoli/apache-logging-log4j2,jinxuan/logging-log4j2,MagicWiz/log4j2,ChetnaChaudhari/logging-log4j2,jsnikhil/nj-logging-log4j2,codescale/logging-log4j2,lburgazzoli/apache-logging-log4j2,lburgazzoli/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,lqbweb/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/logging-log4j2,jsnikhil/nj-logging-log4j2,pisfly/logging-log4j2
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.helpers; /** * Helps deal with integers. */ public class Integers { /** * Parses the string argument as a signed decimal integer. * * @param s * a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""} * @param defaultValue * the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""} * @return the integer value represented by the argument in decimal. * @throws NumberFormatException * if the string does not contain a parsable integer. */ public static int parseInt(String s, int defaultValue) { return Strings.isEmpty(s) ? defaultValue : Integer.parseInt(s); } /** * Parses the string argument as a signed decimal integer. * * @param s * a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""} * @param defaultValue * the return value, use {@code 0} if {@code s} is {@code null} or {@code ""} * @return the integer value represented by the argument in decimal. * @throws NumberFormatException * if the string does not contain a parsable integer. */ public static int parseInt(String s) { return parseInt(s, 0); } }
core/src/main/java/org/apache/logging/log4j/core/helpers/Integers.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.logging.log4j.core.helpers; /** * Helps deal with integers. */ public class Integers { /** * Parses the string argument as a signed decimal integer. * * @param s * a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""} * @param defaultValue * the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""} * @return the integer value represented by the argument in decimal. */ public static int parseInt(String s, int defaultValue) { return Strings.isEmpty(s) ? defaultValue : Integer.parseInt(s); } /** * Parses the string argument as a signed decimal integer. * * @param s * a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""} * @param defaultValue * the return value, use {@code 0} if {@code s} is {@code null} or {@code ""} * @return the integer value represented by the argument in decimal. */ public static int parseInt(String s) { return parseInt(s, 0); } }
Javadoc. git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1501375 13f79535-47bb-0310-9956-ffa450edef68
core/src/main/java/org/apache/logging/log4j/core/helpers/Integers.java
Javadoc.
<ide><path>ore/src/main/java/org/apache/logging/log4j/core/helpers/Integers.java <ide> * @param defaultValue <ide> * the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""} <ide> * @return the integer value represented by the argument in decimal. <add> * @throws NumberFormatException <add> * if the string does not contain a parsable integer. <ide> */ <ide> public static int parseInt(String s, int defaultValue) { <ide> return Strings.isEmpty(s) ? defaultValue : Integer.parseInt(s); <ide> * @param defaultValue <ide> * the return value, use {@code 0} if {@code s} is {@code null} or {@code ""} <ide> * @return the integer value represented by the argument in decimal. <add> * @throws NumberFormatException <add> * if the string does not contain a parsable integer. <ide> */ <ide> public static int parseInt(String s) { <ide> return parseInt(s, 0);
Java
mit
304944830e48c0b0524fda885a2e0999bfdaf7d9
0
stdrone/junior
package ru.sfedu.mmcs.portfolio.swing.chart; import java.awt.BasicStroke; import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.PlotChangeListener; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.util.ShapeUtilities; import ru.sfedu.mmcs.portfolio.AnalyzerData; import ru.sfedu.mmcs.portfolio.Portfolio; import ru.sfedu.mmcs.portfolio.frontier.Frontier; import ru.sfedu.mmcs.portfolio.swing.chart.data.DataSetActives; import ru.sfedu.mmcs.portfolio.swing.chart.data.DataSetFrontier; import ru.sfedu.mmcs.portfolio.swing.chart.data.DataSetOptimal; public class JFrontierChart extends ChartPanel { private static final long serialVersionUID = -4326820921442119966L; private JFrontierChart(JFreeChart chart) { super(chart); } private XYPlot _plot; private Frontier _frontier; public void refresh(AnalyzerData data) { if(data.getResult() != null) { _frontier = data.getResult(); DataSetFrontier frontierDataset = new DataSetFrontier(data.getResult().getFrontier()); DataSetActives portfolioDataset = new DataSetActives(data.getResult().getFrontier()); DataSetOptimal optimalDataset = new DataSetOptimal(data.getResult()); _plot.setDataset(frontierDataset); _plot.setDataset(1, portfolioDataset); _plot.setDataset(3, optimalDataset); _plot.getDomainAxis(0).setAutoRange(true); _plot.getRangeAxis(0).setAutoRange(true); } } public static JFrontierChart createFrontierChartPanel(String title, AnalyzerData data) { JFreeChart chart = ChartFactory.createXYLineChart(title, "μ", "V(μ)", null, PlotOrientation.VERTICAL, true, false, false); JFrontierChart chartPanel = new JFrontierChart(chart); chartPanel.setMouseWheelEnabled(true); chartPanel.setPopupMenu(chartPanel.createPopupMenu(false, true, true, true)); chartPanel._plot = chart.getXYPlot(); chartPanel._plot.addChangeListener(chartPanel.new FixAxisListner()); chartPanel.addChartMouseListener(chartPanel.new ChartClick()); NumberAxis axisActives = new NumberAxis("Активы"); axisActives.setRange(0.0, 1.0); axisActives.setAutoRange(false); chartPanel._plot.setRangeAxis(1,axisActives); chartPanel._plot.mapDatasetToRangeAxis(1,1); chartPanel._plot.mapDatasetToRangeAxis(2,0); chartPanel._plot.setRenderer(0, new StandardXYItemRenderer()); chartPanel._plot.setRenderer(1, new StandardXYItemRenderer()); ((AbstractRenderer) chartPanel._plot.getRenderer(1)).setAutoPopulateSeriesStroke(false); chartPanel._plot.getRenderer(1).setBaseStroke(new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, new float[] {2.0f,1.0f,0.5f,1.0f}, 0.0f)); chartPanel._plot.setRenderer(2, new XYLineAndShapeRenderer()); ((AbstractRenderer) chartPanel._plot.getRenderer(2)).setAutoPopulateSeriesShape(false); ((AbstractRenderer) chartPanel._plot.getRenderer(2)).setAutoPopulateSeriesPaint(false); chartPanel._plot.getRenderer(2).setBaseShape(ShapeUtilities.createDiagonalCross(3, 1)); chartPanel._plot.getRenderer(2).setBasePaint(Color.BLACK); chartPanel._plot.getRenderer(2).setBaseSeriesVisibleInLegend(false); chartPanel._plot.setRenderer(3, new XYLineAndShapeRenderer()); ((AbstractRenderer) chartPanel._plot.getRenderer(3)).setAutoPopulateSeriesShape(false); chartPanel._plot.getRenderer(3).setBaseShape(new Ellipse2D.Double(-3, -3, 6, 6)); chartPanel.setHorizontalAxisTrace(true); chartPanel.refresh(data); return chartPanel; } private class FixAxisListner implements PlotChangeListener{ private boolean _changed = false; @Override public void plotChanged(PlotChangeEvent arg0) { if(!_changed) { _changed = true; ((XYPlot)arg0.getPlot()).getRangeAxis(1).setRange(0.0,1.0); } _changed = false; } }; private class ChartClick implements ChartMouseListener{ private Portfolio _data; @Override public void chartMouseClicked(ChartMouseEvent e) { if(e.getTrigger().getButton() == MouseEvent.BUTTON1) { if(_data != null) JFrontierChart.this.Events.fireEntityClick(new EventEntityClick(JFrontierChart.this, _data)); else if(JFrontierChart.this._frontier != null) { Point2D p = JFrontierChart.this.translateScreenToJava2D(e.getTrigger().getPoint()); Rectangle2D plotArea = JFrontierChart.this.getScreenDataArea(); XYPlot plot = JFrontierChart.this._plot; double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge()); //double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge()); JFrontierChart.this.Events.fireEntityClick( new EventEntityClick(JFrontierChart.this, JFrontierChart.this._frontier.calcPortfolio(new Vector2D(chartX, 0))) ); } } } @Override public void chartMouseMoved(ChartMouseEvent e) { DefaultXYDataset dataPoint = new DefaultXYDataset(); _data = null; if(e.getEntity() instanceof XYItemEntity) { XYItemEntity ce = (XYItemEntity) e.getEntity(); if(ce.getDataset() instanceof DataSetOptimal) { double x = (double) ce.getDataset().getX(ce.getSeriesIndex(), ce.getItem()); double y = (double) ce.getDataset().getY(ce.getSeriesIndex(), ce.getItem()); if(ce.getDataset() instanceof DataSetOptimal) _data = ((DataSetOptimal)ce.getDataset()).getPortfolio(ce.getSeriesIndex(), ce.getItem()); dataPoint.addSeries("", new double[][] {{x},{y}}); } } JFrontierChart.this._plot.setDataset(2, dataPoint); } } public final EntityClickSource Events = new EntityClickSource(); }
src/ru/sfedu/mmcs/portfolio/swing/chart/JFrontierChart.java
package ru.sfedu.mmcs.portfolio.swing.chart; import java.awt.BasicStroke; import java.awt.Color; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.entity.XYItemEntity; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.PlotChangeListener; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.AbstractRenderer; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.util.ShapeUtilities; import ru.sfedu.mmcs.portfolio.AnalyzerData; import ru.sfedu.mmcs.portfolio.Portfolio; import ru.sfedu.mmcs.portfolio.frontier.Frontier; import ru.sfedu.mmcs.portfolio.swing.chart.data.DataSetActives; import ru.sfedu.mmcs.portfolio.swing.chart.data.DataSetFrontier; import ru.sfedu.mmcs.portfolio.swing.chart.data.DataSetOptimal; public class JFrontierChart extends ChartPanel { private static final long serialVersionUID = -4326820921442119966L; private JFrontierChart(JFreeChart chart) { super(chart); } private XYPlot _plot; private Frontier _frontier; public void refresh(AnalyzerData data) { if(data.getResult() != null) { _frontier = data.getResult(); DataSetFrontier frontierDataset = new DataSetFrontier(data.getResult().getFrontier()); DataSetActives portfolioDataset = new DataSetActives(data.getResult().getFrontier()); DataSetOptimal optimalDataset = new DataSetOptimal(data.getResult()); _plot.setDataset(frontierDataset); _plot.setDataset(1, portfolioDataset); _plot.setDataset(3, optimalDataset); _plot.getDomainAxis(0).setAutoRange(true); _plot.getRangeAxis(0).setAutoRange(true); } } public static JFrontierChart createFrontierChartPanel(String title, AnalyzerData data) { JFreeChart chart = ChartFactory.createXYLineChart(title, "μ", "V(μ)", null, PlotOrientation.VERTICAL, true, false, false); JFrontierChart chartPanel = new JFrontierChart(chart); chartPanel.setMouseWheelEnabled(true); chartPanel.setPopupMenu(chartPanel.createPopupMenu(false, true, true, true)); chartPanel._plot = chart.getXYPlot(); chartPanel._plot.addChangeListener(chartPanel.new FixAxisListner()); chartPanel.addChartMouseListener(chartPanel.new ChartClick()); NumberAxis axisActives = new NumberAxis("Активы"); axisActives.setRange(0.0, 1.0); axisActives.setAutoRange(false); chartPanel._plot.setRangeAxis(1,axisActives); chartPanel._plot.mapDatasetToRangeAxis(1,1); chartPanel._plot.mapDatasetToRangeAxis(2,0); chartPanel._plot.setRenderer(0, new StandardXYItemRenderer()); chartPanel._plot.setRenderer(1, new StandardXYItemRenderer()); ((AbstractRenderer) chartPanel._plot.getRenderer(1)).setAutoPopulateSeriesStroke(false); chartPanel._plot.getRenderer(1).setBaseStroke(new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f, new float[] {2.0f,1.0f,0.5f,1.0f}, 0.0f)); chartPanel._plot.setRenderer(2, new XYLineAndShapeRenderer()); ((AbstractRenderer) chartPanel._plot.getRenderer(2)).setAutoPopulateSeriesShape(false); ((AbstractRenderer) chartPanel._plot.getRenderer(2)).setAutoPopulateSeriesPaint(false); chartPanel._plot.getRenderer(2).setBaseShape(ShapeUtilities.createDiagonalCross(3, 1)); chartPanel._plot.getRenderer(2).setBasePaint(Color.BLACK); chartPanel._plot.getRenderer(2).setBaseSeriesVisibleInLegend(false); chartPanel._plot.setRenderer(3, new XYLineAndShapeRenderer()); ((AbstractRenderer) chartPanel._plot.getRenderer(3)).setAutoPopulateSeriesShape(false); chartPanel._plot.getRenderer(3).setBaseShape(new Ellipse2D.Double(-3, -3, 6, 6)); chartPanel.setHorizontalAxisTrace(true); chartPanel.refresh(data); return chartPanel; } private class FixAxisListner implements PlotChangeListener{ private boolean _changed = false; @Override public void plotChanged(PlotChangeEvent arg0) { if(!_changed) { _changed = true; ((XYPlot)arg0.getPlot()).getRangeAxis(1).setRange(0.0,1.0); } _changed = false; } }; private class ChartClick implements ChartMouseListener{ private Portfolio _data; @Override public void chartMouseClicked(ChartMouseEvent e) { if(_data != null) JFrontierChart.this.Events.fireEntityClick(new EventEntityClick(JFrontierChart.this, _data)); else if(JFrontierChart.this._frontier != null) { Point2D p = JFrontierChart.this.translateScreenToJava2D(e.getTrigger().getPoint()); Rectangle2D plotArea = JFrontierChart.this.getScreenDataArea(); XYPlot plot = JFrontierChart.this._plot; double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge()); //double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge()); JFrontierChart.this.Events.fireEntityClick( new EventEntityClick(JFrontierChart.this, JFrontierChart.this._frontier.calcPortfolio(new Vector2D(chartX, 0))) ); } } @Override public void chartMouseMoved(ChartMouseEvent e) { DefaultXYDataset dataPoint = new DefaultXYDataset(); _data = null; if(e.getEntity() instanceof XYItemEntity) { XYItemEntity ce = (XYItemEntity) e.getEntity(); if(ce.getDataset() instanceof DataSetOptimal) { double x = (double) ce.getDataset().getX(ce.getSeriesIndex(), ce.getItem()); double y = (double) ce.getDataset().getY(ce.getSeriesIndex(), ce.getItem()); if(ce.getDataset() instanceof DataSetOptimal) _data = ((DataSetOptimal)ce.getDataset()).getPortfolio(ce.getSeriesIndex(), ce.getItem()); dataPoint.addSeries("", new double[][] {{x},{y}}); } } JFrontierChart.this._plot.setDataset(2, dataPoint); } } public final EntityClickSource Events = new EntityClickSource(); }
right click fix
src/ru/sfedu/mmcs/portfolio/swing/chart/JFrontierChart.java
right click fix
<ide><path>rc/ru/sfedu/mmcs/portfolio/swing/chart/JFrontierChart.java <ide> <ide> import java.awt.BasicStroke; <ide> import java.awt.Color; <add>import java.awt.event.MouseEvent; <ide> import java.awt.geom.Ellipse2D; <ide> import java.awt.geom.Point2D; <ide> import java.awt.geom.Rectangle2D; <ide> <ide> @Override <ide> public void chartMouseClicked(ChartMouseEvent e) { <del> if(_data != null) <del> JFrontierChart.this.Events.fireEntityClick(new EventEntityClick(JFrontierChart.this, _data)); <del> else if(JFrontierChart.this._frontier != null) { <del> Point2D p = JFrontierChart.this.translateScreenToJava2D(e.getTrigger().getPoint()); <del> Rectangle2D plotArea = JFrontierChart.this.getScreenDataArea(); <del> XYPlot plot = JFrontierChart.this._plot; <del> double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge()); <del> //double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge()); <del> JFrontierChart.this.Events.fireEntityClick( <del> new EventEntityClick(JFrontierChart.this, JFrontierChart.this._frontier.calcPortfolio(new Vector2D(chartX, 0))) <del> ); <add> if(e.getTrigger().getButton() == MouseEvent.BUTTON1) { <add> if(_data != null) <add> JFrontierChart.this.Events.fireEntityClick(new EventEntityClick(JFrontierChart.this, _data)); <add> else if(JFrontierChart.this._frontier != null) { <add> Point2D p = JFrontierChart.this.translateScreenToJava2D(e.getTrigger().getPoint()); <add> Rectangle2D plotArea = JFrontierChart.this.getScreenDataArea(); <add> XYPlot plot = JFrontierChart.this._plot; <add> double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge()); <add> //double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge()); <add> JFrontierChart.this.Events.fireEntityClick( <add> new EventEntityClick(JFrontierChart.this, JFrontierChart.this._frontier.calcPortfolio(new Vector2D(chartX, 0))) <add> ); <add> } <ide> } <ide> } <ide>
Java
bsd-3-clause
0e76be695efe9305d103f3b0a5d70b989484511e
0
ox-it/gaboto,ox-it/gaboto
/** * Copyright 2009 University of Oxford * * Written by Arno Mittelbach for the Erewhon Project * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.oucs.gaboto; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.oucs.gaboto.util.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * A configuration object for Gaboto. * * * @author Arno Mittelbach * */ public class GabotoConfiguration { private String dbURL; private String dbUser; private String dbPassword; private String dbEngineName; private String dbDriver; private String NSGraphs = "http://gaboto.sf.net/graphs/"; private String NSData = "http://gaboto.sf.net/data/"; private Map<String, String> namespacePrefixes = new HashMap<String, String>(); public static GabotoConfiguration fromConfigFile() throws ParserConfigurationException, SAXException, IOException{ return fromConfigFile("Gaboto.xml"); } public static GabotoConfiguration fromConfigFile(String name) throws ParserConfigurationException, SAXException, IOException{ GabotoConfiguration config = new GabotoConfiguration(); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); Document doc = XMLUtils.readInputStreamIntoJAXPDoc(is); // Element configEl = (Element) doc.getElementsByTagName("config").item(0); // database NodeList configChildren = configEl.getChildNodes(); for(int i = 0; i < configChildren.getLength(); i++){ if(! (configChildren.item(i) instanceof Element)) continue; Element configSection = (Element) configChildren.item(i); if(configSection.getNodeName().equals("database")){ NodeList databaseChildren = configSection.getChildNodes(); for(int j = 0; j < databaseChildren.getLength(); j++){ if(! (databaseChildren.item(j) instanceof Element)) continue; Element databaseProp = (Element) databaseChildren.item(j); if(databaseProp.getNodeName().equals("engineName")){ config.dbEngineName = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("url")){ config.dbURL = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("user")){ config.dbUser = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("password")){ config.dbPassword = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("driver")){ config.dbDriver = databaseProp.getTextContent(); } } } else if(configSection.getNodeName().equals("namespaces")){ config.NSData = configSection.getAttribute("data"); config.NSGraphs = configSection.getAttribute("graphs"); } else if(configSection.getNodeName().equals("namespacePrefixes")){ NodeList nspChildren = configSection.getChildNodes(); for(int j = 0; j < nspChildren.getLength(); j++){ if(! (nspChildren.item(j) instanceof Element)) continue; Element namespacePrefix = (Element) nspChildren.item(j); if(! namespacePrefix.getNodeName().equals("namespacePrefix")) continue; config.namespacePrefixes.put(namespacePrefix.getAttribute("prefix"), namespacePrefix.getAttribute("ns")); } } } return config; } public String getDbURL() { return dbURL; } public void setDbURL(String dbURL) { this.dbURL = dbURL; } public String getDbUser() { return dbUser; } public void setDbUser(String dbUser) { this.dbUser = dbUser; } public String getDbPassword() { return dbPassword; } public void setDbPassword(String dbPassword) { this.dbPassword = dbPassword; } public String getDbEngineName() { return dbEngineName; } public void setDbEngineName(String dbEngineName) { this.dbEngineName = dbEngineName; } public String getDbDriver() { return dbDriver; } public void setDbDriver(String dbDriver) { this.dbDriver = dbDriver; } public String getNSGraphs() { return NSGraphs; } public void setNSGraphs(String graphs) { NSGraphs = graphs; } public String getNSData() { return NSData; } public void setNSData(String data) { NSData = data; } public String getGKG(){ return NSGraphs + "gkg.rdf"; } public String getCDG(){ return NSGraphs + "cdg.rdf"; } public String getDefaultGraph(){ return NSGraphs + "default.rdf"; } public Map<String, String> getNamespacePrefixes() { return namespacePrefixes; } public void setNamespacePrefixes(Map<String, String> namespacePrefixes) { this.namespacePrefixes = namespacePrefixes; } }
src/main/java/org/oucs/gaboto/GabotoConfiguration.java
/** * Copyright 2009 University of Oxford * * Written by Arno Mittelbach for the Erewhon Project * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.oucs.gaboto; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.oucs.gaboto.util.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * A configuration object for Gaboto. * * * @author Arno Mittelbach * */ public class GabotoConfiguration { private String dbURL; private String dbUser; private String dbPassword; private String dbEngineName; private String dbDriver; private String NSGraphs = "http://gaboto.net/graphs/"; private String NSData = "http://gaboto.net/graphs/"; private Map<String, String> namespacePrefixes = new HashMap<String, String>(); public static GabotoConfiguration fromConfigFile() throws ParserConfigurationException, SAXException, IOException{ return fromConfigFile("Gaboto.xml"); } public static GabotoConfiguration fromConfigFile(String name) throws ParserConfigurationException, SAXException, IOException{ GabotoConfiguration config = new GabotoConfiguration(); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); Document doc = XMLUtils.readInputStreamIntoJAXPDoc(is); // Element configEl = (Element) doc.getElementsByTagName("config").item(0); // database NodeList configChildren = configEl.getChildNodes(); for(int i = 0; i < configChildren.getLength(); i++){ if(! (configChildren.item(i) instanceof Element)) continue; Element configSection = (Element) configChildren.item(i); if(configSection.getNodeName().equals("database")){ NodeList databaseChildren = configSection.getChildNodes(); for(int j = 0; j < databaseChildren.getLength(); j++){ if(! (databaseChildren.item(j) instanceof Element)) continue; Element databaseProp = (Element) databaseChildren.item(j); if(databaseProp.getNodeName().equals("engineName")){ config.dbEngineName = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("url")){ config.dbURL = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("user")){ config.dbUser = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("password")){ config.dbPassword = databaseProp.getTextContent(); } else if(databaseProp.getNodeName().equals("driver")){ config.dbDriver = databaseProp.getTextContent(); } } } else if(configSection.getNodeName().equals("namespaces")){ config.NSData = configSection.getAttribute("data"); config.NSGraphs = configSection.getAttribute("graphs"); } else if(configSection.getNodeName().equals("namespacePrefixes")){ NodeList nspChildren = configSection.getChildNodes(); for(int j = 0; j < nspChildren.getLength(); j++){ if(! (nspChildren.item(j) instanceof Element)) continue; Element namespacePrefix = (Element) nspChildren.item(j); if(! namespacePrefix.getNodeName().equals("namespacePrefix")) continue; config.namespacePrefixes.put(namespacePrefix.getAttribute("prefix"), namespacePrefix.getAttribute("ns")); } } } return config; } public String getDbURL() { return dbURL; } public void setDbURL(String dbURL) { this.dbURL = dbURL; } public String getDbUser() { return dbUser; } public void setDbUser(String dbUser) { this.dbUser = dbUser; } public String getDbPassword() { return dbPassword; } public void setDbPassword(String dbPassword) { this.dbPassword = dbPassword; } public String getDbEngineName() { return dbEngineName; } public void setDbEngineName(String dbEngineName) { this.dbEngineName = dbEngineName; } public String getDbDriver() { return dbDriver; } public void setDbDriver(String dbDriver) { this.dbDriver = dbDriver; } public String getNSGraphs() { return NSGraphs; } public void setNSGraphs(String graphs) { NSGraphs = graphs; } public String getNSData() { return NSData; } public void setNSData(String data) { NSData = data; } public String getGKG(){ return NSGraphs + "gkg.rdf"; } public String getCDG(){ return NSGraphs + "cdg.rdf"; } public String getDefaultGraph(){ return NSGraphs + "default.rdf"; } public Map<String, String> getNamespacePrefixes() { return namespacePrefixes; } public void setNamespacePrefixes(Map<String, String> namespacePrefixes) { this.namespacePrefixes = namespacePrefixes; } }
Use sourceforge urls for unused, default namespace URIs
src/main/java/org/oucs/gaboto/GabotoConfiguration.java
Use sourceforge urls for unused, default namespace URIs
<ide><path>rc/main/java/org/oucs/gaboto/GabotoConfiguration.java <ide> private String dbEngineName; <ide> private String dbDriver; <ide> <del> private String NSGraphs = "http://gaboto.net/graphs/"; <del> private String NSData = "http://gaboto.net/graphs/"; <add> private String NSGraphs = "http://gaboto.sf.net/graphs/"; <add> private String NSData = "http://gaboto.sf.net/data/"; <ide> <ide> private Map<String, String> namespacePrefixes = new HashMap<String, String>(); <ide>
Java
mit
ecb417e1158b2788d4dcc09e7026bbaf339c9d59
0
Muntae/yamlbeans,EsotericSoftware/yamlbeans
/* * Copyright (c) 2008 Nathan Sweet * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.esotericsoftware.yamlbeans; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.esotericsoftware.yamlbeans.YamlConfig.ConstructorParameters; /** Utility for dealing with beans and public fields. * @author <a href="mailto:[email protected]">Nathan Sweet</a> */ class Beans { private Beans () { } static public boolean isScalar (Class c) { return c.isPrimitive() || c == String.class || c == Integer.class || c == Boolean.class || c == Float.class || c == Long.class || c == Double.class || c == Short.class || c == Byte.class || c == Character.class; } static public DeferredConstruction getDeferredConstruction (Class type, YamlConfig config) { ConstructorParameters parameters = config.readConfig.constructorParameters.get(type); if (parameters != null) return new DeferredConstruction(parameters.constructor, parameters.parameterNames); try { Class constructorProperties = Class.forName("java.beans.ConstructorProperties"); for (Constructor typeConstructor : type.getConstructors()) { Annotation annotation = typeConstructor.getAnnotation(constructorProperties); if (annotation == null) continue; String[] parameterNames = (String[])constructorProperties.getMethod("value").invoke(annotation, (Object[])null); return new DeferredConstruction(typeConstructor, parameterNames); } } catch (Exception ignored) { } return null; } static public Object createObject (Class type, boolean privateConstructors) throws InvocationTargetException { // Use no-arg constructor. Constructor constructor = null; for (Constructor typeConstructor : type.getConstructors()) { if (typeConstructor.getParameterTypes().length == 0) { constructor = typeConstructor; break; } } if (constructor == null && privateConstructors) { // Try a private constructor. try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { } } // Otherwise try to use a common implementation. if (constructor == null) { try { if (List.class.isAssignableFrom(type)) { constructor = ArrayList.class.getConstructor(new Class[0]); } else if (Set.class.isAssignableFrom(type)) { constructor = HashSet.class.getConstructor(new Class[0]); } else if (Map.class.isAssignableFrom(type)) { constructor = HashMap.class.getConstructor(new Class[0]); } } catch (Exception ex) { throw new InvocationTargetException(ex, "Error getting constructor for class: " + type.getName()); } } if (constructor == null) throw new InvocationTargetException(null, "Unable to find a no-arg constructor for class: " + type.getName()); try { return constructor.newInstance(); } catch (Exception ex) { throw new InvocationTargetException(ex, "Error constructing instance of class: " + type.getName()); } } static public Set<Property> getProperties (Class type, boolean beanProperties, boolean privateFields, YamlConfig config) { if (type == null) throw new IllegalArgumentException("type cannot be null."); Class[] noArgs = new Class[0], oneArg = new Class[1]; Set<Property> properties = config.writeConfig.keepBeanPropertyOrder ? new LinkedHashSet() : new TreeSet(); for (Field field : getAllFields(type)) { String name = field.getName(); if (beanProperties) { DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name); String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1); Method getMethod = null, setMethod = null; try { oneArg[0] = field.getType(); setMethod = type.getMethod("set" + nameUpper, oneArg); } catch (Exception ignored) { } try { getMethod = type.getMethod("get" + nameUpper, noArgs); } catch (Exception ignored) { } if (getMethod == null && (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class))) { try { getMethod = type.getMethod("is" + nameUpper, noArgs); } catch (Exception ignored) { } } if (getMethod != null && (setMethod != null || constructorProperty)) { properties.add(new MethodProperty(name, setMethod, getMethod)); continue; } } int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue; if (!Modifier.isPublic(modifiers) && !privateFields) continue; try { field.setAccessible(true); } catch (Exception ignored) { } properties.add(new FieldProperty(field)); } return properties; } static private String toJavaIdentifier (String name) { StringBuilder buffer = new StringBuilder(); for (int i = 0, n = name.length(); i < n; i++) { char c = name.charAt(i); if (Character.isJavaIdentifierPart(c)) buffer.append(c); } return buffer.toString(); } static public Property getProperty (Class type, String name, boolean beanProperties, boolean privateFields, YamlConfig config) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (name == null || name.length() == 0) throw new IllegalArgumentException("name cannot be null or empty."); name = toJavaIdentifier(name); if (beanProperties) { DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name); String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1); Method getMethod = null; try { getMethod = type.getMethod("get" + nameUpper); } catch (Exception ignored) { } if (getMethod == null) { try { getMethod = type.getMethod("is" + nameUpper); } catch (Exception ignored) { } } if (getMethod != null) { Method setMethod = null; try { setMethod = type.getMethod("set" + nameUpper, getMethod.getReturnType()); } catch (Exception ignored) { } if (getMethod != null && (setMethod != null || constructorProperty)) return new MethodProperty(name, setMethod, getMethod); } } for (Field field : getAllFields(type)) { if (!field.getName().equals(name)) continue; int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue; if (!Modifier.isPublic(modifiers) && !privateFields) continue; try { field.setAccessible(true); } catch (Exception ignored) { } return new FieldProperty(field); } return null; } static private ArrayList<Field> getAllFields (Class type) { ArrayList<Class> classes = new ArrayList(); Class nextClass = type; while (nextClass != null && nextClass != Object.class) { classes.add(nextClass); nextClass = nextClass.getSuperclass(); } ArrayList<Field> allFields = new ArrayList(); for (int i = classes.size() - 1; i >= 0; i--) { Collections.addAll(allFields, classes.get(i).getDeclaredFields()); } return allFields; } static public class MethodProperty extends Property { private final Method setMethod, getMethod; public MethodProperty (String name, Method setMethod, Method getMethod) { super(getMethod.getDeclaringClass(), name, getMethod.getReturnType(), getMethod.getGenericReturnType()); this.setMethod = setMethod; this.getMethod = getMethod; } public void set (Object object, Object value) throws Exception { if (object instanceof DeferredConstruction) { ((DeferredConstruction)object).storeProperty(this, value); return; } setMethod.invoke(object, value); } public Object get (Object object) throws Exception { return getMethod.invoke(object); } } static public class FieldProperty extends Property { private final Field field; public FieldProperty (Field field) { super(field.getDeclaringClass(), field.getName(), field.getType(), field.getGenericType()); this.field = field; } public void set (Object object, Object value) throws Exception { if (object instanceof DeferredConstruction) { ((DeferredConstruction)object).storeProperty(this, value); return; } field.set(object, value); } public Object get (Object object) throws Exception { return field.get(object); } } static public abstract class Property implements Comparable<Property> { private final Class declaringClass; private final String name; private final Class type; private final Class elementType; Property (Class declaringClass, String name, Class type, Type genericType) { this.declaringClass = declaringClass; this.name = name; this.type = type; this.elementType = getElementTypeFromGenerics(genericType); } private Class getElementTypeFromGenerics (Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; Type rawType = parameterizedType.getRawType(); if (isCollection(rawType) || isMap(rawType)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { return (Class)actualTypeArguments[actualTypeArguments.length - 1]; } } } return null; } private boolean isMap (Type type) { return Map.class.isAssignableFrom((Class)type); } private boolean isCollection (Type type) { return Collection.class.isAssignableFrom((Class)type); } public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((elementType == null) ? 0 : elementType.hashCode()); return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Property other = (Property)obj; if (declaringClass == null) { if (other.declaringClass != null) return false; } else if (!declaringClass.equals(other.declaringClass)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (elementType == null) { if (other.elementType != null) return false; } else if (!elementType.equals(other.elementType)) return false; return true; } public Class getDeclaringClass () { return declaringClass; } public Class getElementType () { return elementType; } public Class getType () { return type; } public String getName () { return name; } public String toString () { return name; } public int compareTo (Property o) { int comparison = name.compareTo(o.name); if (comparison != 0) { // Sort id and name above all other fields. if (name.equals("id")) return -1; if (o.name.equals("id")) return 1; if (name.equals("name")) return -1; if (o.name.equals("name")) return 1; } return comparison; } abstract public void set (Object object, Object value) throws Exception; abstract public Object get (Object object) throws Exception; } }
src/com/esotericsoftware/yamlbeans/Beans.java
/* * Copyright (c) 2008 Nathan Sweet * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.esotericsoftware.yamlbeans; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.esotericsoftware.yamlbeans.YamlConfig.ConstructorParameters; /** Utility for dealing with beans and public fields. * @author <a href="mailto:[email protected]">Nathan Sweet</a> */ class Beans { private Beans () { } static public boolean isScalar (Class c) { return c.isPrimitive() || c == String.class || c == Integer.class || c == Boolean.class || c == Float.class || c == Long.class || c == Double.class || c == Short.class || c == Byte.class || c == Character.class; } static public DeferredConstruction getDeferredConstruction (Class type, YamlConfig config) { ConstructorParameters parameters = config.readConfig.constructorParameters.get(type); if (parameters != null) return new DeferredConstruction(parameters.constructor, parameters.parameterNames); try { Class constructorProperties = Class.forName("java.beans.ConstructorProperties"); for (Constructor typeConstructor : type.getConstructors()) { Annotation annotation = typeConstructor.getAnnotation(constructorProperties); if (annotation == null) continue; String[] parameterNames = (String[])constructorProperties.getMethod("value").invoke(annotation, (Object[])null); return new DeferredConstruction(typeConstructor, parameterNames); } } catch (Exception ignored) { } return null; } static public Object createObject (Class type, boolean privateConstructors) throws InvocationTargetException { // Use no-arg constructor. Constructor constructor = null; for (Constructor typeConstructor : type.getConstructors()) { if (typeConstructor.getParameterTypes().length == 0) { constructor = typeConstructor; break; } } if (constructor == null && privateConstructors) { // Try a private constructor. try { constructor = type.getDeclaredConstructor(); constructor.setAccessible(true); } catch (SecurityException ignored) { } catch (NoSuchMethodException ignored) { } } // Otherwise try to use a common implementation. if (constructor == null) { try { if (List.class.isAssignableFrom(type)) { constructor = ArrayList.class.getConstructor(new Class[0]); } else if (Set.class.isAssignableFrom(type)) { constructor = HashSet.class.getConstructor(new Class[0]); } else if (Map.class.isAssignableFrom(type)) { constructor = HashMap.class.getConstructor(new Class[0]); } } catch (Exception ex) { throw new InvocationTargetException(ex, "Error getting constructor for class: " + type.getName()); } } if (constructor == null) throw new InvocationTargetException(null, "Unable to find a no-arg constructor for class: " + type.getName()); try { return constructor.newInstance(); } catch (Exception ex) { throw new InvocationTargetException(ex, "Error constructing instance of class: " + type.getName()); } } static public Set<Property> getProperties (Class type, boolean beanProperties, boolean privateFields, YamlConfig config) { if (type == null) throw new IllegalArgumentException("type cannot be null."); Class[] noArgs = new Class[0], oneArg = new Class[1]; Set<Property> properties = config.writeConfig.keepBeanPropertyOrder ? new LinkedHashSet() : new TreeSet(); for (Field field : getAllFields(type)) { String name = field.getName(); if (beanProperties) { DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name); String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1); Method getMethod = null, setMethod = null; try { oneArg[0] = field.getType(); setMethod = type.getMethod("set" + nameUpper, oneArg); } catch (Exception ignored) { } try { getMethod = type.getMethod("get" + nameUpper, noArgs); } catch (Exception ignored) { } if (getMethod == null && (field.getType().equals(Boolean.class) || field.getType().equals(boolean.class))) { try { getMethod = type.getMethod("is" + nameUpper, noArgs); } catch (Exception ignored) { } } if (getMethod != null && (setMethod != null || constructorProperty)) { properties.add(new MethodProperty(name, setMethod, getMethod)); continue; } } int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue; if (!Modifier.isPublic(modifiers) && !privateFields) continue; try { field.setAccessible(true); } catch (Exception ignored) { } properties.add(new FieldProperty(field)); } return properties; } static public Property getProperty (Class type, String name, boolean beanProperties, boolean privateFields, YamlConfig config) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (name == null || name.length() == 0) throw new IllegalArgumentException("name cannot be null or empty."); name = name.replace(" ", ""); if (beanProperties) { DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); boolean constructorProperty = deferredConstruction != null && deferredConstruction.hasParameter(name); String nameUpper = Character.toUpperCase(name.charAt(0)) + name.substring(1); Method getMethod = null; try { getMethod = type.getMethod("get" + nameUpper); } catch (Exception ignored) { } if (getMethod == null) { try { getMethod = type.getMethod("is" + nameUpper); } catch (Exception ignored) { } } if (getMethod != null) { Method setMethod = null; try { setMethod = type.getMethod("set" + nameUpper, getMethod.getReturnType()); } catch (Exception ignored) { } if (getMethod != null && (setMethod != null || constructorProperty)) return new MethodProperty(name, setMethod, getMethod); } } for (Field field : getAllFields(type)) { if (!field.getName().equals(name)) continue; int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) continue; if (!Modifier.isPublic(modifiers) && !privateFields) continue; try { field.setAccessible(true); } catch (Exception ignored) { } return new FieldProperty(field); } return null; } static private ArrayList<Field> getAllFields (Class type) { ArrayList<Class> classes = new ArrayList(); Class nextClass = type; while (nextClass != null && nextClass != Object.class) { classes.add(nextClass); nextClass = nextClass.getSuperclass(); } ArrayList<Field> allFields = new ArrayList(); for(int i = classes.size() - 1; i >= 0; i--) { Collections.addAll(allFields, classes.get(i).getDeclaredFields()); } return allFields; } static public class MethodProperty extends Property { private final Method setMethod, getMethod; public MethodProperty (String name, Method setMethod, Method getMethod) { super(getMethod.getDeclaringClass(), name, getMethod.getReturnType(), getMethod.getGenericReturnType()); this.setMethod = setMethod; this.getMethod = getMethod; } public void set (Object object, Object value) throws Exception { if (object instanceof DeferredConstruction) { ((DeferredConstruction)object).storeProperty(this, value); return; } setMethod.invoke(object, value); } public Object get (Object object) throws Exception { return getMethod.invoke(object); } } static public class FieldProperty extends Property { private final Field field; public FieldProperty (Field field) { super(field.getDeclaringClass(), field.getName(), field.getType(), field.getGenericType()); this.field = field; } public void set (Object object, Object value) throws Exception { if (object instanceof DeferredConstruction) { ((DeferredConstruction)object).storeProperty(this, value); return; } field.set(object, value); } public Object get (Object object) throws Exception { return field.get(object); } } static public abstract class Property implements Comparable<Property> { private final Class declaringClass; private final String name; private final Class type; private final Class elementType; Property (Class declaringClass, String name, Class type, Type genericType) { this.declaringClass = declaringClass; this.name = name; this.type = type; this.elementType = getElementTypeFromGenerics(genericType); } private Class getElementTypeFromGenerics (Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; Type rawType = parameterizedType.getRawType(); if (isCollection(rawType) || isMap(rawType)) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length > 0) { return (Class)actualTypeArguments[actualTypeArguments.length - 1]; } } } return null; } private boolean isMap (Type type) { return Map.class.isAssignableFrom((Class)type); } private boolean isCollection (Type type) { return Collection.class.isAssignableFrom((Class)type); } public int hashCode () { final int prime = 31; int result = 1; result = prime * result + ((declaringClass == null) ? 0 : declaringClass.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((elementType == null) ? 0 : elementType.hashCode()); return result; } public boolean equals (Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Property other = (Property)obj; if (declaringClass == null) { if (other.declaringClass != null) return false; } else if (!declaringClass.equals(other.declaringClass)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (elementType == null) { if (other.elementType != null) return false; } else if (!elementType.equals(other.elementType)) return false; return true; } public Class getDeclaringClass () { return declaringClass; } public Class getElementType () { return elementType; } public Class getType () { return type; } public String getName () { return name; } public String toString () { return name; } public int compareTo (Property o) { int comparison = name.compareTo(o.name); if (comparison != 0) { // Sort id and name above all other fields. if (name.equals("id")) return -1; if (o.name.equals("id")) return 1; if (name.equals("name")) return -1; if (o.name.equals("name")) return 1; } return comparison; } abstract public void set (Object object, Object value) throws Exception; abstract public Object get (Object object) throws Exception; } }
Remove invalid characters from field names in YAML data.
src/com/esotericsoftware/yamlbeans/Beans.java
Remove invalid characters from field names in YAML data.
<ide><path>rc/com/esotericsoftware/yamlbeans/Beans.java <ide> return properties; <ide> } <ide> <add> static private String toJavaIdentifier (String name) { <add> StringBuilder buffer = new StringBuilder(); <add> for (int i = 0, n = name.length(); i < n; i++) { <add> char c = name.charAt(i); <add> if (Character.isJavaIdentifierPart(c)) buffer.append(c); <add> } <add> return buffer.toString(); <add> } <add> <ide> static public Property getProperty (Class type, String name, boolean beanProperties, boolean privateFields, <ide> YamlConfig config) { <ide> if (type == null) throw new IllegalArgumentException("type cannot be null."); <ide> if (name == null || name.length() == 0) throw new IllegalArgumentException("name cannot be null or empty."); <del> name = name.replace(" ", ""); <add> name = toJavaIdentifier(name); <ide> <ide> if (beanProperties) { <ide> DeferredConstruction deferredConstruction = getDeferredConstruction(type, config); <ide> nextClass = nextClass.getSuperclass(); <ide> } <ide> ArrayList<Field> allFields = new ArrayList(); <del> for(int i = classes.size() - 1; i >= 0; i--) { <add> for (int i = classes.size() - 1; i >= 0; i--) { <ide> Collections.addAll(allFields, classes.get(i).getDeclaredFields()); <ide> } <ide> return allFields;
Java
apache-2.0
error: pathspec 'bbvm-core/src/main/java/me/wener/bbvm/dev/Images.java' did not match any file(s) known to git
2243ed84f9bec239694dfb9718ab6906649728b7
1
wenerme/bbvm,wenerme/bbvm
package me.wener.bbvm.dev; import com.google.common.base.MoreObjects; import com.google.common.collect.Maps; import com.google.common.io.Files; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.image.DataBufferUShort; import java.awt.image.DirectColorModel; import java.awt.image.WritableRaster; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author wener * @since 15/12/19 */ public class Images { private static final Map<String, ImageCodec> CODEC = Maps.newHashMap(); private static final int DCM_565_RED_MASK = 0xf800; private static final int DCM_565_GRN_MASK = 0x07E0; private static final int DCM_565_BLU_MASK = 0x001F; static { } public static List<ImageInfo> load(String file) throws IOException { Path path = Paths.get(file); for (Map.Entry<String, ImageCodec> entry : CODEC.entrySet()) { ImageCodec codec = entry.getValue(); if (codec.accept(path)) { return codec.load(path); } } throw new RuntimeException("Can not load image file " + file); } public static BufferedImage read(ImageInfo info) throws IOException { return CODEC.get(info.getType()).read(info); } public static BufferedImage read(String file, int index) throws IOException { return read(load(file).get(index)); } private static List<ImageInfo> loadInfos(Path file, String type, boolean hasName) throws IOException { try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) { int n = ch.map(FileChannel.MapMode.READ_ONLY, 0, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); ByteBuf buf = Unpooled.wrappedBuffer(ch.map(FileChannel.MapMode.READ_ONLY, 4, n * (4 + 32))).order(ByteOrder.LITTLE_ENDIAN); List<ImageInfo> list = new ArrayList<>(n); for (int i = 0; i < n; i++) { int offset = buf.readInt(); String name = null; if (hasName) { int length = buf.bytesBefore(32, (byte) 0); if (length > 0) { name = buf.toString(buf.readerIndex(), length, StandardCharsets.UTF_8); } buf.skipBytes(32); } if (name == null) { name = "NO-" + i; } list.add(new ImageInfo(i, name, offset, file.toString(), type)); } return list; } } interface ImageCodec { List<ImageInfo> load(Path file) throws IOException; default BufferedImage read(Path path, int index) throws IOException { return read(load(path).get(index)); } String getType(); boolean accept(Path path); BufferedImage read(ImageInfo info) throws IOException; } static class LibRGB565ImageCodec implements ImageCodec { @Override public List<ImageInfo> load(Path file) throws IOException { return loadInfos(file, getType(), false); } @Override public String getType() { return "LIB_RGB565"; } @Override public boolean accept(Path path) { File file = path.toFile(); return !file.isDirectory() && Files.getFileExtension(file.getName()).equalsIgnoreCase("RLB"); } @Override public BufferedImage read(ImageInfo info) throws IOException { try (FileChannel ch = FileChannel.open(Paths.get(info.getFilename()), StandardOpenOption.READ)) { // + 4 to skip length ByteBuf buf = Unpooled.wrappedBuffer(ch.map(FileChannel.MapMode.READ_ONLY, info.getOffset() + 4, 8)).order(ByteOrder.LITTLE_ENDIAN); int w = buf.readUnsignedShort(), h = buf.readUnsignedShort(); ByteBuffer buffer = ByteBuffer.allocate(w * h * 2).order(ByteOrder.LITTLE_ENDIAN); ch.read(buffer); // Fast way to load the data DirectColorModel colorModel = new DirectColorModel(16, DCM_565_RED_MASK, DCM_565_GRN_MASK, DCM_565_BLU_MASK); WritableRaster raster = colorModel.createCompatibleWritableRaster(w, h); buffer.flip(); buffer.asShortBuffer().get(((DataBufferUShort) raster.getDataBuffer()).getData()); return new BufferedImage(colorModel, raster, false, null); } } } static class RLBImageCodec implements ImageCodec { @Override public List<ImageInfo> load(Path path) throws IOException { return loadInfos(path, getType(), true); } @Override public BufferedImage read(Path path, int index) throws IOException { return read(load(path).get(index)); } @Override public String getType() { return "RLB"; } @Override public boolean accept(Path path) { File file = path.toFile(); return !file.isDirectory() && Files.getFileExtension(file.getName()).equalsIgnoreCase("RLB"); } @Override public BufferedImage read(ImageInfo info) throws IOException { FileInputStream is = new FileInputStream(new File(info.getFilename())); long skipped = is.skip(info.getOffset() + 4); assert skipped == info.getOffset() + 4; return ImageIO.read(is); } } static class ImageInfo { private final int index; private final String name; private final int offset; private final String filename; private final String type; public ImageInfo(int index, String name, int offset, String filename, String type) { this.index = index; this.name = name; this.offset = offset; this.filename = filename; this.type = type; } public int getOffset() { return offset; } public int getIndex() { return index; } public String getType() { return type; } public String getName() { return name; } public String getFilename() { return filename; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("index", index) .add("name", name) .add("offset", offset) .add("filename", filename) .add("type", type) .toString(); } } }
bbvm-core/src/main/java/me/wener/bbvm/dev/Images.java
#5 Implement RLB and LIB_RGB565 codec.
bbvm-core/src/main/java/me/wener/bbvm/dev/Images.java
#5 Implement RLB and LIB_RGB565 codec.
<ide><path>bvm-core/src/main/java/me/wener/bbvm/dev/Images.java <add>package me.wener.bbvm.dev; <add> <add>import com.google.common.base.MoreObjects; <add>import com.google.common.collect.Maps; <add>import com.google.common.io.Files; <add>import io.netty.buffer.ByteBuf; <add>import io.netty.buffer.Unpooled; <add> <add>import javax.imageio.ImageIO; <add>import java.awt.image.BufferedImage; <add>import java.awt.image.DataBufferUShort; <add>import java.awt.image.DirectColorModel; <add>import java.awt.image.WritableRaster; <add>import java.io.File; <add>import java.io.FileInputStream; <add>import java.io.IOException; <add>import java.nio.ByteBuffer; <add>import java.nio.ByteOrder; <add>import java.nio.channels.FileChannel; <add>import java.nio.charset.StandardCharsets; <add>import java.nio.file.Path; <add>import java.nio.file.Paths; <add>import java.nio.file.StandardOpenOption; <add>import java.util.ArrayList; <add>import java.util.List; <add>import java.util.Map; <add> <add>/** <add> * @author wener <add> * @since 15/12/19 <add> */ <add>public class Images { <add> private static final Map<String, ImageCodec> CODEC = Maps.newHashMap(); <add> private static final int DCM_565_RED_MASK = 0xf800; <add> private static final int DCM_565_GRN_MASK = 0x07E0; <add> private static final int DCM_565_BLU_MASK = 0x001F; <add> <add> static { <add> } <add> <add> public static List<ImageInfo> load(String file) throws IOException { <add> Path path = Paths.get(file); <add> for (Map.Entry<String, ImageCodec> entry : CODEC.entrySet()) { <add> ImageCodec codec = entry.getValue(); <add> if (codec.accept(path)) { <add> return codec.load(path); <add> } <add> } <add> throw new RuntimeException("Can not load image file " + file); <add> } <add> <add> public static BufferedImage read(ImageInfo info) throws IOException { <add> return CODEC.get(info.getType()).read(info); <add> } <add> <add> public static BufferedImage read(String file, int index) throws IOException { <add> return read(load(file).get(index)); <add> } <add> <add> <add> private static List<ImageInfo> loadInfos(Path file, String type, boolean hasName) throws IOException { <add> try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) { <add> int n = ch.map(FileChannel.MapMode.READ_ONLY, 0, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); <add> ByteBuf buf = Unpooled.wrappedBuffer(ch.map(FileChannel.MapMode.READ_ONLY, 4, n * (4 + 32))).order(ByteOrder.LITTLE_ENDIAN); <add> List<ImageInfo> list = new ArrayList<>(n); <add> for (int i = 0; i < n; i++) { <add> int offset = buf.readInt(); <add> String name = null; <add> if (hasName) { <add> int length = buf.bytesBefore(32, (byte) 0); <add> if (length > 0) { <add> name = buf.toString(buf.readerIndex(), length, StandardCharsets.UTF_8); <add> } <add> buf.skipBytes(32); <add> } <add> if (name == null) { <add> name = "NO-" + i; <add> } <add> list.add(new ImageInfo(i, name, offset, file.toString(), type)); <add> <add> } <add> return list; <add> } <add> } <add> <add> <add> interface ImageCodec { <add> List<ImageInfo> load(Path file) throws IOException; <add> <add> default BufferedImage read(Path path, int index) throws IOException { <add> return read(load(path).get(index)); <add> } <add> <add> String getType(); <add> <add> boolean accept(Path path); <add> <add> BufferedImage read(ImageInfo info) throws IOException; <add> } <add> <add> static class LibRGB565ImageCodec implements ImageCodec { <add> <add> @Override <add> public List<ImageInfo> load(Path file) throws IOException { <add> return loadInfos(file, getType(), false); <add> } <add> <add> @Override <add> public String getType() { <add> return "LIB_RGB565"; <add> } <add> <add> @Override <add> public boolean accept(Path path) { <add> File file = path.toFile(); <add> return !file.isDirectory() && Files.getFileExtension(file.getName()).equalsIgnoreCase("RLB"); <add> } <add> <add> @Override <add> public BufferedImage read(ImageInfo info) throws IOException { <add> try (FileChannel ch = FileChannel.open(Paths.get(info.getFilename()), StandardOpenOption.READ)) { <add> // + 4 to skip length <add> ByteBuf buf = Unpooled.wrappedBuffer(ch.map(FileChannel.MapMode.READ_ONLY, info.getOffset() + 4, 8)).order(ByteOrder.LITTLE_ENDIAN); <add> int w = buf.readUnsignedShort(), h = buf.readUnsignedShort(); <add> ByteBuffer buffer = ByteBuffer.allocate(w * h * 2).order(ByteOrder.LITTLE_ENDIAN); <add> ch.read(buffer); <add> // Fast way to load the data <add> DirectColorModel colorModel = new DirectColorModel(16, DCM_565_RED_MASK, DCM_565_GRN_MASK, DCM_565_BLU_MASK); <add> WritableRaster raster = colorModel.createCompatibleWritableRaster(w, h); <add> <add> buffer.flip(); <add> buffer.asShortBuffer().get(((DataBufferUShort) raster.getDataBuffer()).getData()); <add> return new BufferedImage(colorModel, raster, false, null); <add> } <add> } <add> } <add> <add> static class RLBImageCodec implements ImageCodec { <add> <add> @Override <add> public List<ImageInfo> load(Path path) throws IOException { <add> return loadInfos(path, getType(), true); <add> } <add> <add> @Override <add> public BufferedImage read(Path path, int index) throws IOException { <add> return read(load(path).get(index)); <add> } <add> <add> @Override <add> public String getType() { <add> return "RLB"; <add> } <add> <add> @Override <add> public boolean accept(Path path) { <add> File file = path.toFile(); <add> return !file.isDirectory() && Files.getFileExtension(file.getName()).equalsIgnoreCase("RLB"); <add> } <add> <add> @Override <add> public BufferedImage read(ImageInfo info) throws IOException { <add> FileInputStream is = new FileInputStream(new File(info.getFilename())); <add> long skipped = is.skip(info.getOffset() + 4); <add> assert skipped == info.getOffset() + 4; <add> return ImageIO.read(is); <add> } <add> } <add> <add> static class ImageInfo { <add> private final int index; <add> private final String name; <add> private final int offset; <add> private final String filename; <add> private final String type; <add> <add> public ImageInfo(int index, String name, int offset, String filename, String type) { <add> this.index = index; <add> this.name = name; <add> this.offset = offset; <add> this.filename = filename; <add> this.type = type; <add> } <add> <add> public int getOffset() { <add> return offset; <add> } <add> <add> public int getIndex() { <add> return index; <add> } <add> <add> public String getType() { <add> return type; <add> } <add> <add> public String getName() { <add> return name; <add> } <add> <add> public String getFilename() { <add> return filename; <add> } <add> <add> @Override <add> public String toString() { <add> return MoreObjects.toStringHelper(this) <add> .add("index", index) <add> .add("name", name) <add> .add("offset", offset) <add> .add("filename", filename) <add> .add("type", type) <add> .toString(); <add> } <add> } <add>}
Java
apache-2.0
a2b4d2caedf2df3a760e1715fd85191940eaf16a
0
xannz/StormCharmConnector
/** * */ package com.ubuntu.stormdeployer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.List; import org.apache.maven.cli.MavenCli; import org.yaml.snakeyaml.Loader; import org.yaml.snakeyaml.Yaml; /** * @author maarten Undeploy storm topologies */ public class StormDeployer { public void execute(String command, PrintStream log) throws Exception { Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { log.append(line + "\n"); } } finally { reader.close(); } } public void wget(URL url, File destination) throws Exception { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } public void git(String giturl, File directory, PrintStream out, String credentials) throws Exception { if (credentials.equals("")) { execute("git clone " + giturl + " " + directory.getAbsolutePath(), out); } else { String EersteDeel = giturl.split("//")[0]; String userenpass = "//" + credentials + "@"; String TweedeDeel = giturl.split("//")[1]; String git = EersteDeel + userenpass + TweedeDeel; execute("git clone " + git + " " + directory.getAbsolutePath(), out); } } public void deploy(String command, Topology topology, PrintStream out, String credentials) throws Exception { String name = topology.getName(); String jar = topology.getJar(); String packaging = topology.getPackaging(); String repo = topology.getRepository(); String topologyclass = topology.getTopologyclass(); String beforePackage = topology.getScriptbeforepackaging(); String beforeDeploy = topology.getScriptbeforedeploying(); List<DataSource> dss = topology.getDatasources(); String release = topology.getRelease(); String[] nameAndParams = name.split(" ", 2); // choise target folder File target = new File("/tmp/stormdeployertmp"); if (!target.exists()) { out.append("Creating /tmp/stormdeployertmp \n"); target.mkdir(); } //File topologyDir = new File(target.getAbsolutePath() + "/" + name.split(" ")[0]); File topologyDir = new File(target.getAbsolutePath() + "/" + nameAndParams[0]); // Did we deploy this topology already? if (!topologyDir.exists()) { out.append("Topology not yet deployed.\n"); topologyDir.mkdir(); //Check if source code or jar file if (packaging.equals("jar")) { out.append("Jar will be downloaded.\n"); URL url = new URL(release); try (InputStream inStream = url.openStream()) { System.out.println(inStream.available()); BufferedInputStream bufIn = new BufferedInputStream(inStream); File fileWrite = new File(topologyDir.getAbsolutePath() + "/" + jar); OutputStream outp = new FileOutputStream(fileWrite); BufferedOutputStream bufOut = new BufferedOutputStream(outp); byte buffer[] = new byte[1024]; while (true) { int nRead = bufIn.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } bufOut.write(buffer, 0, nRead); } bufOut.flush(); outp.close(); } if (nameAndParams.length > 1) { deploy(command, topologyDir.getAbsolutePath() + "/" + jar, topologyclass, nameAndParams[1], out); } else { deploy(command, topologyDir.getAbsolutePath() + "/" + jar, topologyclass, nameAndParams[0], out); } } else { out.append("Source code will be downloaded.\n"); // download source code from git git(repo, topologyDir, out, credentials); // Run before packaging script if (beforePackage != null) { out.append("Run before packaging script.\n"); File beforePackageDir = new File(topologyDir.getAbsolutePath() + "/package"); beforePackageDir.mkdir(); File packageScript = new File(beforePackageDir.getAbsolutePath() + "/script"); wget(new URL(beforePackage), packageScript); execute("chmod u+x " + packageScript.getAbsolutePath(), out); execute(packageScript.getAbsolutePath(), out); } if (dss != null) { out.append("Applying datasources.\n"); for (DataSource ds : dss) { applyDataSource(ds, topologyDir, out); } } // Todo implement alternative packaging and subdirectory support for Maven MavenCli cli = new MavenCli(); if(packaging.equals("mvn package")){ cli.doMain(new String[]{"package"}, topologyDir.getAbsolutePath(), out, out); }else{ cli.doMain(new String[]{packaging}, topologyDir.getAbsolutePath(), out, out); } // Run before deploying script if (beforeDeploy != null) { out.append("Running before deploy script.\n"); File beforeDeployDir = new File(topologyDir.getAbsolutePath() + "/deploy"); beforeDeployDir.mkdir(); File deployScript = new File(beforeDeployDir.getAbsolutePath() + "/script"); wget(new URL(beforeDeploy), deployScript); execute("chmod u+x " + deployScript.getAbsolutePath(), out); execute(deployScript.getAbsolutePath(), out); } // Deploy the topology if (nameAndParams.length > 1) { deploy(command, topologyDir.getAbsolutePath() + "/target/" + jar, topologyclass, nameAndParams[1], out); } else { deploy(command, topologyDir.getAbsolutePath() + "/target/" + jar, topologyclass, nameAndParams[0], out); } } } } public void applyDataSource(DataSource ds, File topologyDir, PrintStream out) throws Exception { List<Parameter> params = ds.getParameters(); String scriptURL = ds.getScript(); String type = ds.getType(); File dsdir = new File(topologyDir.getAbsolutePath() + "/datasources"); dsdir.mkdir(); File dir = new File(topologyDir.getAbsolutePath() + "/datasources/" + type); dir.mkdir(); File file = new File(topologyDir.getAbsolutePath() + "/datasources/" + type + "/script"); wget(new URL(scriptURL), file); execute("chmod u+x " + file, out); StringBuffer sb = new StringBuffer(); for (Parameter param : params) { sb.append(param.getName()); sb.append("="); sb.append(param.getValue()); sb.append(" "); } execute(file + " " + sb.toString(), out); } public void deploy(String deployment, String jar, String topologyClass, String topologyName, PrintStream out) throws Exception { out.append("Deploying:" + deployment + " " + jar + " " + topologyClass + " " + topologyName + "\n"); execute(deployment + " " + jar + " " + topologyClass + " " + topologyName, out); } public List<Topology> readTopologies(String file) throws Exception { StringBuffer deployer = new StringBuffer(); FileReader fr = new FileReader(file); BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(fr); while ((sCurrentLine = br.readLine()) != null) { //System.out.println(sCurrentLine); deployer.append(sCurrentLine); deployer.append("\n"); } } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { } } TopologiesConstructor constructor = new TopologiesConstructor(Topologies.class); Loader loader = new Loader(constructor); Yaml yaml = new Yaml(loader); Topologies topologies = (Topologies) yaml.load(deployer.toString()); return topologies.getTopology(); } /** * @param args * @throws Exception When deployment can not be done. */ public static void main(String[] args) throws Exception { if (args.length < 1) { throw new Exception("deployer file is missing. Usage: deployerURL (debugLogFile)"); } PrintStream out = System.out; if (args.length > 2) { out = new PrintStream(args[2]); }else if (args.length > 1) { out = new PrintStream(args[1]); } StormDeployer sd = new StormDeployer(); File stormFile = new File("/tmp/stormdeploy" + System.nanoTime()); sd.wget(new URL(args[0]), stormFile); //sd.wget(new URL("https://github.ugent.be/raw/sborny/StormDemo/master/StormDemo?token=AAAD4IP4Grwbg-8Em6hNhDyTSKXN5stEks5XB6USwA%3D%3D"), stormFile); for (Topology topology : sd.readTopologies(stormFile.getAbsolutePath())) { out.append("Deploying topology:" + topology.getName()); sd.deploy("/opt/storm/latest/bin/storm jar", topology, out, args[1]); } } }
src/main/java/com/ubuntu/stormdeployer/StormDeployer.java
/** * */ package com.ubuntu.stormdeployer; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.List; import org.apache.maven.cli.MavenCli; import org.yaml.snakeyaml.Loader; import org.yaml.snakeyaml.Yaml; /** * @author maarten Undeploy storm topologies */ public class StormDeployer { public void execute(String command, PrintStream log) throws Exception { Process p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { log.append(line + "\n"); } } finally { reader.close(); } } public void wget(URL url, File destination) throws Exception { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); rbc.close(); } public void git(String giturl, File directory, PrintStream out, String credentials) throws Exception { if (credentials.equals("")) { execute("git clone " + giturl + " " + directory.getAbsolutePath(), out); } else { String EersteDeel = giturl.split("//")[0]; String userenpass = "//" + credentials + "@"; String TweedeDeel = giturl.split("//")[1]; String git = EersteDeel + userenpass + TweedeDeel; execute("git clone " + git + " " + directory.getAbsolutePath(), out); } } public void deploy(String command, Topology topology, PrintStream out, String credentials) throws Exception { String name = topology.getName(); String jar = topology.getJar(); String packaging = topology.getPackaging(); String repo = topology.getRepository(); String topologyclass = topology.getTopologyclass(); String beforePackage = topology.getScriptbeforepackaging(); String beforeDeploy = topology.getScriptbeforedeploying(); List<DataSource> dss = topology.getDatasources(); String release = topology.getRelease(); String[] nameAndParams = name.split(" ", 2); // choise target folder File target = new File("/tmp/stormdeployertmp"); if (!target.exists()) { out.append("Creating /tmp/stormdeployertmp \n"); target.mkdir(); } //File topologyDir = new File(target.getAbsolutePath() + "/" + name.split(" ")[0]); File topologyDir = new File(target.getAbsolutePath() + "/" + nameAndParams[0]); // Did we deploy this topology already? if (!topologyDir.exists()) { out.append("Topology not yet deployed.\n"); topologyDir.mkdir(); //Check if source code or jar file if (packaging.equals("jar")) { out.append("Jar will be downloaded.\n"); URL url = new URL(release); try (InputStream inStream = url.openStream()) { System.out.println(inStream.available()); BufferedInputStream bufIn = new BufferedInputStream(inStream); File fileWrite = new File(topologyDir.getAbsolutePath() + "/" + jar); OutputStream outp = new FileOutputStream(fileWrite); BufferedOutputStream bufOut = new BufferedOutputStream(outp); byte buffer[] = new byte[1024]; while (true) { int nRead = bufIn.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } bufOut.write(buffer, 0, nRead); } bufOut.flush(); outp.close(); } if (nameAndParams.length > 1) { deploy(command, topologyDir.getAbsolutePath() + "/" + jar, topologyclass, nameAndParams[1], out); } else { deploy(command, topologyDir.getAbsolutePath() + "/" + jar, topologyclass, nameAndParams[0], out); } } else { out.append("Source code will be downloaded.\n"); // download source code from git git(repo, topologyDir, out, credentials); // Run before packaging script if (beforePackage != null) { out.append("Run before packaging script.\n"); File beforePackageDir = new File(topologyDir.getAbsolutePath() + "/package"); beforePackageDir.mkdir(); File packageScript = new File(beforePackageDir.getAbsolutePath() + "/script"); wget(new URL(beforePackage), packageScript); execute("chmod u+x " + packageScript.getAbsolutePath(), out); execute(packageScript.getAbsolutePath(), out); } if (dss != null) { out.append("Applying datasources.\n"); for (DataSource ds : dss) { applyDataSource(ds, topologyDir, out); } } // Todo implement alternative packaging and subdirectory support for Maven MavenCli cli = new MavenCli(); if(packaging.equals("mvn package")){ cli.doMain(new String[]{"package"}, topologyDir.getAbsolutePath(), out, out); }else{ cli.doMain(new String[]{packaging}, topologyDir.getAbsolutePath(), out, out); } // Run before deploying script if (beforeDeploy != null) { out.append("Running before deploy script.\n"); File beforeDeployDir = new File(topologyDir.getAbsolutePath() + "/deploy"); beforeDeployDir.mkdir(); File deployScript = new File(beforeDeployDir.getAbsolutePath() + "/script"); wget(new URL(beforeDeploy), deployScript); execute("chmod u+x " + deployScript.getAbsolutePath(), out); execute(deployScript.getAbsolutePath(), out); } // Deploy the topology if (nameAndParams.length > 1) { deploy(command, topologyDir.getAbsolutePath() + "/target/" + jar, topologyclass, nameAndParams[1], out); } else { deploy(command, topologyDir.getAbsolutePath() + "/target/" + jar, topologyclass, nameAndParams[0], out); } } } } public void applyDataSource(DataSource ds, File topologyDir, PrintStream out) throws Exception { List<Parameter> params = ds.getParameters(); String scriptURL = ds.getScript(); String type = ds.getType(); File dsdir = new File(topologyDir.getAbsolutePath() + "/datasources"); dsdir.mkdir(); File dir = new File(topologyDir.getAbsolutePath() + "/datasources/" + type); dir.mkdir(); File file = new File(topologyDir.getAbsolutePath() + "/datasources/" + type + "/script"); wget(new URL(scriptURL), file); execute("chmod u+x " + file, out); StringBuffer sb = new StringBuffer(); for (Parameter param : params) { sb.append(param.getName()); sb.append("="); sb.append(param.getValue()); sb.append(" "); } execute(file + " " + sb.toString(), out); } public void deploy(String deployment, String jar, String topologyClass, String topologyName, PrintStream out) throws Exception { out.append("Deploying:" + deployment + " " + jar + " " + topologyClass + " " + topologyName + "\n"); execute(deployment + " " + jar + " " + topologyClass + " " + topologyName, out); } public List<Topology> readTopologies(String file) throws Exception { StringBuffer deployer = new StringBuffer(); FileReader fr = new FileReader(file); BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(fr); while ((sCurrentLine = br.readLine()) != null) { //System.out.println(sCurrentLine); deployer.append(sCurrentLine); deployer.append("\n"); } } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { } } TopologiesConstructor constructor = new TopologiesConstructor(Topologies.class); Loader loader = new Loader(constructor); Yaml yaml = new Yaml(loader); Topologies topologies = (Topologies) yaml.load(deployer.toString()); return topologies.getTopology(); } /** * @param args * @throws Exception When deployment can not be done. */ public static void main(String[] args) throws Exception { if (args.length < 1) { throw new Exception("deployer file is missing. Usage: deployerURL (debugLogFile)"); } PrintStream out = System.out; if (args.length > 2) { out = new PrintStream(args[2]); } StormDeployer sd = new StormDeployer(); File stormFile = new File("/tmp/stormdeploy" + System.nanoTime()); sd.wget(new URL(args[0]), stormFile); //sd.wget(new URL("https://github.ugent.be/raw/sborny/StormDemo/master/StormDemo?token=AAAD4IP4Grwbg-8Em6hNhDyTSKXN5stEks5XB6USwA%3D%3D"), stormFile); for (Topology topology : sd.readTopologies(stormFile.getAbsolutePath())) { out.append("Deploying topology:" + topology.getName()); sd.deploy("/opt/storm/latest/bin/storm jar", topology, out, args[1]); } } }
Deployer fix
src/main/java/com/ubuntu/stormdeployer/StormDeployer.java
Deployer fix
<ide><path>rc/main/java/com/ubuntu/stormdeployer/StormDeployer.java <ide> PrintStream out = System.out; <ide> if (args.length > 2) { <ide> out = new PrintStream(args[2]); <add> }else if (args.length > 1) { <add> out = new PrintStream(args[1]); <ide> } <ide> <ide> StormDeployer sd = new StormDeployer();
Java
mit
b002c53f2f34d6ee6d36147a18c23cfc8746353b
0
bcgit/bc-java,open-keychain/spongycastle,partheinstein/bc-java,onessimofalconi/bc-java,savichris/spongycastle,sonork/spongycastle,sergeypayu/bc-java,isghe/bc-java,sonork/spongycastle,savichris/spongycastle,FAU-Inf2/spongycastle,iseki-masaya/spongycastle,FAU-Inf2/spongycastle,sergeypayu/bc-java,isghe/bc-java,Skywalker-11/spongycastle,Skywalker-11/spongycastle,Skywalker-11/spongycastle,iseki-masaya/spongycastle,lesstif/spongycastle,partheinstein/bc-java,onessimofalconi/bc-java,lesstif/spongycastle,isghe/bc-java,open-keychain/spongycastle,sonork/spongycastle,bcgit/bc-java,bcgit/bc-java,FAU-Inf2/spongycastle,partheinstein/bc-java,savichris/spongycastle,open-keychain/spongycastle,sergeypayu/bc-java,lesstif/spongycastle,onessimofalconi/bc-java,iseki-masaya/spongycastle
package org.bouncycastle.crypto.test; import org.bouncycastle.util.test.Test; import org.bouncycastle.util.test.TestResult; public class RegressionTest { public static Test[] tests = { new AESTest(), new AESLightTest(), new AESFastTest(), new AESWrapTest(), new AESWrapPadTest(), new DESTest(), new DESedeTest(), new ModeTest(), new PaddingTest(), new DHTest(), new ElGamalTest(), new DSATest(), new ECTest(), new DeterministicDSATest(), new GOST3410Test(), new ECGOST3410Test(), new ECIESTest(), new ECNRTest(), new MacTest(), new GOST28147MacTest(), new RC2Test(), new RC2WrapTest(), new RC4Test(), new RC5Test(), new RC6Test(), new RijndaelTest(), new SerpentTest(), new CamelliaTest(), new CamelliaLightTest(), new DigestRandomNumberTest(), new SkipjackTest(), new BlowfishTest(), new TwofishTest(), new Threefish256Test(), new Threefish512Test(), new Threefish1024Test(), new SkeinDigestTest(), new SkeinMacTest(), new CAST5Test(), new CAST6Test(), new GOST28147Test(), new IDEATest(), new RSATest(), new RSABlindedTest(), new RSADigestSignerTest(), new PSSBlindTest(), new ISO9796Test(), new ISO9797Alg3MacTest(), new MD2DigestTest(), new MD4DigestTest(), new MD5DigestTest(), new SHA1DigestTest(), new SHA224DigestTest(), new SHA256DigestTest(), new SHA384DigestTest(), new SHA512DigestTest(), new SHA512t224DigestTest(), new SHA512t256DigestTest(), new SHA3DigestTest(), new RIPEMD128DigestTest(), new RIPEMD160DigestTest(), new RIPEMD256DigestTest(), new RIPEMD320DigestTest(), new TigerDigestTest(), new GOST3411DigestTest(), new WhirlpoolDigestTest(), new MD5HMacTest(), new SHA1HMacTest(), new SHA224HMacTest(), new SHA256HMacTest(), new SHA384HMacTest(), new SHA512HMacTest(), new RIPEMD128HMacTest(), new RIPEMD160HMacTest(), new OAEPTest(), new PSSTest(), new CTSTest(), new CCMTest(), new PKCS5Test(), new PKCS12Test(), new KDF1GeneratorTest(), new KDF2GeneratorTest(), new MGF1GeneratorTest(), new HKDFGeneratorTest(), new DHKEKGeneratorTest(), new ECDHKEKGeneratorTest(), new ShortenedDigestTest(), new EqualsHashCodeTest(), new TEATest(), new XTEATest(), new RFC3211WrapTest(), new SEEDTest(), new Salsa20Test(), new XSalsa20Test(), new ChaChaTest(), new CMacTest(), new EAXTest(), new GCMTest(), new GMacTest(), new HCFamilyTest(), new HCFamilyVecTest(), new ISAACTest(), new NoekeonTest(), new VMPCKSA3Test(), new VMPCMacTest(), new VMPCTest(), new Grainv1Test(), new Grain128Test(), //new NaccacheSternTest(), new SRP6Test(), new SCryptTest(), new ResetTest(), new NullTest(), new DSTU4145Test(), new SipHashTest(), new Poly1305Test(), new OCBTest(), new NonMemoableDigestTest(), new RSAKeyEncapsulationTest(), new ECIESKeyEncapsulationTest(), new HashCommitmentTest(), new CipherStreamTest(), new BlockCipherResetTest(), new StreamCipherResetTest(), new SM3DigestTest(), new Shacal2Test(), new KDFCounterGeneratorTest(), new KDFDoublePipelineIteratorGeneratorTest(), new KDFFeedbackGeneratorTest(), new CramerShoupTest() }; public static void main( String[] args) { for (int i = 0; i != tests.length; i++) { TestResult result = tests[i].perform(); if (result.getException() != null) { result.getException().printStackTrace(); } System.out.println(result); } } }
core/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java
package org.bouncycastle.crypto.test; import org.bouncycastle.util.test.Test; import org.bouncycastle.util.test.TestResult; public class RegressionTest { public static Test[] tests = { new AESTest(), new AESLightTest(), new AESFastTest(), new AESWrapTest(), new AESWrapPadTest(), new DESTest(), new DESedeTest(), new ModeTest(), new PaddingTest(), new DHTest(), new ElGamalTest(), new DSATest(), new ECTest(), new DeterministicDSATest(), new GOST3410Test(), new ECGOST3410Test(), new ECIESTest(), new ECNRTest(), new MacTest(), new GOST28147MacTest(), new RC2Test(), new RC2WrapTest(), new RC4Test(), new RC5Test(), new RC6Test(), new RijndaelTest(), new SerpentTest(), new CamelliaTest(), new CamelliaLightTest(), new DigestRandomNumberTest(), new SkipjackTest(), new BlowfishTest(), new TwofishTest(), new Threefish256Test(), new Threefish512Test(), new Threefish1024Test(), new SkeinDigestTest(), new SkeinMacTest(), new CAST5Test(), new CAST6Test(), new GOST28147Test(), new IDEATest(), new RSATest(), new RSABlindedTest(), new RSADigestSignerTest(), new PSSBlindTest(), new ISO9796Test(), new ISO9797Alg3MacTest(), new MD2DigestTest(), new MD4DigestTest(), new MD5DigestTest(), new SHA1DigestTest(), new SHA224DigestTest(), new SHA256DigestTest(), new SHA384DigestTest(), new SHA512DigestTest(), new SHA512t224DigestTest(), new SHA512t256DigestTest(), new SHA3DigestTest(), new RIPEMD128DigestTest(), new RIPEMD160DigestTest(), new RIPEMD256DigestTest(), new RIPEMD320DigestTest(), new TigerDigestTest(), new GOST3411DigestTest(), new WhirlpoolDigestTest(), new MD5HMacTest(), new SHA1HMacTest(), new SHA224HMacTest(), new SHA256HMacTest(), new SHA384HMacTest(), new SHA512HMacTest(), new RIPEMD128HMacTest(), new RIPEMD160HMacTest(), new OAEPTest(), new PSSTest(), new CTSTest(), new CCMTest(), new PKCS5Test(), new PKCS12Test(), new KDF1GeneratorTest(), new KDF2GeneratorTest(), new MGF1GeneratorTest(), new HKDFGeneratorTest(), new DHKEKGeneratorTest(), new ECDHKEKGeneratorTest(), new ShortenedDigestTest(), new EqualsHashCodeTest(), new TEATest(), new XTEATest(), new RFC3211WrapTest(), new SEEDTest(), new Salsa20Test(), new XSalsa20Test(), new ChaChaTest(), new CMacTest(), new EAXTest(), new GCMTest(), new GMacTest(), new HCFamilyTest(), new HCFamilyVecTest(), new ISAACTest(), new NoekeonTest(), new VMPCKSA3Test(), new VMPCMacTest(), new VMPCTest(), new Grainv1Test(), new Grain128Test(), //new NaccacheSternTest(), new SRP6Test(), new SCryptTest(), new ResetTest(), new NullTest(), new DSTU4145Test(), new SipHashTest(), new Poly1305Test(), new OCBTest(), new NonMemoableDigestTest(), new RSAKeyEncapsulationTest(), new ECIESKeyEncapsulationTest(), new HashCommitmentTest(), new CipherStreamTest(), new BlockCipherResetTest(), new StreamCipherResetTest(), new SM3DigestTest(), new Shacal2Test(), new KDFCounterGeneratorTest(), new KDFDoublePipelineIteratorGeneratorTest(), new KDFFeedbackGeneratorTest() }; public static void main( String[] args) { for (int i = 0; i != tests.length; i++) { TestResult result = tests[i].perform(); if (result.getException() != null) { result.getException().printStackTrace(); } System.out.println(result); } } }
Include Cramer-Shoup tests
core/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java
Include Cramer-Shoup tests
<ide><path>ore/src/test/java/org/bouncycastle/crypto/test/RegressionTest.java <ide> new Shacal2Test(), <ide> new KDFCounterGeneratorTest(), <ide> new KDFDoublePipelineIteratorGeneratorTest(), <del> new KDFFeedbackGeneratorTest() <add> new KDFFeedbackGeneratorTest(), <add> new CramerShoupTest() <ide> }; <ide> <ide> public static void main(
JavaScript
mit
98fb2c90416f18a45757e3f439f4bfa81fc3da93
0
primus/primus,STRML/primus,primus/primus,STRML/primus,primus/primus,STRML/primus
(function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.eio=f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ module.exports = _dereq_('./socket'); /** * Exports parser * * @api public * */ module.exports.parser = _dereq_('engine.io-parser'); },{"./socket":2,"engine.io-parser":18}],2:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var transports = _dereq_('./transports/index'); var Emitter = _dereq_('component-emitter'); var debug = _dereq_('debug')('engine.io-client:socket'); var index = _dereq_('indexof'); var parser = _dereq_('engine.io-parser'); var parseuri = _dereq_('parseuri'); var parsejson = _dereq_('parsejson'); var parseqs = _dereq_('parseqs'); /** * Module exports. */ module.exports = Socket; /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket (uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' === location.protocol); if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.prevBufferLen = 0; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; this.forceNode = !!opts.forceNode; // other options for Node.js client var freeGlobal = typeof global === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } if (opts.localAddress) { this.localAddress = opts.localAddress; } } // set on handshake this.id = null; this.upgrades = null; this.pingInterval = null; this.pingTimeout = null; // set on heartbeat this.pingIntervalTimer = null; this.pingTimeoutTimer = null; this.open(); } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = _dereq_('./transport'); Socket.transports = _dereq_('./transports/index'); Socket.parser = _dereq_('engine.io-parser'); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, jsonp: this.jsonp, forceBase64: this.forceBase64, enablesXDR: this.enablesXDR, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, policyPort: this.policyPort, socket: this, pfx: this.pfx, key: this.key, passphrase: this.passphrase, cert: this.cert, ca: this.ca, ciphers: this.ciphers, rejectUnauthorized: this.rejectUnauthorized, perMessageDeflate: this.perMessageDeflate, extraHeaders: this.extraHeaders, forceNode: this.forceNode, localAddress: this.localAddress }); return transport; }; function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { transport = 'websocket'; } else if (0 === this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function () { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function (transport) { debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function () { self.onDrain(); }) .on('packet', function (packet) { self.onPacket(packet); }) .on('error', function (e) { self.onError(e); }) .on('close', function () { self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }); var failed = false; var self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen () { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport () { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } // Handle any error that happens while probing function onerror (err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose () { onerror('transport closed'); } // When the socket is closed while we're probing function onclose () { onerror('socket closed'); } // When the socket is upgraded while we're probing function onupgrade (to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } // Remove all listeners on the transport and on self function cleanup () { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open(); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' === this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); this.emit('pong'); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.onError(err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' === this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' === self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout)); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api private */ Socket.prototype.ping = function () { var self = this; this.sendPacket('ping', function () { self.emit('ping'); }); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function () { this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (0 === this.writeBuffer.length) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @param {Object} options. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, options, fn) { this.sendPacket('message', msg, options, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Object} options. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, options, fn) { if ('function' === typeof data) { fn = data; data = undefined; } if ('function' === typeof options) { fn = options; options = null; } if ('closing' === this.readyState || 'closed' === this.readyState) { return; } options = options || {}; options.compress = false !== options.compress; var packet = { type: type, data: data, options: options }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); if (fn) this.once('flush', fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.readyState = 'closing'; var self = this; if (this.writeBuffer.length) { this.once('drain', function () { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } function close () { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose () { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade () { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); // clean buffers after, so users can still // grab the buffers on `close` event self.writeBuffer = []; self.prevBufferLen = 0; } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i < j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./transport":3,"./transports/index":4,"component-emitter":14,"debug":16,"engine.io-parser":18,"indexof":22,"parsejson":25,"parseqs":26,"parseuri":27}],3:[function(_dereq_,module,exports){ /** * Module dependencies. */ var parser = _dereq_('engine.io-parser'); var Emitter = _dereq_('component-emitter'); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; this.forceNode = opts.forceNode; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.localAddress = opts.localAddress; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' === this.readyState || '' === this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function (packets) { if ('open' === this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function (data) { var packet = parser.decodePacket(data, this.socket.binaryType); this.onPacket(packet); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; },{"component-emitter":14,"engine.io-parser":18}],4:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies */ var XMLHttpRequest = _dereq_('xmlhttprequest-ssl'); var XHR = _dereq_('./polling-xhr'); var JSONP = _dereq_('./polling-jsonp'); var websocket = _dereq_('./websocket'); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling-jsonp":5,"./polling-xhr":6,"./websocket":8,"xmlhttprequest-ssl":9}],5:[function(_dereq_,module,exports){ (function (global){ /** * Module requirements. */ var Polling = _dereq_('./polling'); var inherit = _dereq_('component-inherit'); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; var rEscapedNewline = /\\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Noop. */ function empty () { } /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling (opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } } /** * Inherits from Polling. */ inherit(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket. * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; this.iframe = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function (e) { self.onError('jsonp poll error', e); }; var insertAt = document.getElementsByTagName('script')[0]; if (insertAt) { insertAt.parentNode.insertBefore(script, insertAt); } else { (document.head || document.body).appendChild(script); } this.script = script; var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); if (isUAgecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete () { initIframe(); fn(); } function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="' + self.iframeId + '">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; } initIframe(); // escape \n to prevent it from being converted into \r\n by some UAs // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side data = data.replace(rEscapedNewline, '\\\n'); this.area.value = data.replace(rNewline, '\\n'); try { this.form.submit(); } catch (e) {} if (this.iframe.attachEvent) { this.iframe.onreadystatechange = function () { if (self.iframe.readyState === 'complete') { complete(); } }; } else { this.iframe.onload = complete; } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling":7,"component-inherit":15}],6:[function(_dereq_,module,exports){ (function (global){ /** * Module requirements. */ var XMLHttpRequest = _dereq_('xmlhttprequest-ssl'); var Polling = _dereq_('./polling'); var Emitter = _dereq_('component-emitter'); var inherit = _dereq_('component-inherit'); var debug = _dereq_('debug')('engine.io-client:polling-xhr'); /** * Module exports. */ module.exports = XHR; module.exports.Request = Request; /** * Empty function */ function empty () {} /** * XHR Polling constructor. * * @param {Object} opts * @api public */ function XHR (opts) { Polling.call(this, opts); this.requestTimeout = opts.requestTimeout; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname !== global.location.hostname || port !== opts.port; this.xs = opts.secure !== isSSL; } else { this.extraHeaders = opts.extraHeaders; } } /** * Inherits from Polling. */ inherit(XHR, Polling); /** * XHR supports binary */ XHR.prototype.supportsBinary = true; /** * Creates a request. * * @param {String} method * @api private */ XHR.prototype.request = function (opts) { opts = opts || {}; opts.uri = this.uri(); opts.xd = this.xd; opts.xs = this.xs; opts.agent = this.agent || false; opts.supportsBinary = this.supportsBinary; opts.enablesXDR = this.enablesXDR; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; opts.requestTimeout = this.requestTimeout; // other options for Node.js client opts.extraHeaders = this.extraHeaders; return new Request(opts); }; /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @api private */ XHR.prototype.doWrite = function (data, fn) { var isBinary = typeof data !== 'string' && data !== undefined; var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); var self = this; req.on('success', fn); req.on('error', function (err) { self.onError('xhr post error', err); }); this.sendXhr = req; }; /** * Starts a poll cycle. * * @api private */ XHR.prototype.doPoll = function () { debug('xhr poll'); var req = this.request(); var self = this; req.on('data', function (data) { self.onData(data); }); req.on('error', function (err) { self.onError('xhr poll error', err); }); this.pollXhr = req; }; /** * Request constructor * * @param {Object} options * @api public */ function Request (opts) { this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.xs = !!opts.xs; this.async = false !== opts.async; this.data = undefined !== opts.data ? opts.data : null; this.agent = opts.agent; this.isBinary = opts.isBinary; this.supportsBinary = opts.supportsBinary; this.enablesXDR = opts.enablesXDR; this.requestTimeout = opts.requestTimeout; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.create(); } /** * Mix in `Emitter`. */ Emitter(Request.prototype); /** * Creates the XHR object and sends the request. * * @api private */ Request.prototype.create = function () { var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; var xhr = this.xhr = new XMLHttpRequest(opts); var self = this; try { debug('xhr open %s: %s', this.method, this.uri); xhr.open(this.method, this.uri, this.async); try { if (this.extraHeaders) { xhr.setDisableHeaderCheck(true); for (var i in this.extraHeaders) { if (this.extraHeaders.hasOwnProperty(i)) { xhr.setRequestHeader(i, this.extraHeaders[i]); } } } } catch (e) {} if (this.supportsBinary) { // This has to be done after open because Firefox is stupid // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension xhr.responseType = 'arraybuffer'; } if ('POST' === this.method) { try { if (this.isBinary) { xhr.setRequestHeader('Content-type', 'application/octet-stream'); } else { xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); } } catch (e) {} } try { xhr.setRequestHeader('Accept', '*/*'); } catch (e) {} // ie6 check if ('withCredentials' in xhr) { xhr.withCredentials = true; } if (this.requestTimeout) { xhr.timeout = this.requestTimeout; } if (this.hasXDR()) { xhr.onload = function () { self.onLoad(); }; xhr.onerror = function () { self.onError(xhr.responseText); }; } else { xhr.onreadystatechange = function () { if (4 !== xhr.readyState) return; if (200 === xhr.status || 1223 === xhr.status) { self.onLoad(); } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here setTimeout(function () { self.onError(xhr.status); }, 0); } }; } debug('xhr data %s', this.data); xhr.send(this.data); } catch (e) { // Need to defer since .create() is called directly fhrom the constructor // and thus the 'error' event can only be only bound *after* this exception // occurs. Therefore, also, we cannot throw here at all. setTimeout(function () { self.onError(e); }, 0); return; } if (global.document) { this.index = Request.requestsCount++; Request.requests[this.index] = this; } }; /** * Called upon successful response. * * @api private */ Request.prototype.onSuccess = function () { this.emit('success'); this.cleanup(); }; /** * Called if we have data. * * @api private */ Request.prototype.onData = function (data) { this.emit('data', data); this.onSuccess(); }; /** * Called upon error. * * @api private */ Request.prototype.onError = function (err) { this.emit('error', err); this.cleanup(true); }; /** * Cleans up house. * * @api private */ Request.prototype.cleanup = function (fromError) { if ('undefined' === typeof this.xhr || null === this.xhr) { return; } // xmlhttprequest if (this.hasXDR()) { this.xhr.onload = this.xhr.onerror = empty; } else { this.xhr.onreadystatechange = empty; } if (fromError) { try { this.xhr.abort(); } catch (e) {} } if (global.document) { delete Request.requests[this.index]; } this.xhr = null; }; /** * Called upon load. * * @api private */ Request.prototype.onLoad = function () { var data; try { var contentType; try { contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0]; } catch (e) {} if (contentType === 'application/octet-stream') { data = this.xhr.response || this.xhr.responseText; } else { if (!this.supportsBinary) { data = this.xhr.responseText; } else { try { data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response)); } catch (e) { var ui8Arr = new Uint8Array(this.xhr.response); var dataArray = []; for (var idx = 0, length = ui8Arr.length; idx < length; idx++) { dataArray.push(ui8Arr[idx]); } data = String.fromCharCode.apply(null, dataArray); } } } } catch (e) { this.onError(e); } if (null != data) { this.onData(data); } }; /** * Check if it has XDomainRequest. * * @api private */ Request.prototype.hasXDR = function () { return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; }; /** * Aborts the request. * * @api public */ Request.prototype.abort = function () { this.cleanup(); }; /** * Aborts pending requests when unloading the window. This is needed to prevent * memory leaks (e.g. when using IE) and to ensure that no spurious error is * emitted. */ Request.requestsCount = 0; Request.requests = {}; if (global.document) { if (global.attachEvent) { global.attachEvent('onunload', unloadHandler); } else if (global.addEventListener) { global.addEventListener('beforeunload', unloadHandler, false); } } function unloadHandler () { for (var i in Request.requests) { if (Request.requests.hasOwnProperty(i)) { Request.requests[i].abort(); } } } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling":7,"component-emitter":14,"component-inherit":15,"debug":16,"xmlhttprequest-ssl":9}],7:[function(_dereq_,module,exports){ /** * Module dependencies. */ var Transport = _dereq_('../transport'); var parseqs = _dereq_('parseqs'); var parser = _dereq_('engine.io-parser'); var inherit = _dereq_('component-inherit'); var yeast = _dereq_('yeast'); var debug = _dereq_('debug')('engine.io-client:polling'); /** * Module exports. */ module.exports = Polling; /** * Is XHR2 supported? */ var hasXHR2 = (function () { var XMLHttpRequest = _dereq_('xmlhttprequest-ssl'); var xhr = new XMLHttpRequest({ xdomain: false }); return null != xhr.responseType; })(); /** * Polling interface. * * @param {Object} opts * @api private */ function Polling (opts) { var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(Polling, Transport); /** * Transport name. */ Polling.prototype.name = 'polling'; /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @api private */ Polling.prototype.doOpen = function () { this.poll(); }; /** * Pauses polling. * * @param {Function} callback upon buffers are flushed and transport is paused * @api private */ Polling.prototype.pause = function (onPause) { var self = this; this.readyState = 'pausing'; function pause () { debug('paused'); self.readyState = 'paused'; onPause(); } if (this.polling || !this.writable) { var total = 0; if (this.polling) { debug('we are currently polling - waiting to pause'); total++; this.once('pollComplete', function () { debug('pre-pause polling complete'); --total || pause(); }); } if (!this.writable) { debug('we are currently writing - waiting to pause'); total++; this.once('drain', function () { debug('pre-pause writing complete'); --total || pause(); }); } } else { pause(); } }; /** * Starts polling cycle. * * @api public */ Polling.prototype.poll = function () { debug('polling'); this.polling = true; this.doPoll(); this.emit('poll'); }; /** * Overloads onData to detect payloads. * * @api private */ Polling.prototype.onData = function (data) { var self = this; debug('polling got data %s', data); var callback = function (packet, index, total) { // if its the first message we consider the transport open if ('opening' === self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' === packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }; // decode payload parser.decodePayload(data, this.socket.binaryType, callback); // if an event did not trigger closing if ('closed' !== this.readyState) { // if we got data we're not polling this.polling = false; this.emit('pollComplete'); if ('open' === this.readyState) { this.poll(); } else { debug('ignoring poll - transport state "%s"', this.readyState); } } }; /** * For polling, send a close packet. * * @api private */ Polling.prototype.doClose = function () { var self = this; function close () { debug('writing close packet'); self.write([{ type: 'close' }]); } if ('open' === this.readyState) { debug('transport open - closing'); close(); } else { // in case we're trying to close while // handshaking is in progress (GH-164) debug('transport not open - deferring close'); this.once('open', close); } }; /** * Writes a packets payload. * * @param {Array} data packets * @param {Function} drain callback * @api private */ Polling.prototype.write = function (packets) { var self = this; this.writable = false; var callbackfn = function () { self.writable = true; self.emit('drain'); }; parser.encodePayload(packets, this.supportsBinary, function (data) { self.doWrite(data, callbackfn); }); }; /** * Generates uri for connection. * * @api private */ Polling.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'https' : 'http'; var port = ''; // cache busting is forced if (false !== this.timestampRequests) { query[this.timestampParam] = yeast(); } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } query = parseqs.encode(query); // avoid port if default for schema if (this.port && (('https' === schema && Number(this.port) !== 443) || ('http' === schema && Number(this.port) !== 80))) { port = ':' + this.port; } // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; },{"../transport":3,"component-inherit":15,"debug":16,"engine.io-parser":18,"parseqs":26,"xmlhttprequest-ssl":9,"yeast":29}],8:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var Transport = _dereq_('../transport'); var parser = _dereq_('engine.io-parser'); var parseqs = _dereq_('parseqs'); var inherit = _dereq_('component-inherit'); var yeast = _dereq_('yeast'); var debug = _dereq_('debug')('engine.io-client:websocket'); var BrowserWebSocket = global.WebSocket || global.MozWebSocket; var NodeWebSocket; if (typeof window === 'undefined') { try { NodeWebSocket = _dereq_('ws'); } catch (e) { } } /** * Get either the `WebSocket` or `MozWebSocket` globals * in the browser or try to resolve WebSocket-compatible * interface exposed by `ws` for Node-like environment. */ var WebSocket = BrowserWebSocket; if (!WebSocket && typeof window === 'undefined') { WebSocket = NodeWebSocket; } /** * Module exports. */ module.exports = WS; /** * WebSocket transport constructor. * * @api {Object} connection options * @api public */ function WS (opts) { var forceBase64 = (opts && opts.forceBase64); if (forceBase64) { this.supportsBinary = false; } this.perMessageDeflate = opts.perMessageDeflate; this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode; if (!this.usingBrowserWebSocket) { WebSocket = NodeWebSocket; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(WS, Transport); /** * Transport name. * * @api public */ WS.prototype.name = 'websocket'; /* * WebSockets support binary */ WS.prototype.supportsBinary = true; /** * Opens socket. * * @api private */ WS.prototype.doOpen = function () { if (!this.check()) { // let probe timeout return; } var uri = this.uri(); var protocols = void (0); var opts = { agent: this.agent, perMessageDeflate: this.perMessageDeflate }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; if (this.extraHeaders) { opts.headers = this.extraHeaders; } if (this.localAddress) { opts.localAddress = this.localAddress; } try { this.ws = this.usingBrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts); } catch (err) { return this.emit('error', err); } if (this.ws.binaryType === undefined) { this.supportsBinary = false; } if (this.ws.supports && this.ws.supports.binary) { this.supportsBinary = true; this.ws.binaryType = 'nodebuffer'; } else { this.ws.binaryType = 'arraybuffer'; } this.addEventListeners(); }; /** * Adds event listeners to the socket * * @api private */ WS.prototype.addEventListeners = function () { var self = this; this.ws.onopen = function () { self.onOpen(); }; this.ws.onclose = function () { self.onClose(); }; this.ws.onmessage = function (ev) { self.onData(ev.data); }; this.ws.onerror = function (e) { self.onError('websocket error', e); }; }; /** * Writes data to socket. * * @param {Array} array of packets. * @api private */ WS.prototype.write = function (packets) { var self = this; this.writable = false; // encodePacket efficient as it uses WS framing // no need for encodePayload var total = packets.length; for (var i = 0, l = total; i < l; i++) { (function (packet) { parser.encodePacket(packet, self.supportsBinary, function (data) { if (!self.usingBrowserWebSocket) { // always create a new object (GH-437) var opts = {}; if (packet.options) { opts.compress = packet.options.compress; } if (self.perMessageDeflate) { var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length; if (len < self.perMessageDeflate.threshold) { opts.compress = false; } } } // Sometimes the websocket has already been closed but the browser didn't // have a chance of informing us about it yet, in that case send will // throw an error try { if (self.usingBrowserWebSocket) { // TypeError is thrown when passing the second argument on Safari self.ws.send(data); } else { self.ws.send(data, opts); } } catch (e) { debug('websocket closed before onclose event'); } --total || done(); }); })(packets[i]); } function done () { self.emit('flush'); // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(function () { self.writable = true; self.emit('drain'); }, 0); } }; /** * Called upon close * * @api private */ WS.prototype.onClose = function () { Transport.prototype.onClose.call(this); }; /** * Closes socket. * * @api private */ WS.prototype.doClose = function () { if (typeof this.ws !== 'undefined') { this.ws.close(); } }; /** * Generates uri for connection. * * @api private */ WS.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'wss' : 'ws'; var port = ''; // avoid port if default for schema if (this.port && (('wss' === schema && Number(this.port) !== 443) || ('ws' === schema && Number(this.port) !== 80))) { port = ':' + this.port; } // append timestamp to URI if (this.timestampRequests) { query[this.timestampParam] = yeast(); } // communicate binary support capabilities if (!this.supportsBinary) { query.b64 = 1; } query = parseqs.encode(query); // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; /** * Feature detection for WebSocket. * * @return {Boolean} whether this transport is available. * @api public */ WS.prototype.check = function () { return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../transport":3,"component-inherit":15,"debug":16,"engine.io-parser":18,"parseqs":26,"ws":undefined,"yeast":29}],9:[function(_dereq_,module,exports){ (function (global){ // browser shim for xmlhttprequest module var hasCORS = _dereq_('has-cors'); module.exports = function (opts) { var xdomain = opts.xdomain; // scheme must be same when usign XDomainRequest // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx var xscheme = opts.xscheme; // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. // https://github.com/Automattic/engine.io-client/pull/217 var enablesXDR = opts.enablesXDR; // XMLHttpRequest can be disabled on IE try { if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { return new XMLHttpRequest(); } } catch (e) { } // Use XDomainRequest for IE8 if enablesXDR is true // because loading bar keeps flashing when using jsonp-polling // https://github.com/yujiosaka/socke.io-ie8-loading-example try { if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) { return new XDomainRequest(); } } catch (e) { } if (!xdomain) { try { return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP'); } catch (e) { } } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"has-cors":21}],10:[function(_dereq_,module,exports){ module.exports = after function after(count, callback, err_cb) { var bail = false err_cb = err_cb || noop proxy.count = count return (count === 0) ? callback() : proxy function proxy(err, result) { if (proxy.count <= 0) { throw new Error('after called too many times') } --proxy.count // after first error, rest are passed to err_cb if (err) { bail = true callback(err) // future error callbacks will go to error handler callback = err_cb } else if (proxy.count === 0 && !bail) { callback(null, result) } } } function noop() {} },{}],11:[function(_dereq_,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported * * @api public */ module.exports = function(arraybuffer, start, end) { var bytes = arraybuffer.byteLength; start = start || 0; end = end || bytes; if (arraybuffer.slice) { return arraybuffer.slice(start, end); } if (start < 0) { start += bytes; } if (end < 0) { end += bytes; } if (end > bytes) { end = bytes; } if (start >= bytes || start >= end || bytes === 0) { return new ArrayBuffer(0); } var abv = new Uint8Array(arraybuffer); var result = new Uint8Array(end - start); for (var i = start, ii = 0; i < end; i++, ii++) { result[ii] = abv[i]; } return result.buffer; }; },{}],12:[function(_dereq_,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(){ "use strict"; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Use a lookup table to find the index. var lookup = new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i+1)]; encoded3 = lookup[base64.charCodeAt(i+2)]; encoded4 = lookup[base64.charCodeAt(i+3)]; bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })(); },{}],13:[function(_dereq_,module,exports){ (function (global){ /** * Create a blob builder even when vendor prefixes exist */ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder; /** * Check if Blob constructor is supported */ var blobSupported = (function() { try { var a = new Blob(['hi']); return a.size === 2; } catch(e) { return false; } })(); /** * Check if Blob constructor supports ArrayBufferViews * Fails in Safari 6, so we need to map to ArrayBuffers there. */ var blobSupportsArrayBufferView = blobSupported && (function() { try { var b = new Blob([new Uint8Array([1,2])]); return b.size === 2; } catch(e) { return false; } })(); /** * Check if BlobBuilder is supported */ var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob; /** * Helper function that maps ArrayBufferViews to ArrayBuffers * Used by BlobBuilder constructor and old browsers that didn't * support it in the Blob constructor. */ function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } } function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); mapArrayBufferViews(ary); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }; function BlobConstructor(ary, options) { mapArrayBufferViews(ary); return new Blob(ary, options || {}); }; module.exports = (function() { if (blobSupported) { return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; } else if (blobBuilderSupported) { return BlobBuilderConstructor; } else { return undefined; } })(); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],14:[function(_dereq_,module,exports){ /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],15:[function(_dereq_,module,exports){ module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; },{}],16:[function(_dereq_,module,exports){ (function (process){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = _dereq_('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } }).call(this,_dereq_('_process')) },{"./debug":17,"_process":undefined}],17:[function(_dereq_,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = _dereq_('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":24}],18:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var keys = _dereq_('./keys'); var hasBinary = _dereq_('has-binary'); var sliceBuffer = _dereq_('arraybuffer.slice'); var after = _dereq_('after'); var utf8 = _dereq_('wtf-8'); var base64encoder; if (global && global.ArrayBuffer) { base64encoder = _dereq_('base64-arraybuffer'); } /** * Check if we are running an android browser. That requires us to use * ArrayBuffer with polling transports... * * http://ghinda.net/jpeg-blob-ajax-android/ */ var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); /** * Check if we are running in PhantomJS. * Uploading a Blob with PhantomJS does not work correctly, as reported here: * https://github.com/ariya/phantomjs/issues/11395 * @type boolean */ var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); /** * When true, avoids using Blobs to encode payloads. * @type boolean */ var dontSendBlobs = isAndroid || isPhantomJS; /** * Current protocol version. */ exports.protocol = 3; /** * Packet types. */ var packets = exports.packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; /** * Create a blob api even for blob builder when vendor prefixes exist */ var Blob = _dereq_('blob'); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { if ('function' == typeof supportsBinary) { callback = supportsBinary; supportsBinary = false; } if ('function' == typeof utf8encode) { callback = utf8encode; utf8encode = null; } var data = (packet.data === undefined) ? undefined : packet.data.buffer || packet.data; if (global.ArrayBuffer && data instanceof ArrayBuffer) { return encodeArrayBuffer(packet, supportsBinary, callback); } else if (Blob && data instanceof global.Blob) { return encodeBlob(packet, supportsBinary, callback); } // might be an object with { base64: true, data: dataAsBase64String } if (data && data.base64) { return encodeBase64Object(packet, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data); } return callback('' + encoded); }; function encodeBase64Object(packet, callback) { // packet data is an object { base64: true, data: dataAsBase64String } var message = 'b' + exports.packets[packet.type] + packet.data.data; return callback(message); } /** * Encode packet helpers for binary types */ function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); } function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, true, callback); }; return fr.readAsArrayBuffer(packet.data); } function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (dontSendBlobs) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ exports.encodeBase64Packet = function(packet, callback) { var message = 'b' + exports.packets[packet.type]; if (Blob && packet.data instanceof global.Blob) { var fr = new FileReader(); fr.onload = function() { var b64 = fr.result.split(',')[1]; callback(message + b64); }; return fr.readAsDataURL(packet.data); } var b64data; try { b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); } catch (e) { // iPhone Safari doesn't let you apply with typed arrays var typed = new Uint8Array(packet.data); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } b64data = String.fromCharCode.apply(null, basic); } message += global.btoa(b64data); return callback(message); }; /** * Decodes a packet. Changes format to Blob if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ exports.decodePacket = function (data, binaryType, utf8decode) { if (data === undefined) { return err; } // String data if (typeof data == 'string') { if (data.charAt(0) == 'b') { return exports.decodeBase64Packet(data.substr(1), binaryType); } if (utf8decode) { data = tryDecode(data); if (data === false) { return err; } } var type = data.charAt(0); if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } var asArray = new Uint8Array(data); var type = asArray[0]; var rest = sliceBuffer(data, 1); if (Blob && binaryType === 'blob') { rest = new Blob([rest]); } return { type: packetslist[type], data: rest }; }; function tryDecode(data) { try { data = utf8.decode(data); } catch (e) { return false; } return data; } /** * Decodes a packet encoded in a base64 string * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ exports.decodeBase64Packet = function(msg, binaryType) { var type = packetslist[msg.charAt(0)]; if (!base64encoder) { return { type: type, data: { base64: true, data: msg.substr(1) } }; } var data = base64encoder.decode(msg.substr(1)); if (binaryType === 'blob' && Blob) { data = new Blob([data]); } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ exports.encodePayload = function (packets, supportsBinary, callback) { if (typeof supportsBinary == 'function') { callback = supportsBinary; supportsBinary = null; } var isBinary = hasBinary(packets); if (supportsBinary && isBinary) { if (Blob && !dontSendBlobs) { return exports.encodePayloadAsBlob(packets, callback); } return exports.encodePayloadAsArrayBuffer(packets, callback); } if (!packets.length) { return callback('0:'); } function setLengthHeader(message) { return message.length + ':' + message; } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; /** * Async array map using after */ function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); var eachWithIndex = function(i, el, cb) { each(el, function(error, msg) { result[i] = msg; cb(error, result); }); }; for (var i = 0; i < ary.length; i++) { eachWithIndex(i, ary[i], next); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ exports.decodePayload = function (data, binaryType, callback) { if (typeof data != 'string') { return exports.decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var packet; if (data == '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '' , n, msg; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (':' != chr) { length += chr; } else { if ('' == length || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = exports.decodePacket(msg, binaryType, true); if (err.type == packet.type && err.data == packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var ret = callback(packet, i + n, l); if (false === ret) return; } // advance cursor i += n; length = ''; } } if (length != '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {ArrayBuffer} encoded payload * @api private */ exports.encodePayloadAsArrayBuffer = function(packets, callback) { if (!packets.length) { return callback(new ArrayBuffer(0)); } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(data) { return doneCallback(null, data); }); } map(packets, encodeOne, function(err, encodedPackets) { var totalLength = encodedPackets.reduce(function(acc, p) { var len; if (typeof p === 'string'){ len = p.length; } else { len = p.byteLength; } return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 }, 0); var resultArray = new Uint8Array(totalLength); var bufferIndex = 0; encodedPackets.forEach(function(p) { var isString = typeof p === 'string'; var ab = p; if (isString) { var view = new Uint8Array(p.length); for (var i = 0; i < p.length; i++) { view[i] = p.charCodeAt(i); } ab = view.buffer; } if (isString) { // not true binary resultArray[bufferIndex++] = 0; } else { // true binary resultArray[bufferIndex++] = 1; } var lenStr = ab.byteLength.toString(); for (var i = 0; i < lenStr.length; i++) { resultArray[bufferIndex++] = parseInt(lenStr[i]); } resultArray[bufferIndex++] = 255; var view = new Uint8Array(ab); for (var i = 0; i < view.length; i++) { resultArray[bufferIndex++] = view[i]; } }); return callback(resultArray.buffer); }); }; /** * Encode as Blob */ exports.encodePayloadAsBlob = function(packets, callback) { function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(encoded) { var binaryIdentifier = new Uint8Array(1); binaryIdentifier[0] = 1; if (typeof encoded === 'string') { var view = new Uint8Array(encoded.length); for (var i = 0; i < encoded.length; i++) { view[i] = encoded.charCodeAt(i); } encoded = view.buffer; binaryIdentifier[0] = 0; } var len = (encoded instanceof ArrayBuffer) ? encoded.byteLength : encoded.size; var lenStr = len.toString(); var lengthAry = new Uint8Array(lenStr.length + 1); for (var i = 0; i < lenStr.length; i++) { lengthAry[i] = parseInt(lenStr[i]); } lengthAry[lenStr.length] = 255; if (Blob) { var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); doneCallback(null, blob); } }); } map(packets, encodeOne, function(err, results) { return callback(new Blob(results)); }); }; /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * * @param {ArrayBuffer} data, callback method * @api public */ exports.decodePayloadAsBinary = function (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; var numberTooLong = false; while (bufferTail.byteLength > 0) { var tailArray = new Uint8Array(bufferTail); var isString = tailArray[0] === 0; var msgLength = ''; for (var i = 1; ; i++) { if (tailArray[i] == 255) break; if (msgLength.length > 310) { numberTooLong = true; break; } msgLength += tailArray[i]; } if(numberTooLong) return callback(err, 0, 1); bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); msgLength = parseInt(msgLength); var msg = sliceBuffer(bufferTail, 0, msgLength); if (isString) { try { msg = String.fromCharCode.apply(null, new Uint8Array(msg)); } catch (e) { // iPhone Safari doesn't let you apply to typed arrays var typed = new Uint8Array(msg); msg = ''; for (var i = 0; i < typed.length; i++) { msg += String.fromCharCode(typed[i]); } } } buffers.push(msg); bufferTail = sliceBuffer(bufferTail, msgLength); } var total = buffers.length; buffers.forEach(function(buffer, i) { callback(exports.decodePacket(buffer, binaryType, true), i, total); }); }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./keys":19,"after":10,"arraybuffer.slice":11,"base64-arraybuffer":12,"blob":13,"has-binary":20,"wtf-8":28}],19:[function(_dereq_,module,exports){ /** * Gets the keys for an object. * * @return {Array} keys * @api private */ module.exports = Object.keys || function keys (obj){ var arr = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { arr.push(i); } } return arr; }; },{}],20:[function(_dereq_,module,exports){ (function (global){ /* * Module requirements. */ var isArray = _dereq_('isarray'); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && 'function' == typeof obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"isarray":23}],21:[function(_dereq_,module,exports){ /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } },{}],22:[function(_dereq_,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],23:[function(_dereq_,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],24:[function(_dereq_,module,exports){ /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } },{}],25:[function(_dereq_,module,exports){ (function (global){ /** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 * @api private */ var rvalidchars = /^[\],:{}\s]*$/; var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; var rtrimLeft = /^\s+/; var rtrimRight = /\s+$/; module.exports = function parsejson(data) { if ('string' != typeof data || !data) { return null; } data = data.replace(rtrimLeft, '').replace(rtrimRight, ''); // Attempt to parse using the native JSON parser first if (global.JSON && JSON.parse) { return JSON.parse(data); } if (rvalidchars.test(data.replace(rvalidescape, '@') .replace(rvalidtokens, ']') .replace(rvalidbraces, ''))) { return (new Function('return ' + data))(); } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],26:[function(_dereq_,module,exports){ /** * Compiles a querystring * Returns string representation of the object * * @param {Object} * @api private */ exports.encode = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring into an object * * @param {String} qs * @api private */ exports.decode = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; },{}],27:[function(_dereq_,module,exports){ /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var src = str, b = str.indexOf('['), e = str.indexOf(']'); if (b != -1 && e != -1) { str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); } var m = re.exec(str || ''), uri = {}, i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } if (b != -1 && e != -1) { uri.source = src; uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); uri.ipv6uri = true; } return uri; }; },{}],28:[function(_dereq_,module,exports){ (function (global){ /*! https://mths.be/wtf8 v1.0.0 by @mathias */ ;(function(root) { // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var stringFromCharCode = String.fromCharCode; // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; var value; var extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; var index = -1; var value; var output = ''; while (++index < length) { value = array[index]; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); } return output; } /*--------------------------------------------------------------------------*/ function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } function encodeCodePoint(codePoint) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); } var symbol = ''; if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); symbol += createByte(codePoint, 6); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); symbol += createByte(codePoint, 12); symbol += createByte(codePoint, 6); } symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } function wtf8encode(string) { var codePoints = ucs2decode(string); var length = codePoints.length; var index = -1; var codePoint; var byteString = ''; while (++index < length) { codePoint = codePoints[index]; byteString += encodeCodePoint(codePoint); } return byteString; } /*--------------------------------------------------------------------------*/ function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } // If we end up here, it’s not a continuation byte. throw Error('Invalid continuation byte'); } function decodeSymbol() { var byte1; var byte2; var byte3; var byte4; var codePoint; if (byteIndex > byteCount) { throw Error('Invalid byte index'); } if (byteIndex == byteCount) { return false; } // Read the first byte. byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { var byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; if (codePoint >= 0x0800) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; } } throw Error('Invalid WTF-8 detected'); } var byteArray; var byteCount; var byteIndex; function wtf8decode(byteString) { byteArray = ucs2decode(byteString); byteCount = byteArray.length; byteIndex = 0; var codePoints = []; var tmp; while ((tmp = decodeSymbol()) !== false) { codePoints.push(tmp); } return ucs2encode(codePoints); } /*--------------------------------------------------------------------------*/ var wtf8 = { 'version': '1.0.0', 'encode': wtf8encode, 'decode': wtf8decode }; if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = wtf8; } else { // in Narwhal or RingoJS v0.7.0- var object = {}; var hasOwnProperty = object.hasOwnProperty; for (var key in wtf8) { hasOwnProperty.call(wtf8, key) && (freeExports[key] = wtf8[key]); } } } else { // in Rhino or a web browser root.wtf8 = wtf8; } }(this)); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],29:[function(_dereq_,module,exports){ 'use strict'; var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') , length = 64 , map = {} , seed = 0 , i = 0 , prev; /** * Return a string representing the specified number. * * @param {Number} num The number to convert. * @returns {String} The string representation of the number. * @api public */ function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; } /** * Return the integer value specified by the given string. * * @param {String} str The string to convert. * @returns {Number} The integer value represented by the string. * @api public */ function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; } /** * Yeast: A tiny growing id generator. * * @returns {String} A unique id. * @api public */ function yeast() { var now = encode(+new Date()); if (now !== prev) return seed = 0, prev = now; return now +'.'+ encode(seed++); } // // Map each character to its index. // for (; i < length; i++) map[alphabet[i]] = i; // // Expose the `yeast`, `encode` and `decode` functions. // yeast.encode = encode; yeast.decode = decode; module.exports = yeast; },{}],30:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib/index'); },{"./lib/index":1}]},{},[30])(30) });
transformers/engine.io/library.js
(function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.eio=f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ module.exports = _dereq_('./socket'); /** * Exports parser * * @api public * */ module.exports.parser = _dereq_('engine.io-parser'); },{"./socket":2,"engine.io-parser":18}],2:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var transports = _dereq_('./transports/index'); var Emitter = _dereq_('component-emitter'); var debug = _dereq_('debug')('engine.io-client:socket'); var index = _dereq_('indexof'); var parser = _dereq_('engine.io-parser'); var parseuri = _dereq_('parseuri'); var parsejson = _dereq_('parsejson'); var parseqs = _dereq_('parseqs'); /** * Module exports. */ module.exports = Socket; /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket (uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' === location.protocol); if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.prevBufferLen = 0; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; this.forceNode = !!opts.forceNode; // other options for Node.js client var freeGlobal = typeof global === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } if (opts.localAddress) { this.localAddress = opts.localAddress; } } // set on handshake this.id = null; this.upgrades = null; this.pingInterval = null; this.pingTimeout = null; // set on heartbeat this.pingIntervalTimer = null; this.pingTimeoutTimer = null; this.open(); } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = _dereq_('./transport'); Socket.transports = _dereq_('./transports/index'); Socket.parser = _dereq_('engine.io-parser'); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, jsonp: this.jsonp, forceBase64: this.forceBase64, enablesXDR: this.enablesXDR, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, policyPort: this.policyPort, socket: this, pfx: this.pfx, key: this.key, passphrase: this.passphrase, cert: this.cert, ca: this.ca, ciphers: this.ciphers, rejectUnauthorized: this.rejectUnauthorized, perMessageDeflate: this.perMessageDeflate, extraHeaders: this.extraHeaders, forceNode: this.forceNode, localAddress: this.localAddress }); return transport; }; function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { transport = 'websocket'; } else if (0 === this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function () { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function (transport) { debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function () { self.onDrain(); }) .on('packet', function (packet) { self.onPacket(packet); }) .on('error', function (e) { self.onError(e); }) .on('close', function () { self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }); var failed = false; var self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen () { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport () { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } // Handle any error that happens while probing function onerror (err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose () { onerror('transport closed'); } // When the socket is closed while we're probing function onclose () { onerror('socket closed'); } // When the socket is upgraded while we're probing function onupgrade (to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } // Remove all listeners on the transport and on self function cleanup () { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open(); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' === this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); this.emit('pong'); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.onError(err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' === this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' === self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout)); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api private */ Socket.prototype.ping = function () { var self = this; this.sendPacket('ping', function () { self.emit('ping'); }); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function () { this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (0 === this.writeBuffer.length) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @param {Object} options. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, options, fn) { this.sendPacket('message', msg, options, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Object} options. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, options, fn) { if ('function' === typeof data) { fn = data; data = undefined; } if ('function' === typeof options) { fn = options; options = null; } if ('closing' === this.readyState || 'closed' === this.readyState) { return; } options = options || {}; options.compress = false !== options.compress; var packet = { type: type, data: data, options: options }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); if (fn) this.once('flush', fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.readyState = 'closing'; var self = this; if (this.writeBuffer.length) { this.once('drain', function () { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } function close () { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose () { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade () { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); // clean buffers after, so users can still // grab the buffers on `close` event self.writeBuffer = []; self.prevBufferLen = 0; } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i < j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./transport":3,"./transports/index":4,"component-emitter":14,"debug":16,"engine.io-parser":18,"indexof":22,"parsejson":25,"parseqs":26,"parseuri":27}],3:[function(_dereq_,module,exports){ /** * Module dependencies. */ var parser = _dereq_('engine.io-parser'); var Emitter = _dereq_('component-emitter'); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; this.forceNode = opts.forceNode; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.localAddress = opts.localAddress; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' === this.readyState || '' === this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function (packets) { if ('open' === this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function (data) { var packet = parser.decodePacket(data, this.socket.binaryType); this.onPacket(packet); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; },{"component-emitter":14,"engine.io-parser":18}],4:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies */ var XMLHttpRequest = _dereq_('xmlhttprequest-ssl'); var XHR = _dereq_('./polling-xhr'); var JSONP = _dereq_('./polling-jsonp'); var websocket = _dereq_('./websocket'); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling-jsonp":5,"./polling-xhr":6,"./websocket":8,"xmlhttprequest-ssl":9}],5:[function(_dereq_,module,exports){ (function (global){ /** * Module requirements. */ var Polling = _dereq_('./polling'); var inherit = _dereq_('component-inherit'); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; var rEscapedNewline = /\\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Noop. */ function empty () { } /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling (opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } } /** * Inherits from Polling. */ inherit(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket. * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; this.iframe = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function (e) { self.onError('jsonp poll error', e); }; var insertAt = document.getElementsByTagName('script')[0]; if (insertAt) { insertAt.parentNode.insertBefore(script, insertAt); } else { (document.head || document.body).appendChild(script); } this.script = script; var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); if (isUAgecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete () { initIframe(); fn(); } function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="' + self.iframeId + '">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; } initIframe(); // escape \n to prevent it from being converted into \r\n by some UAs // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side data = data.replace(rEscapedNewline, '\\\n'); this.area.value = data.replace(rNewline, '\\n'); try { this.form.submit(); } catch (e) {} if (this.iframe.attachEvent) { this.iframe.onreadystatechange = function () { if (self.iframe.readyState === 'complete') { complete(); } }; } else { this.iframe.onload = complete; } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling":7,"component-inherit":15}],6:[function(_dereq_,module,exports){ (function (global){ /** * Module requirements. */ var XMLHttpRequest = _dereq_('xmlhttprequest-ssl'); var Polling = _dereq_('./polling'); var Emitter = _dereq_('component-emitter'); var inherit = _dereq_('component-inherit'); var debug = _dereq_('debug')('engine.io-client:polling-xhr'); /** * Module exports. */ module.exports = XHR; module.exports.Request = Request; /** * Empty function */ function empty () {} /** * XHR Polling constructor. * * @param {Object} opts * @api public */ function XHR (opts) { Polling.call(this, opts); this.requestTimeout = opts.requestTimeout; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname !== global.location.hostname || port !== opts.port; this.xs = opts.secure !== isSSL; } else { this.extraHeaders = opts.extraHeaders; } } /** * Inherits from Polling. */ inherit(XHR, Polling); /** * XHR supports binary */ XHR.prototype.supportsBinary = true; /** * Creates a request. * * @param {String} method * @api private */ XHR.prototype.request = function (opts) { opts = opts || {}; opts.uri = this.uri(); opts.xd = this.xd; opts.xs = this.xs; opts.agent = this.agent || false; opts.supportsBinary = this.supportsBinary; opts.enablesXDR = this.enablesXDR; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; opts.requestTimeout = this.requestTimeout; // other options for Node.js client opts.extraHeaders = this.extraHeaders; return new Request(opts); }; /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @api private */ XHR.prototype.doWrite = function (data, fn) { var isBinary = typeof data !== 'string' && data !== undefined; var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); var self = this; req.on('success', fn); req.on('error', function (err) { self.onError('xhr post error', err); }); this.sendXhr = req; }; /** * Starts a poll cycle. * * @api private */ XHR.prototype.doPoll = function () { debug('xhr poll'); var req = this.request(); var self = this; req.on('data', function (data) { self.onData(data); }); req.on('error', function (err) { self.onError('xhr poll error', err); }); this.pollXhr = req; }; /** * Request constructor * * @param {Object} options * @api public */ function Request (opts) { this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.xs = !!opts.xs; this.async = false !== opts.async; this.data = undefined !== opts.data ? opts.data : null; this.agent = opts.agent; this.isBinary = opts.isBinary; this.supportsBinary = opts.supportsBinary; this.enablesXDR = opts.enablesXDR; this.requestTimeout = opts.requestTimeout; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.create(); } /** * Mix in `Emitter`. */ Emitter(Request.prototype); /** * Creates the XHR object and sends the request. * * @api private */ Request.prototype.create = function () { var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; var xhr = this.xhr = new XMLHttpRequest(opts); var self = this; try { debug('xhr open %s: %s', this.method, this.uri); xhr.open(this.method, this.uri, this.async); try { if (this.extraHeaders) { xhr.setDisableHeaderCheck(true); for (var i in this.extraHeaders) { if (this.extraHeaders.hasOwnProperty(i)) { xhr.setRequestHeader(i, this.extraHeaders[i]); } } } } catch (e) {} if (this.supportsBinary) { // This has to be done after open because Firefox is stupid // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension xhr.responseType = 'arraybuffer'; } if ('POST' === this.method) { try { if (this.isBinary) { xhr.setRequestHeader('Content-type', 'application/octet-stream'); } else { xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); } } catch (e) {} } try { xhr.setRequestHeader('Accept', '*/*'); } catch (e) {} // ie6 check if ('withCredentials' in xhr) { xhr.withCredentials = true; } if (this.requestTimeout) { xhr.timeout = this.requestTimeout; } if (this.hasXDR()) { xhr.onload = function () { self.onLoad(); }; xhr.onerror = function () { self.onError(xhr.responseText); }; } else { xhr.onreadystatechange = function () { if (4 !== xhr.readyState) return; if (200 === xhr.status || 1223 === xhr.status) { self.onLoad(); } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here setTimeout(function () { self.onError(xhr.status); }, 0); } }; } debug('xhr data %s', this.data); xhr.send(this.data); } catch (e) { // Need to defer since .create() is called directly fhrom the constructor // and thus the 'error' event can only be only bound *after* this exception // occurs. Therefore, also, we cannot throw here at all. setTimeout(function () { self.onError(e); }, 0); return; } if (global.document) { this.index = Request.requestsCount++; Request.requests[this.index] = this; } }; /** * Called upon successful response. * * @api private */ Request.prototype.onSuccess = function () { this.emit('success'); this.cleanup(); }; /** * Called if we have data. * * @api private */ Request.prototype.onData = function (data) { this.emit('data', data); this.onSuccess(); }; /** * Called upon error. * * @api private */ Request.prototype.onError = function (err) { this.emit('error', err); this.cleanup(true); }; /** * Cleans up house. * * @api private */ Request.prototype.cleanup = function (fromError) { if ('undefined' === typeof this.xhr || null === this.xhr) { return; } // xmlhttprequest if (this.hasXDR()) { this.xhr.onload = this.xhr.onerror = empty; } else { this.xhr.onreadystatechange = empty; } if (fromError) { try { this.xhr.abort(); } catch (e) {} } if (global.document) { delete Request.requests[this.index]; } this.xhr = null; }; /** * Called upon load. * * @api private */ Request.prototype.onLoad = function () { var data; try { var contentType; try { contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0]; } catch (e) {} if (contentType === 'application/octet-stream') { data = this.xhr.response || this.xhr.responseText; } else { if (!this.supportsBinary) { data = this.xhr.responseText; } else { try { data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response)); } catch (e) { var ui8Arr = new Uint8Array(this.xhr.response); var dataArray = []; for (var idx = 0, length = ui8Arr.length; idx < length; idx++) { dataArray.push(ui8Arr[idx]); } data = String.fromCharCode.apply(null, dataArray); } } } } catch (e) { this.onError(e); } if (null != data) { this.onData(data); } }; /** * Check if it has XDomainRequest. * * @api private */ Request.prototype.hasXDR = function () { return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; }; /** * Aborts the request. * * @api public */ Request.prototype.abort = function () { this.cleanup(); }; /** * Aborts pending requests when unloading the window. This is needed to prevent * memory leaks (e.g. when using IE) and to ensure that no spurious error is * emitted. */ Request.requestsCount = 0; Request.requests = {}; if (global.document) { if (global.attachEvent) { global.attachEvent('onunload', unloadHandler); } else if (global.addEventListener) { global.addEventListener('beforeunload', unloadHandler, false); } } function unloadHandler () { for (var i in Request.requests) { if (Request.requests.hasOwnProperty(i)) { Request.requests[i].abort(); } } } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling":7,"component-emitter":14,"component-inherit":15,"debug":16,"xmlhttprequest-ssl":9}],7:[function(_dereq_,module,exports){ /** * Module dependencies. */ var Transport = _dereq_('../transport'); var parseqs = _dereq_('parseqs'); var parser = _dereq_('engine.io-parser'); var inherit = _dereq_('component-inherit'); var yeast = _dereq_('yeast'); var debug = _dereq_('debug')('engine.io-client:polling'); /** * Module exports. */ module.exports = Polling; /** * Is XHR2 supported? */ var hasXHR2 = (function () { var XMLHttpRequest = _dereq_('xmlhttprequest-ssl'); var xhr = new XMLHttpRequest({ xdomain: false }); return null != xhr.responseType; })(); /** * Polling interface. * * @param {Object} opts * @api private */ function Polling (opts) { var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(Polling, Transport); /** * Transport name. */ Polling.prototype.name = 'polling'; /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @api private */ Polling.prototype.doOpen = function () { this.poll(); }; /** * Pauses polling. * * @param {Function} callback upon buffers are flushed and transport is paused * @api private */ Polling.prototype.pause = function (onPause) { var self = this; this.readyState = 'pausing'; function pause () { debug('paused'); self.readyState = 'paused'; onPause(); } if (this.polling || !this.writable) { var total = 0; if (this.polling) { debug('we are currently polling - waiting to pause'); total++; this.once('pollComplete', function () { debug('pre-pause polling complete'); --total || pause(); }); } if (!this.writable) { debug('we are currently writing - waiting to pause'); total++; this.once('drain', function () { debug('pre-pause writing complete'); --total || pause(); }); } } else { pause(); } }; /** * Starts polling cycle. * * @api public */ Polling.prototype.poll = function () { debug('polling'); this.polling = true; this.doPoll(); this.emit('poll'); }; /** * Overloads onData to detect payloads. * * @api private */ Polling.prototype.onData = function (data) { var self = this; debug('polling got data %s', data); var callback = function (packet, index, total) { // if its the first message we consider the transport open if ('opening' === self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' === packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }; // decode payload parser.decodePayload(data, this.socket.binaryType, callback); // if an event did not trigger closing if ('closed' !== this.readyState) { // if we got data we're not polling this.polling = false; this.emit('pollComplete'); if ('open' === this.readyState) { this.poll(); } else { debug('ignoring poll - transport state "%s"', this.readyState); } } }; /** * For polling, send a close packet. * * @api private */ Polling.prototype.doClose = function () { var self = this; function close () { debug('writing close packet'); self.write([{ type: 'close' }]); } if ('open' === this.readyState) { debug('transport open - closing'); close(); } else { // in case we're trying to close while // handshaking is in progress (GH-164) debug('transport not open - deferring close'); this.once('open', close); } }; /** * Writes a packets payload. * * @param {Array} data packets * @param {Function} drain callback * @api private */ Polling.prototype.write = function (packets) { var self = this; this.writable = false; var callbackfn = function () { self.writable = true; self.emit('drain'); }; parser.encodePayload(packets, this.supportsBinary, function (data) { self.doWrite(data, callbackfn); }); }; /** * Generates uri for connection. * * @api private */ Polling.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'https' : 'http'; var port = ''; // cache busting is forced if (false !== this.timestampRequests) { query[this.timestampParam] = yeast(); } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } query = parseqs.encode(query); // avoid port if default for schema if (this.port && (('https' === schema && Number(this.port) !== 443) || ('http' === schema && Number(this.port) !== 80))) { port = ':' + this.port; } // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; },{"../transport":3,"component-inherit":15,"debug":16,"engine.io-parser":18,"parseqs":26,"xmlhttprequest-ssl":9,"yeast":29}],8:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var Transport = _dereq_('../transport'); var parser = _dereq_('engine.io-parser'); var parseqs = _dereq_('parseqs'); var inherit = _dereq_('component-inherit'); var yeast = _dereq_('yeast'); var debug = _dereq_('debug')('engine.io-client:websocket'); var BrowserWebSocket = global.WebSocket || global.MozWebSocket; var NodeWebSocket; if (typeof window === 'undefined') { try { NodeWebSocket = _dereq_('ws'); } catch (e) { } } /** * Get either the `WebSocket` or `MozWebSocket` globals * in the browser or try to resolve WebSocket-compatible * interface exposed by `ws` for Node-like environment. */ var WebSocket = BrowserWebSocket; if (!WebSocket && typeof window === 'undefined') { WebSocket = NodeWebSocket; } /** * Module exports. */ module.exports = WS; /** * WebSocket transport constructor. * * @api {Object} connection options * @api public */ function WS (opts) { var forceBase64 = (opts && opts.forceBase64); if (forceBase64) { this.supportsBinary = false; } this.perMessageDeflate = opts.perMessageDeflate; this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode; if (!this.usingBrowserWebSocket) { WebSocket = NodeWebSocket; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(WS, Transport); /** * Transport name. * * @api public */ WS.prototype.name = 'websocket'; /* * WebSockets support binary */ WS.prototype.supportsBinary = true; /** * Opens socket. * * @api private */ WS.prototype.doOpen = function () { if (!this.check()) { // let probe timeout return; } var uri = this.uri(); var protocols = void (0); var opts = { agent: this.agent, perMessageDeflate: this.perMessageDeflate }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; if (this.extraHeaders) { opts.headers = this.extraHeaders; } if (this.localAddress) { opts.localAddress = this.localAddress; } try { this.ws = this.usingBrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts); } catch (err) { return this.emit('error', err); } if (this.ws.binaryType === undefined) { this.supportsBinary = false; } if (this.ws.supports && this.ws.supports.binary) { this.supportsBinary = true; this.ws.binaryType = 'nodebuffer'; } else { this.ws.binaryType = 'arraybuffer'; } this.addEventListeners(); }; /** * Adds event listeners to the socket * * @api private */ WS.prototype.addEventListeners = function () { var self = this; this.ws.onopen = function () { self.onOpen(); }; this.ws.onclose = function () { self.onClose(); }; this.ws.onmessage = function (ev) { self.onData(ev.data); }; this.ws.onerror = function (e) { self.onError('websocket error', e); }; }; /** * Writes data to socket. * * @param {Array} array of packets. * @api private */ WS.prototype.write = function (packets) { var self = this; this.writable = false; // encodePacket efficient as it uses WS framing // no need for encodePayload var total = packets.length; for (var i = 0, l = total; i < l; i++) { (function (packet) { parser.encodePacket(packet, self.supportsBinary, function (data) { if (!self.usingBrowserWebSocket) { // always create a new object (GH-437) var opts = {}; if (packet.options) { opts.compress = packet.options.compress; } if (self.perMessageDeflate) { var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length; if (len < self.perMessageDeflate.threshold) { opts.compress = false; } } } // Sometimes the websocket has already been closed but the browser didn't // have a chance of informing us about it yet, in that case send will // throw an error try { if (self.usingBrowserWebSocket) { // TypeError is thrown when passing the second argument on Safari self.ws.send(data); } else { self.ws.send(data, opts); } } catch (e) { debug('websocket closed before onclose event'); } --total || done(); }); })(packets[i]); } function done () { self.emit('flush'); // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(function () { self.writable = true; self.emit('drain'); }, 0); } }; /** * Called upon close * * @api private */ WS.prototype.onClose = function () { Transport.prototype.onClose.call(this); }; /** * Closes socket. * * @api private */ WS.prototype.doClose = function () { if (typeof this.ws !== 'undefined') { this.ws.close(); } }; /** * Generates uri for connection. * * @api private */ WS.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'wss' : 'ws'; var port = ''; // avoid port if default for schema if (this.port && (('wss' === schema && Number(this.port) !== 443) || ('ws' === schema && Number(this.port) !== 80))) { port = ':' + this.port; } // append timestamp to URI if (this.timestampRequests) { query[this.timestampParam] = yeast(); } // communicate binary support capabilities if (!this.supportsBinary) { query.b64 = 1; } query = parseqs.encode(query); // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; /** * Feature detection for WebSocket. * * @return {Boolean} whether this transport is available. * @api public */ WS.prototype.check = function () { return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../transport":3,"component-inherit":15,"debug":16,"engine.io-parser":18,"parseqs":26,"ws":undefined,"yeast":29}],9:[function(_dereq_,module,exports){ (function (global){ // browser shim for xmlhttprequest module var hasCORS = _dereq_('has-cors'); module.exports = function (opts) { var xdomain = opts.xdomain; // scheme must be same when usign XDomainRequest // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx var xscheme = opts.xscheme; // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. // https://github.com/Automattic/engine.io-client/pull/217 var enablesXDR = opts.enablesXDR; // XMLHttpRequest can be disabled on IE try { if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { return new XMLHttpRequest(); } } catch (e) { } // Use XDomainRequest for IE8 if enablesXDR is true // because loading bar keeps flashing when using jsonp-polling // https://github.com/yujiosaka/socke.io-ie8-loading-example try { if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) { return new XDomainRequest(); } } catch (e) { } if (!xdomain) { try { return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP'); } catch (e) { } } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"has-cors":21}],10:[function(_dereq_,module,exports){ module.exports = after function after(count, callback, err_cb) { var bail = false err_cb = err_cb || noop proxy.count = count return (count === 0) ? callback() : proxy function proxy(err, result) { if (proxy.count <= 0) { throw new Error('after called too many times') } --proxy.count // after first error, rest are passed to err_cb if (err) { bail = true callback(err) // future error callbacks will go to error handler callback = err_cb } else if (proxy.count === 0 && !bail) { callback(null, result) } } } function noop() {} },{}],11:[function(_dereq_,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported * * @api public */ module.exports = function(arraybuffer, start, end) { var bytes = arraybuffer.byteLength; start = start || 0; end = end || bytes; if (arraybuffer.slice) { return arraybuffer.slice(start, end); } if (start < 0) { start += bytes; } if (end < 0) { end += bytes; } if (end > bytes) { end = bytes; } if (start >= bytes || start >= end || bytes === 0) { return new ArrayBuffer(0); } var abv = new Uint8Array(arraybuffer); var result = new Uint8Array(end - start); for (var i = start, ii = 0; i < end; i++, ii++) { result[ii] = abv[i]; } return result.buffer; }; },{}],12:[function(_dereq_,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(){ "use strict"; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Use a lookup table to find the index. var lookup = new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i+1)]; encoded3 = lookup[base64.charCodeAt(i+2)]; encoded4 = lookup[base64.charCodeAt(i+3)]; bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })(); },{}],13:[function(_dereq_,module,exports){ (function (global){ /** * Create a blob builder even when vendor prefixes exist */ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder; /** * Check if Blob constructor is supported */ var blobSupported = (function() { try { var a = new Blob(['hi']); return a.size === 2; } catch(e) { return false; } })(); /** * Check if Blob constructor supports ArrayBufferViews * Fails in Safari 6, so we need to map to ArrayBuffers there. */ var blobSupportsArrayBufferView = blobSupported && (function() { try { var b = new Blob([new Uint8Array([1,2])]); return b.size === 2; } catch(e) { return false; } })(); /** * Check if BlobBuilder is supported */ var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob; /** * Helper function that maps ArrayBufferViews to ArrayBuffers * Used by BlobBuilder constructor and old browsers that didn't * support it in the Blob constructor. */ function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } } function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); mapArrayBufferViews(ary); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }; function BlobConstructor(ary, options) { mapArrayBufferViews(ary); return new Blob(ary, options || {}); }; module.exports = (function() { if (blobSupported) { return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; } else if (blobBuilderSupported) { return BlobBuilderConstructor; } else { return undefined; } })(); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],14:[function(_dereq_,module,exports){ /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],15:[function(_dereq_,module,exports){ module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; },{}],16:[function(_dereq_,module,exports){ (function (process){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = _dereq_('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } }).call(this,_dereq_('_process')) },{"./debug":17,"_process":undefined}],17:[function(_dereq_,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = _dereq_('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":24}],18:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var keys = _dereq_('./keys'); var hasBinary = _dereq_('has-binary'); var sliceBuffer = _dereq_('arraybuffer.slice'); var after = _dereq_('after'); var utf8 = _dereq_('wtf-8'); var base64encoder; if (global && global.ArrayBuffer) { base64encoder = _dereq_('base64-arraybuffer'); } /** * Check if we are running an android browser. That requires us to use * ArrayBuffer with polling transports... * * http://ghinda.net/jpeg-blob-ajax-android/ */ var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); /** * Check if we are running in PhantomJS. * Uploading a Blob with PhantomJS does not work correctly, as reported here: * https://github.com/ariya/phantomjs/issues/11395 * @type boolean */ var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); /** * When true, avoids using Blobs to encode payloads. * @type boolean */ var dontSendBlobs = isAndroid || isPhantomJS; /** * Current protocol version. */ exports.protocol = 3; /** * Packet types. */ var packets = exports.packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; /** * Create a blob api even for blob builder when vendor prefixes exist */ var Blob = _dereq_('blob'); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { if ('function' == typeof supportsBinary) { callback = supportsBinary; supportsBinary = false; } if ('function' == typeof utf8encode) { callback = utf8encode; utf8encode = null; } var data = (packet.data === undefined) ? undefined : packet.data.buffer || packet.data; if (global.ArrayBuffer && data instanceof ArrayBuffer) { return encodeArrayBuffer(packet, supportsBinary, callback); } else if (Blob && data instanceof global.Blob) { return encodeBlob(packet, supportsBinary, callback); } // might be an object with { base64: true, data: dataAsBase64String } if (data && data.base64) { return encodeBase64Object(packet, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data); } return callback('' + encoded); }; function encodeBase64Object(packet, callback) { // packet data is an object { base64: true, data: dataAsBase64String } var message = 'b' + exports.packets[packet.type] + packet.data.data; return callback(message); } /** * Encode packet helpers for binary types */ function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); } function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, true, callback); }; return fr.readAsArrayBuffer(packet.data); } function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (dontSendBlobs) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ exports.encodeBase64Packet = function(packet, callback) { var message = 'b' + exports.packets[packet.type]; if (Blob && packet.data instanceof global.Blob) { var fr = new FileReader(); fr.onload = function() { var b64 = fr.result.split(',')[1]; callback(message + b64); }; return fr.readAsDataURL(packet.data); } var b64data; try { b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); } catch (e) { // iPhone Safari doesn't let you apply with typed arrays var typed = new Uint8Array(packet.data); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } b64data = String.fromCharCode.apply(null, basic); } message += global.btoa(b64data); return callback(message); }; /** * Decodes a packet. Changes format to Blob if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ exports.decodePacket = function (data, binaryType, utf8decode) { if (data === undefined) { return err; } // String data if (typeof data == 'string') { if (data.charAt(0) == 'b') { return exports.decodeBase64Packet(data.substr(1), binaryType); } if (utf8decode) { data = tryDecode(data); if (data === false) { return err; } } var type = data.charAt(0); if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } var asArray = new Uint8Array(data); var type = asArray[0]; var rest = sliceBuffer(data, 1); if (Blob && binaryType === 'blob') { rest = new Blob([rest]); } return { type: packetslist[type], data: rest }; }; function tryDecode(data) { try { data = utf8.decode(data); } catch (e) { return false; } return data; } /** * Decodes a packet encoded in a base64 string * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ exports.decodeBase64Packet = function(msg, binaryType) { var type = packetslist[msg.charAt(0)]; if (!base64encoder) { return { type: type, data: { base64: true, data: msg.substr(1) } }; } var data = base64encoder.decode(msg.substr(1)); if (binaryType === 'blob' && Blob) { data = new Blob([data]); } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ exports.encodePayload = function (packets, supportsBinary, callback) { if (typeof supportsBinary == 'function') { callback = supportsBinary; supportsBinary = null; } var isBinary = hasBinary(packets); if (supportsBinary && isBinary) { if (Blob && !dontSendBlobs) { return exports.encodePayloadAsBlob(packets, callback); } return exports.encodePayloadAsArrayBuffer(packets, callback); } if (!packets.length) { return callback('0:'); } function setLengthHeader(message) { return message.length + ':' + message; } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; /** * Async array map using after */ function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); var eachWithIndex = function(i, el, cb) { each(el, function(error, msg) { result[i] = msg; cb(error, result); }); }; for (var i = 0; i < ary.length; i++) { eachWithIndex(i, ary[i], next); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ exports.decodePayload = function (data, binaryType, callback) { if (typeof data != 'string') { return exports.decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var packet; if (data == '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '' , n, msg; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (':' != chr) { length += chr; } else { if ('' == length || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = exports.decodePacket(msg, binaryType, true); if (err.type == packet.type && err.data == packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var ret = callback(packet, i + n, l); if (false === ret) return; } // advance cursor i += n; length = ''; } } if (length != '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {ArrayBuffer} encoded payload * @api private */ exports.encodePayloadAsArrayBuffer = function(packets, callback) { if (!packets.length) { return callback(new ArrayBuffer(0)); } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(data) { return doneCallback(null, data); }); } map(packets, encodeOne, function(err, encodedPackets) { var totalLength = encodedPackets.reduce(function(acc, p) { var len; if (typeof p === 'string'){ len = p.length; } else { len = p.byteLength; } return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 }, 0); var resultArray = new Uint8Array(totalLength); var bufferIndex = 0; encodedPackets.forEach(function(p) { var isString = typeof p === 'string'; var ab = p; if (isString) { var view = new Uint8Array(p.length); for (var i = 0; i < p.length; i++) { view[i] = p.charCodeAt(i); } ab = view.buffer; } if (isString) { // not true binary resultArray[bufferIndex++] = 0; } else { // true binary resultArray[bufferIndex++] = 1; } var lenStr = ab.byteLength.toString(); for (var i = 0; i < lenStr.length; i++) { resultArray[bufferIndex++] = parseInt(lenStr[i]); } resultArray[bufferIndex++] = 255; var view = new Uint8Array(ab); for (var i = 0; i < view.length; i++) { resultArray[bufferIndex++] = view[i]; } }); return callback(resultArray.buffer); }); }; /** * Encode as Blob */ exports.encodePayloadAsBlob = function(packets, callback) { function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(encoded) { var binaryIdentifier = new Uint8Array(1); binaryIdentifier[0] = 1; if (typeof encoded === 'string') { var view = new Uint8Array(encoded.length); for (var i = 0; i < encoded.length; i++) { view[i] = encoded.charCodeAt(i); } encoded = view.buffer; binaryIdentifier[0] = 0; } var len = (encoded instanceof ArrayBuffer) ? encoded.byteLength : encoded.size; var lenStr = len.toString(); var lengthAry = new Uint8Array(lenStr.length + 1); for (var i = 0; i < lenStr.length; i++) { lengthAry[i] = parseInt(lenStr[i]); } lengthAry[lenStr.length] = 255; if (Blob) { var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); doneCallback(null, blob); } }); } map(packets, encodeOne, function(err, results) { return callback(new Blob(results)); }); }; /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * * @param {ArrayBuffer} data, callback method * @api public */ exports.decodePayloadAsBinary = function (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; var numberTooLong = false; while (bufferTail.byteLength > 0) { var tailArray = new Uint8Array(bufferTail); var isString = tailArray[0] === 0; var msgLength = ''; for (var i = 1; ; i++) { if (tailArray[i] == 255) break; if (msgLength.length > 310) { numberTooLong = true; break; } msgLength += tailArray[i]; } if(numberTooLong) return callback(err, 0, 1); bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); msgLength = parseInt(msgLength); var msg = sliceBuffer(bufferTail, 0, msgLength); if (isString) { try { msg = String.fromCharCode.apply(null, new Uint8Array(msg)); } catch (e) { // iPhone Safari doesn't let you apply to typed arrays var typed = new Uint8Array(msg); msg = ''; for (var i = 0; i < typed.length; i++) { msg += String.fromCharCode(typed[i]); } } } buffers.push(msg); bufferTail = sliceBuffer(bufferTail, msgLength); } var total = buffers.length; buffers.forEach(function(buffer, i) { callback(exports.decodePacket(buffer, binaryType, true), i, total); }); }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./keys":19,"after":10,"arraybuffer.slice":11,"base64-arraybuffer":12,"blob":13,"has-binary":20,"wtf-8":28}],19:[function(_dereq_,module,exports){ /** * Gets the keys for an object. * * @return {Array} keys * @api private */ module.exports = Object.keys || function keys (obj){ var arr = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { arr.push(i); } } return arr; }; },{}],20:[function(_dereq_,module,exports){ (function (global){ /* * Module requirements. */ var isArray = _dereq_('isarray'); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { if (obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"isarray":23}],21:[function(_dereq_,module,exports){ /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } },{}],22:[function(_dereq_,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],23:[function(_dereq_,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],24:[function(_dereq_,module,exports){ /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } },{}],25:[function(_dereq_,module,exports){ (function (global){ /** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 * @api private */ var rvalidchars = /^[\],:{}\s]*$/; var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; var rtrimLeft = /^\s+/; var rtrimRight = /\s+$/; module.exports = function parsejson(data) { if ('string' != typeof data || !data) { return null; } data = data.replace(rtrimLeft, '').replace(rtrimRight, ''); // Attempt to parse using the native JSON parser first if (global.JSON && JSON.parse) { return JSON.parse(data); } if (rvalidchars.test(data.replace(rvalidescape, '@') .replace(rvalidtokens, ']') .replace(rvalidbraces, ''))) { return (new Function('return ' + data))(); } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],26:[function(_dereq_,module,exports){ /** * Compiles a querystring * Returns string representation of the object * * @param {Object} * @api private */ exports.encode = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring into an object * * @param {String} qs * @api private */ exports.decode = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; },{}],27:[function(_dereq_,module,exports){ /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var src = str, b = str.indexOf('['), e = str.indexOf(']'); if (b != -1 && e != -1) { str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); } var m = re.exec(str || ''), uri = {}, i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } if (b != -1 && e != -1) { uri.source = src; uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); uri.ipv6uri = true; } return uri; }; },{}],28:[function(_dereq_,module,exports){ (function (global){ /*! https://mths.be/wtf8 v1.0.0 by @mathias */ ;(function(root) { // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var stringFromCharCode = String.fromCharCode; // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; var value; var extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; var index = -1; var value; var output = ''; while (++index < length) { value = array[index]; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); } return output; } /*--------------------------------------------------------------------------*/ function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } function encodeCodePoint(codePoint) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); } var symbol = ''; if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); symbol += createByte(codePoint, 6); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); symbol += createByte(codePoint, 12); symbol += createByte(codePoint, 6); } symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } function wtf8encode(string) { var codePoints = ucs2decode(string); var length = codePoints.length; var index = -1; var codePoint; var byteString = ''; while (++index < length) { codePoint = codePoints[index]; byteString += encodeCodePoint(codePoint); } return byteString; } /*--------------------------------------------------------------------------*/ function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } // If we end up here, it’s not a continuation byte. throw Error('Invalid continuation byte'); } function decodeSymbol() { var byte1; var byte2; var byte3; var byte4; var codePoint; if (byteIndex > byteCount) { throw Error('Invalid byte index'); } if (byteIndex == byteCount) { return false; } // Read the first byte. byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { var byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; if (codePoint >= 0x0800) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; } } throw Error('Invalid WTF-8 detected'); } var byteArray; var byteCount; var byteIndex; function wtf8decode(byteString) { byteArray = ucs2decode(byteString); byteCount = byteArray.length; byteIndex = 0; var codePoints = []; var tmp; while ((tmp = decodeSymbol()) !== false) { codePoints.push(tmp); } return ucs2encode(codePoints); } /*--------------------------------------------------------------------------*/ var wtf8 = { 'version': '1.0.0', 'encode': wtf8encode, 'decode': wtf8decode }; if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = wtf8; } else { // in Narwhal or RingoJS v0.7.0- var object = {}; var hasOwnProperty = object.hasOwnProperty; for (var key in wtf8) { hasOwnProperty.call(wtf8, key) && (freeExports[key] = wtf8[key]); } } } else { // in Rhino or a web browser root.wtf8 = wtf8; } }(this)); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],29:[function(_dereq_,module,exports){ 'use strict'; var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') , length = 64 , map = {} , seed = 0 , i = 0 , prev; /** * Return a string representing the specified number. * * @param {Number} num The number to convert. * @returns {String} The string representation of the number. * @api public */ function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; } /** * Return the integer value specified by the given string. * * @param {String} str The string to convert. * @returns {Number} The integer value represented by the string. * @api public */ function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; } /** * Yeast: A tiny growing id generator. * * @returns {String} A unique id. * @api public */ function yeast() { var now = encode(+new Date()); if (now !== prev) return seed = 0, prev = now; return now +'.'+ encode(seed++); } // // Map each character to its index. // for (; i < length; i++) map[alphabet[i]] = i; // // Expose the `yeast`, `encode` and `decode` functions. // yeast.encode = encode; yeast.decode = decode; module.exports = yeast; },{}],30:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib/index'); },{"./lib/index":1}]},{},[30])(30) });
[minor] Rebuild the Engine.IO client -- version 1.8.2
transformers/engine.io/library.js
[minor] Rebuild the Engine.IO client -- version 1.8.2
<ide><path>ransformers/engine.io/library.js <ide> function _hasBinary(obj) { <ide> if (!obj) return false; <ide> <del> if ( (global.Buffer && global.Buffer.isBuffer(obj)) || <add> if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || <ide> (global.ArrayBuffer && obj instanceof ArrayBuffer) || <ide> (global.Blob && obj instanceof Blob) || <ide> (global.File && obj instanceof File) <ide> } <ide> } <ide> } else if (obj && 'object' == typeof obj) { <del> if (obj.toJSON) { <add> // see: https://github.com/Automattic/has-binary/pull/4 <add> if (obj.toJSON && 'function' == typeof obj.toJSON) { <ide> obj = obj.toJSON(); <ide> } <ide>
Java
apache-2.0
e6a8a00b89dbdf922405f8586b43d1c9b99cff90
0
apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.storage.hbase; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.lock.DistributedLock; import org.apache.kylin.common.persistence.StorageException; import org.apache.kylin.common.util.HadoopUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author yangli9 * */ public class HBaseConnection { public static final String HTABLE_UUID_TAG = "UUID"; private static final Logger logger = LoggerFactory.getLogger(HBaseConnection.class); private static final Map<String, Configuration> configCache = new ConcurrentHashMap<String, Configuration>(); private static final Map<String, Connection> connPool = new ConcurrentHashMap<String, Connection>(); private static final ThreadLocal<Configuration> configThreadLocal = new ThreadLocal<>(); private static ExecutorService coprocessorPool = null; private static DistributedLock lock = null; static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { closeCoprocessorPool(); for (Connection conn : connPool.values()) { try { conn.close(); } catch (IOException e) { e.printStackTrace(); } } } }); } public static ExecutorService getCoprocessorPool() { if (coprocessorPool != null) { return coprocessorPool; } synchronized (HBaseConnection.class) { if (coprocessorPool != null) { return coprocessorPool; } KylinConfig config = KylinConfig.getInstanceFromEnv(); // copy from HConnectionImplementation.getBatchPool() int maxThreads = config.getHBaseMaxConnectionThreads(); int coreThreads = config.getHBaseCoreConnectionThreads(); long keepAliveTime = config.getHBaseConnectionThreadPoolAliveSeconds(); LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maxThreads * 100); ThreadPoolExecutor tpe = new ThreadPoolExecutor(coreThreads, maxThreads, keepAliveTime, TimeUnit.SECONDS, workQueue, // Threads.newDaemonThreadFactory("kylin-coproc-")); tpe.allowCoreThreadTimeOut(true); logger.info("Creating coprocessor thread pool with max of {}, core of {}", maxThreads, coreThreads); coprocessorPool = tpe; return coprocessorPool; } } private static void closeCoprocessorPool() { if (coprocessorPool == null) return; coprocessorPool.shutdown(); try { if (!coprocessorPool.awaitTermination(10, TimeUnit.SECONDS)) { coprocessorPool.shutdownNow(); } } catch (InterruptedException e) { coprocessorPool.shutdownNow(); } } public static void clearConnCache() { connPool.clear(); } public static Configuration getCurrentHBaseConfiguration() { if (configThreadLocal.get() == null) { String storageUrl = KylinConfig.getInstanceFromEnv().getStorageUrl(); configThreadLocal.set(newHBaseConfiguration(storageUrl)); } return configThreadLocal.get(); } private static Configuration newHBaseConfiguration(String url) { // using a hbase:xxx URL is deprecated, instead hbase config is always loaded from hbase-site.xml in classpath if (!(StringUtils.isEmpty(url) || "hbase".equals(url))) throw new IllegalArgumentException("to use hbase storage, pls set 'kylin.storage.url=hbase' in kylin.properties"); Configuration conf = HBaseConfiguration.create(HadoopUtil.getCurrentConfiguration()); addHBaseClusterNNHAConfiguration(conf); // support hbase using a different FS KylinConfig kylinConf = KylinConfig.getInstanceFromEnv(); String hbaseClusterFs = kylinConf.getHBaseClusterFs(); if (StringUtils.isNotEmpty(hbaseClusterFs)) { conf.set(FileSystem.FS_DEFAULT_NAME_KEY, hbaseClusterFs); } // https://issues.apache.org/jira/browse/KYLIN-953 if (StringUtils.isBlank(conf.get("hadoop.tmp.dir"))) { conf.set("hadoop.tmp.dir", "/tmp"); } if (StringUtils.isBlank(conf.get("hbase.fs.tmp.dir"))) { conf.set("hbase.fs.tmp.dir", "/tmp"); } return conf; } // See YARN-3021. Copy here in case of missing in dependency MR client jars public static final String JOB_NAMENODES_TOKEN_RENEWAL_EXCLUDE = "mapreduce.job.hdfs-servers.token-renewal.exclude"; public static void addHBaseClusterNNHAConfiguration(Configuration conf) { String hdfsConfigFile = KylinConfig.getInstanceFromEnv().getHBaseClusterHDFSConfigFile(); if (hdfsConfigFile == null || hdfsConfigFile.isEmpty()) { return; } Configuration hdfsConf = new Configuration(false); hdfsConf.addResource(hdfsConfigFile); Collection<String> nameServices = hdfsConf.getTrimmedStringCollection(DFSConfigKeys.DFS_NAMESERVICES); Collection<String> mainNameServices = conf.getTrimmedStringCollection(DFSConfigKeys.DFS_NAMESERVICES); for (String serviceId : nameServices) { mainNameServices.add(serviceId); String serviceConfKey = DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + "." + serviceId; String proxyConfKey = DFSConfigKeys.DFS_CLIENT_FAILOVER_PROXY_PROVIDER_KEY_PREFIX + "." + serviceId; conf.set(serviceConfKey, hdfsConf.get(serviceConfKey, "")); conf.set(proxyConfKey, hdfsConf.get(proxyConfKey, "")); Collection<String> nameNodes = hdfsConf.getTrimmedStringCollection(serviceConfKey); for (String nameNode : nameNodes) { String rpcConfKey = DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + serviceId + "." + nameNode; conf.set(rpcConfKey, hdfsConf.get(rpcConfKey, "")); } } conf.setStrings(DFSConfigKeys.DFS_NAMESERVICES, mainNameServices.toArray(new String[0])); // See YARN-3021, instruct RM skip renew token of hbase cluster name services conf.setStrings(JOB_NAMENODES_TOKEN_RENEWAL_EXCLUDE, nameServices.toArray(new String[0])); } public static String makeQualifiedPathInHBaseCluster(String inPath) { Path path = new Path(inPath); path = Path.getPathWithoutSchemeAndAuthority(path); try { FileSystem fs = FileSystem.get(getCurrentHBaseConfiguration()); return fs.makeQualified(path).toString(); } catch (IOException e) { throw new IllegalArgumentException("Cannot create FileSystem from current hbase cluster conf", e); } } // ============================================================================ // returned Connection can be shared by multiple threads and does not require close() @SuppressWarnings("resource") public static Connection get(String url) { // find configuration Configuration conf = configCache.get(url); if (conf == null) { conf = newHBaseConfiguration(url); configCache.put(url, conf); } Connection connection = connPool.get(url); try { while (true) { // I don't use DCL since recreate a connection is not a big issue. if (connection == null || connection.isClosed()) { logger.info("connection is null or closed, creating a new one"); connection = ConnectionFactory.createConnection(conf); connPool.put(url, connection); } if (connection == null || connection.isClosed()) { Thread.sleep(10000);// wait a while and retry } else { break; } } } catch (Throwable t) { logger.error("Error when open connection " + url, t); throw new StorageException("Error when open connection " + url, t); } return connection; } public static boolean tableExists(Connection conn, String tableName) throws IOException { Admin hbase = conn.getAdmin(); try { return hbase.tableExists(TableName.valueOf(tableName)); } finally { hbase.close(); } } public static boolean tableExists(String hbaseUrl, String tableName) throws IOException { return tableExists(HBaseConnection.get(hbaseUrl), tableName); } public static void createHTableIfNeeded(String hbaseUrl, String tableName, String... families) throws IOException { createHTableIfNeeded(HBaseConnection.get(hbaseUrl), tableName, families); } public static void deleteTable(String hbaseUrl, String tableName) throws IOException { deleteTable(HBaseConnection.get(hbaseUrl), tableName); } public static void createHTableIfNeeded(Connection conn, String table, String... families) throws IOException { Admin hbase = conn.getAdmin(); TableName tableName = TableName.valueOf(table); boolean hasLock = false; try { if (tableExists(conn, table)) { logger.debug("HTable '" + table + "' already exists"); Set<String> existingFamilies = getFamilyNames(hbase.getTableDescriptor(tableName)); boolean wait = false; for (String family : families) { if (existingFamilies.contains(family) == false) { logger.debug("Adding family '" + family + "' to HTable '" + table + "'"); hbase.addColumn(tableName, newFamilyDescriptor(family)); // addColumn() is async, is there a way to wait it finish? wait = true; } } if (wait) { try { Thread.sleep(10000); } catch (InterruptedException e) { logger.warn("", e); } } return; } lock = KylinConfig.getInstanceFromEnv().getDistributedLockFactory().lockForCurrentProcess(); hasLock = lock.lock(getLockPath(table), Long.MAX_VALUE); if (tableExists(conn, table)) { logger.debug("HTable '" + table + "' already exists"); return; } logger.debug("Creating HTable '" + table + "'"); HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(table)); if (null != families && families.length > 0) { for (String family : families) { HColumnDescriptor fd = newFamilyDescriptor(family); desc.addFamily(fd); } } //desc.setValue(HTABLE_UUID_TAG, UUID.randomUUID().toString()); hbase.createTable(desc); logger.debug("HTable '" + table + "' created"); } finally { hbase.close(); if (hasLock && lock != null) { lock.unlock(getLockPath(table)); } } } private static Set<String> getFamilyNames(HTableDescriptor desc) { HashSet<String> result = Sets.newHashSet(); for (byte[] bytes : desc.getFamiliesKeys()) { try { result.add(new String(bytes, "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error(e.toString()); } } return result; } private static HColumnDescriptor newFamilyDescriptor(String family) { HColumnDescriptor fd = new HColumnDescriptor(family); fd.setInMemory(true); // metadata tables are best in memory return fd; } public static void deleteTable(Connection conn, String tableName) throws IOException { Admin hbase = conn.getAdmin(); try { if (!tableExists(conn, tableName)) { logger.debug("HTable '" + tableName + "' does not exists"); return; } logger.debug("delete HTable '" + tableName + "'"); if (hbase.isTableEnabled(TableName.valueOf(tableName))) { hbase.disableTable(TableName.valueOf(tableName)); } hbase.deleteTable(TableName.valueOf(tableName)); logger.debug("HTable '" + tableName + "' deleted"); } finally { hbase.close(); } } private static String getLockPath(String pathName) { return "/create_htable/" + pathName + "/lock"; } }
storage-hbase/src/main/java/org/apache/kylin/storage/hbase/HBaseConnection.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.storage.hbase; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.persistence.StorageException; import org.apache.kylin.common.util.HadoopUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author yangli9 * */ public class HBaseConnection { public static final String HTABLE_UUID_TAG = "UUID"; private static final Logger logger = LoggerFactory.getLogger(HBaseConnection.class); private static final Map<String, Configuration> configCache = new ConcurrentHashMap<String, Configuration>(); private static final Map<String, Connection> connPool = new ConcurrentHashMap<String, Connection>(); private static final ThreadLocal<Configuration> configThreadLocal = new ThreadLocal<>(); private static ExecutorService coprocessorPool = null; static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { closeCoprocessorPool(); for (Connection conn : connPool.values()) { try { conn.close(); } catch (IOException e) { e.printStackTrace(); } } } }); } public static ExecutorService getCoprocessorPool() { if (coprocessorPool != null) { return coprocessorPool; } synchronized (HBaseConnection.class) { if (coprocessorPool != null) { return coprocessorPool; } KylinConfig config = KylinConfig.getInstanceFromEnv(); // copy from HConnectionImplementation.getBatchPool() int maxThreads = config.getHBaseMaxConnectionThreads(); int coreThreads = config.getHBaseCoreConnectionThreads(); long keepAliveTime = config.getHBaseConnectionThreadPoolAliveSeconds(); LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maxThreads * 100); ThreadPoolExecutor tpe = new ThreadPoolExecutor(coreThreads, maxThreads, keepAliveTime, TimeUnit.SECONDS, workQueue, // Threads.newDaemonThreadFactory("kylin-coproc-")); tpe.allowCoreThreadTimeOut(true); logger.info("Creating coprocessor thread pool with max of {}, core of {}", maxThreads, coreThreads); coprocessorPool = tpe; return coprocessorPool; } } private static void closeCoprocessorPool() { if (coprocessorPool == null) return; coprocessorPool.shutdown(); try { if (!coprocessorPool.awaitTermination(10, TimeUnit.SECONDS)) { coprocessorPool.shutdownNow(); } } catch (InterruptedException e) { coprocessorPool.shutdownNow(); } } public static void clearConnCache() { connPool.clear(); } public static Configuration getCurrentHBaseConfiguration() { if (configThreadLocal.get() == null) { String storageUrl = KylinConfig.getInstanceFromEnv().getStorageUrl(); configThreadLocal.set(newHBaseConfiguration(storageUrl)); } return configThreadLocal.get(); } private static Configuration newHBaseConfiguration(String url) { // using a hbase:xxx URL is deprecated, instead hbase config is always loaded from hbase-site.xml in classpath if (!(StringUtils.isEmpty(url) || "hbase".equals(url))) throw new IllegalArgumentException("to use hbase storage, pls set 'kylin.storage.url=hbase' in kylin.properties"); Configuration conf = HBaseConfiguration.create(HadoopUtil.getCurrentConfiguration()); addHBaseClusterNNHAConfiguration(conf); // support hbase using a different FS KylinConfig kylinConf = KylinConfig.getInstanceFromEnv(); String hbaseClusterFs = kylinConf.getHBaseClusterFs(); if (StringUtils.isNotEmpty(hbaseClusterFs)) { conf.set(FileSystem.FS_DEFAULT_NAME_KEY, hbaseClusterFs); } // https://issues.apache.org/jira/browse/KYLIN-953 if (StringUtils.isBlank(conf.get("hadoop.tmp.dir"))) { conf.set("hadoop.tmp.dir", "/tmp"); } if (StringUtils.isBlank(conf.get("hbase.fs.tmp.dir"))) { conf.set("hbase.fs.tmp.dir", "/tmp"); } return conf; } // See YARN-3021. Copy here in case of missing in dependency MR client jars public static final String JOB_NAMENODES_TOKEN_RENEWAL_EXCLUDE = "mapreduce.job.hdfs-servers.token-renewal.exclude"; public static void addHBaseClusterNNHAConfiguration(Configuration conf) { String hdfsConfigFile = KylinConfig.getInstanceFromEnv().getHBaseClusterHDFSConfigFile(); if (hdfsConfigFile == null || hdfsConfigFile.isEmpty()) { return; } Configuration hdfsConf = new Configuration(false); hdfsConf.addResource(hdfsConfigFile); Collection<String> nameServices = hdfsConf.getTrimmedStringCollection(DFSConfigKeys.DFS_NAMESERVICES); Collection<String> mainNameServices = conf.getTrimmedStringCollection(DFSConfigKeys.DFS_NAMESERVICES); for (String serviceId : nameServices) { mainNameServices.add(serviceId); String serviceConfKey = DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + "." + serviceId; String proxyConfKey = DFSConfigKeys.DFS_CLIENT_FAILOVER_PROXY_PROVIDER_KEY_PREFIX + "." + serviceId; conf.set(serviceConfKey, hdfsConf.get(serviceConfKey, "")); conf.set(proxyConfKey, hdfsConf.get(proxyConfKey, "")); Collection<String> nameNodes = hdfsConf.getTrimmedStringCollection(serviceConfKey); for (String nameNode : nameNodes) { String rpcConfKey = DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + serviceId + "." + nameNode; conf.set(rpcConfKey, hdfsConf.get(rpcConfKey, "")); } } conf.setStrings(DFSConfigKeys.DFS_NAMESERVICES, mainNameServices.toArray(new String[0])); // See YARN-3021, instruct RM skip renew token of hbase cluster name services conf.setStrings(JOB_NAMENODES_TOKEN_RENEWAL_EXCLUDE, nameServices.toArray(new String[0])); } public static String makeQualifiedPathInHBaseCluster(String inPath) { Path path = new Path(inPath); path = Path.getPathWithoutSchemeAndAuthority(path); try { FileSystem fs = FileSystem.get(getCurrentHBaseConfiguration()); return fs.makeQualified(path).toString(); } catch (IOException e) { throw new IllegalArgumentException("Cannot create FileSystem from current hbase cluster conf", e); } } // ============================================================================ // returned Connection can be shared by multiple threads and does not require close() @SuppressWarnings("resource") public static Connection get(String url) { // find configuration Configuration conf = configCache.get(url); if (conf == null) { conf = newHBaseConfiguration(url); configCache.put(url, conf); } Connection connection = connPool.get(url); try { while (true) { // I don't use DCL since recreate a connection is not a big issue. if (connection == null || connection.isClosed()) { logger.info("connection is null or closed, creating a new one"); connection = ConnectionFactory.createConnection(conf); connPool.put(url, connection); } if (connection == null || connection.isClosed()) { Thread.sleep(10000);// wait a while and retry } else { break; } } } catch (Throwable t) { logger.error("Error when open connection " + url, t); throw new StorageException("Error when open connection " + url, t); } return connection; } public static boolean tableExists(Connection conn, String tableName) throws IOException { Admin hbase = conn.getAdmin(); try { return hbase.tableExists(TableName.valueOf(tableName)); } finally { hbase.close(); } } public static boolean tableExists(String hbaseUrl, String tableName) throws IOException { return tableExists(HBaseConnection.get(hbaseUrl), tableName); } public static void createHTableIfNeeded(String hbaseUrl, String tableName, String... families) throws IOException { createHTableIfNeeded(HBaseConnection.get(hbaseUrl), tableName, families); } public static void deleteTable(String hbaseUrl, String tableName) throws IOException { deleteTable(HBaseConnection.get(hbaseUrl), tableName); } public static void createHTableIfNeeded(Connection conn, String table, String... families) throws IOException { Admin hbase = conn.getAdmin(); TableName tableName = TableName.valueOf(table); try { if (tableExists(conn, table)) { logger.debug("HTable '" + table + "' already exists"); Set<String> existingFamilies = getFamilyNames(hbase.getTableDescriptor(tableName)); boolean wait = false; for (String family : families) { if (existingFamilies.contains(family) == false) { logger.debug("Adding family '" + family + "' to HTable '" + table + "'"); hbase.addColumn(tableName, newFamilyDescriptor(family)); // addColumn() is async, is there a way to wait it finish? wait = true; } } if (wait) { try { Thread.sleep(10000); } catch (InterruptedException e) { logger.warn("", e); } } return; } logger.debug("Creating HTable '" + table + "'"); HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(table)); if (null != families && families.length > 0) { for (String family : families) { HColumnDescriptor fd = newFamilyDescriptor(family); desc.addFamily(fd); } } //desc.setValue(HTABLE_UUID_TAG, UUID.randomUUID().toString()); hbase.createTable(desc); logger.debug("HTable '" + table + "' created"); } finally { hbase.close(); } } private static Set<String> getFamilyNames(HTableDescriptor desc) { HashSet<String> result = Sets.newHashSet(); for (byte[] bytes : desc.getFamiliesKeys()) { try { result.add(new String(bytes, "UTF-8")); } catch (UnsupportedEncodingException e) { logger.error(e.toString()); } } return result; } private static HColumnDescriptor newFamilyDescriptor(String family) { HColumnDescriptor fd = new HColumnDescriptor(family); fd.setInMemory(true); // metadata tables are best in memory return fd; } public static void deleteTable(Connection conn, String tableName) throws IOException { Admin hbase = conn.getAdmin(); try { if (!tableExists(conn, tableName)) { logger.debug("HTable '" + tableName + "' does not exists"); return; } logger.debug("delete HTable '" + tableName + "'"); if (hbase.isTableEnabled(TableName.valueOf(tableName))) { hbase.disableTable(TableName.valueOf(tableName)); } hbase.deleteTable(TableName.valueOf(tableName)); logger.debug("HTable '" + tableName + "' deleted"); } finally { hbase.close(); } } }
KYLIN-2557-The-kylin-will-start-failed Signed-off-by: Yang Li <[email protected]>
storage-hbase/src/main/java/org/apache/kylin/storage/hbase/HBaseConnection.java
KYLIN-2557-The-kylin-will-start-failed
<ide><path>torage-hbase/src/main/java/org/apache/kylin/storage/hbase/HBaseConnection.java <ide> import org.apache.hadoop.hbase.util.Threads; <ide> import org.apache.hadoop.hdfs.DFSConfigKeys; <ide> import org.apache.kylin.common.KylinConfig; <add>import org.apache.kylin.common.lock.DistributedLock; <ide> import org.apache.kylin.common.persistence.StorageException; <ide> import org.apache.kylin.common.util.HadoopUtil; <ide> import org.slf4j.Logger; <ide> <ide> private static ExecutorService coprocessorPool = null; <ide> <add> private static DistributedLock lock = null; <add> <ide> static { <ide> Runtime.getRuntime().addShutdownHook(new Thread() { <ide> @Override <ide> public static void createHTableIfNeeded(Connection conn, String table, String... families) throws IOException { <ide> Admin hbase = conn.getAdmin(); <ide> TableName tableName = TableName.valueOf(table); <add> boolean hasLock = false; <ide> try { <ide> if (tableExists(conn, table)) { <ide> logger.debug("HTable '" + table + "' already exists"); <ide> return; <ide> } <ide> <add> lock = KylinConfig.getInstanceFromEnv().getDistributedLockFactory().lockForCurrentProcess(); <add> hasLock = lock.lock(getLockPath(table), Long.MAX_VALUE); <add> <add> if (tableExists(conn, table)) { <add> logger.debug("HTable '" + table + "' already exists"); <add> return; <add> } <add> <ide> logger.debug("Creating HTable '" + table + "'"); <ide> <ide> HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(table)); <ide> logger.debug("HTable '" + table + "' created"); <ide> } finally { <ide> hbase.close(); <add> if (hasLock && lock != null) { <add> lock.unlock(getLockPath(table)); <add> } <ide> } <ide> } <ide> <ide> } <ide> } <ide> <add> private static String getLockPath(String pathName) { <add> return "/create_htable/" + pathName + "/lock"; <add> } <add> <ide> }
Java
lgpl-2.1
0405bd0bab14ee3692e3f3f806756da74e7719fb
0
SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.davis.frames; import eu.seebetter.ini.chips.ApsDvsChip; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.util.avioutput.AVIOutputStream; /** * Writes AVI file from DAVIS APS frames, using ApsFrameExtractor. * The AVI file is in RAW format with pixel values 0-255 coming from ApsFrameExtractor displayed frames, which are offset and scaled by it. * * @author Tobi */ @Description("Writes AVI file from DAVIS APS frames, using ApsFrameExtractor") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class DAVISAVIWriter extends EventFilter2D implements PropertyChangeListener { ApsFrameExtractor apsFrameExtractor; AVIOutputStream aviOutputStream = null; private String DEFAULT_FILENAME = "DAVIS_APS.avi"; private String lastFileName = getString("lastFileName", DEFAULT_FILENAME); ApsDvsChip apsDvsChip = null; private int framesWritten = 0; private final int logEveryThisManyFrames = 30; public DAVISAVIWriter(AEChip chip) { super(chip); FilterChain filterChain = new FilterChain(chip); apsFrameExtractor = new ApsFrameExtractor(chip); apsFrameExtractor.getSupport().addPropertyChangeListener(this); filterChain.add(apsFrameExtractor); setEnclosedFilterChain(filterChain); setPropertyTooltip("saveAVIFileAs", "Opens the output file. The AVI file is in RAW format with pixel values 0-255 coming from ApsFrameExtractor displayed frames, which are offset and scaled by it."); setPropertyTooltip("closeFile", "Closes the output file if it is open."); } @Override public EventPacket<?> filterPacket(EventPacket<?> in) { apsDvsChip = (ApsDvsChip) chip; apsFrameExtractor.filterPacket(in); return in; } @Override public void resetFilter() { apsFrameExtractor.resetFilter(); } @Override public void initFilter() { apsFrameExtractor.initFilter(); } @Override public void propertyChange(PropertyChangeEvent evt) { if (aviOutputStream != null && evt.getPropertyName() == ApsFrameExtractor.EVENT_NEW_FRAME) { double[] frame = apsFrameExtractor.getNewFrame(); BufferedImage bufferedImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_3BYTE_BGR); WritableRaster raster = bufferedImage.getRaster(); int sx = chip.getSizeX(), sy = chip.getSizeY(); for (int y = 0; y < sy; y++) { for (int x = 0; x < sx; x++) { int k = apsFrameExtractor.getIndex(x, y); // bufferedImage.setRGB(x, y, (int) (frame[k] * 1024)); int v=(int)(frame[k]*255), yy=sy - y - 1; // must flip image vertially according to java convention that image starts at upper left raster.setSample(x, yy, 0, v); raster.setSample(x, yy, 1, v); raster.setSample(x, yy, 2, v); } } try { aviOutputStream.writeFrame(bufferedImage); if (++framesWritten % logEveryThisManyFrames == 0) { log.info(String.format("wrote %d frames", framesWritten)); } // apsFrameExtractor.getIndex(x, y); } catch (IOException ex) { Logger.getLogger(DAVISAVIWriter.class.getName()).log(Level.SEVERE, null, ex); } } } synchronized public void doSaveAVIFileAs() { JFileChooser c = new JFileChooser(lastFileName); c.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".avi"); } @Override public String getDescription() { return "AVI (Audio Video Interleave) Microsoft video file"; } }); c.setSelectedFile(new File(lastFileName)); int ret = c.showSaveDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } lastFileName = c.getSelectedFile().toString(); if (c.getSelectedFile().exists()) { int r = JOptionPane.showConfirmDialog(null, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?"); if (r != JOptionPane.OK_OPTION) { return; } } openAVIOutputStream(c.getSelectedFile()); } synchronized public void doCloseFile() { if (aviOutputStream != null) { try { aviOutputStream.close(); aviOutputStream = null; log.info("Closed " + lastFileName); } catch (IOException ex) { log.warning(ex.toString()); } } } private void openAVIOutputStream(File f) { try { aviOutputStream = new AVIOutputStream(f, AVIOutputStream.VideoFormat.RAW); aviOutputStream.setFrameRate((int) apsDvsChip.getFrameRateHz()); // aviOutputStream.setVideoDimension(chip.getSizeX(), chip.getSizeY()); lastFileName = f.toString(); putString("lastFileName", lastFileName); log.info("Opened " + f.toString()); framesWritten = 0; } catch (IOException ex) { JOptionPane.showMessageDialog(null, ex.toString(), "Couldn't create output file stream", JOptionPane.WARNING_MESSAGE, null); return; } } }
src/ch/unizh/ini/jaer/projects/davis/frames/DAVISAVIWriter.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.unizh.ini.jaer.projects.davis.frames; import eu.seebetter.ini.chips.ApsDvsChip; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.util.avioutput.AVIOutputStream; /** * Writes AVI file from DAVIS APS frames, using ApsFrameExtractor. * The AVI file is in RAW format with pixel values 0-255 coming from ApsFrameExtractor displayed frames, which are offset and scaled by it. * * @author Tobi */ @Description("Writes AVI file from DAVIS APS frames, using ApsFrameExtractor") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class DAVISAVIWriter extends EventFilter2D implements PropertyChangeListener { ApsFrameExtractor apsFrameExtractor; AVIOutputStream aviOutputStream = null; private String DEFAULT_FILENAME = "DAVIS_APS.avi"; private String lastFileName = getString("lastFileName", DEFAULT_FILENAME); ApsDvsChip apsDvsChip = null; private int framesWritten = 0; private final int logEveryThisManyFrames = 30; public DAVISAVIWriter(AEChip chip) { super(chip); FilterChain filterChain = new FilterChain(chip); apsFrameExtractor = new ApsFrameExtractor(chip); apsFrameExtractor.getSupport().addPropertyChangeListener(this); filterChain.add(apsFrameExtractor); setEnclosedFilterChain(filterChain); setPropertyTooltip("saveAVIFileAs", "Opens the output file. The AVI file is in RAW format with pixel values 0-255 coming from ApsFrameExtractor displayed frames, which are offset and scaled by it."); setPropertyTooltip("closeFile", "Closes the output file if it is open."); } @Override public EventPacket<?> filterPacket(EventPacket<?> in) { apsDvsChip = (ApsDvsChip) chip; apsFrameExtractor.filterPacket(in); return in; } @Override public void resetFilter() { apsFrameExtractor.resetFilter(); } @Override public void initFilter() { apsFrameExtractor.initFilter(); } @Override public void propertyChange(PropertyChangeEvent evt) { if (aviOutputStream != null && evt.getPropertyName() == ApsFrameExtractor.EVENT_NEW_FRAME) { double[] frame = apsFrameExtractor.getNewFrame(); BufferedImage bufferedImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_USHORT_GRAY); WritableRaster raster = bufferedImage.getRaster(); int sx = chip.getSizeX(), sy = chip.getSizeY(); for (int y = 0; y < sy; y++) { for (int x = 0; x < sx; x++) { int k = apsFrameExtractor.getIndex(x, y); // bufferedImage.setRGB(x, y, (int) (frame[k] * 1024)); raster.setSample(x, sy - y - 1, 0, frame[k]*256); // must flip image vertially according to java convention that image starts at upper left } } try { aviOutputStream.writeFrame(bufferedImage); if (++framesWritten % logEveryThisManyFrames == 0) { log.info(String.format("wrote %d frames", framesWritten)); } // apsFrameExtractor.getIndex(x, y); } catch (IOException ex) { Logger.getLogger(DAVISAVIWriter.class.getName()).log(Level.SEVERE, null, ex); } } } synchronized public void doSaveAVIFileAs() { JFileChooser c = new JFileChooser(lastFileName); c.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".avi"); } @Override public String getDescription() { return "AVI (Audio Video Interleave) Microsoft video file"; } }); c.setSelectedFile(new File(lastFileName)); int ret = c.showSaveDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } lastFileName = c.getSelectedFile().toString(); if (c.getSelectedFile().exists()) { int r = JOptionPane.showConfirmDialog(null, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?"); if (r != JOptionPane.OK_OPTION) { return; } } openAVIOutputStream(c.getSelectedFile()); } synchronized public void doCloseFile() { if (aviOutputStream != null) { try { aviOutputStream.close(); aviOutputStream = null; log.info("Closed " + lastFileName); } catch (IOException ex) { log.warning(ex.toString()); } } } private void openAVIOutputStream(File f) { try { aviOutputStream = new AVIOutputStream(f, AVIOutputStream.VideoFormat.RAW); aviOutputStream.setFrameRate((int) apsDvsChip.getFrameRateHz()); // aviOutputStream.setVideoDimension(chip.getSizeX(), chip.getSizeY()); lastFileName = f.toString(); putString("lastFileName", lastFileName); log.info("Opened " + f.toString()); framesWritten = 0; } catch (IOException ex) { JOptionPane.showMessageDialog(null, ex.toString(), "Couldn't create output file stream", JOptionPane.WARNING_MESSAGE, null); return; } } }
changed AVI file to use RGB format for buffered image; now the video plays back correctly in VLC as lovely gray video. git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@5840 b7f4320f-462c-0410-a916-d9f35bb82d52
src/ch/unizh/ini/jaer/projects/davis/frames/DAVISAVIWriter.java
changed AVI file to use RGB format for buffered image; now the video plays back correctly in VLC as lovely gray video.
<ide><path>rc/ch/unizh/ini/jaer/projects/davis/frames/DAVISAVIWriter.java <ide> public void propertyChange(PropertyChangeEvent evt) { <ide> if (aviOutputStream != null && evt.getPropertyName() == ApsFrameExtractor.EVENT_NEW_FRAME) { <ide> double[] frame = apsFrameExtractor.getNewFrame(); <del> BufferedImage bufferedImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_USHORT_GRAY); <add> BufferedImage bufferedImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_3BYTE_BGR); <ide> WritableRaster raster = bufferedImage.getRaster(); <ide> int sx = chip.getSizeX(), sy = chip.getSizeY(); <ide> for (int y = 0; y < sy; y++) { <ide> for (int x = 0; x < sx; x++) { <ide> int k = apsFrameExtractor.getIndex(x, y); <ide> // bufferedImage.setRGB(x, y, (int) (frame[k] * 1024)); <del> raster.setSample(x, sy - y - 1, 0, frame[k]*256); // must flip image vertially according to java convention that image starts at upper left <add> int v=(int)(frame[k]*255), yy=sy - y - 1; // must flip image vertially according to java convention that image starts at upper left <add> raster.setSample(x, yy, 0, v); <add> raster.setSample(x, yy, 1, v); <add> raster.setSample(x, yy, 2, v); <ide> } <ide> } <ide> try {
Java
mit
58c8446b28bd837d8bb04f5bbf0669a40731754c
0
gaborkolozsy/XChange,douggie/XChange,LeonidShamis/XChange,ww3456/XChange,jheusser/XChange,kzbikowski/XChange,nivertech/XChange,npomfret/XChange,mmithril/XChange,evdubs/XChange,jennieolsson/XChange,codeck/XChange,joansmith/XChange,timmolter/XChange,chrisrico/XChange,dozd/XChange,stevenuray/XChange,TSavo/XChange,stachon/XChange,nopy/XChange,okazia/XChange,coingecko/XChange,anwfr/XChange,yarKH/XChange,andre77/XChange,cinjoff/XChange-1,Panchen/XChange,sutra/XChange,Muffon/XChange
package com.xeiam.xchange.cryptsy.service.polling; import java.io.IOException; import java.util.Date; import com.xeiam.xchange.ExchangeException; import com.xeiam.xchange.ExchangeSpecification; import com.xeiam.xchange.NotAvailableFromExchangeException; import com.xeiam.xchange.NotYetImplementedForExchangeException; import com.xeiam.xchange.cryptsy.CryptsyAdapters; import com.xeiam.xchange.cryptsy.CryptsyCurrencyUtils; import com.xeiam.xchange.cryptsy.dto.CryptsyOrder.CryptsyOrderType; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyCancelOrderReturn; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyOpenOrdersReturn; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyPlaceOrderReturn; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyTradeHistoryReturn; import com.xeiam.xchange.dto.Order.OrderType; import com.xeiam.xchange.dto.trade.LimitOrder; import com.xeiam.xchange.dto.trade.MarketOrder; import com.xeiam.xchange.dto.trade.OpenOrders; import com.xeiam.xchange.dto.trade.UserTrades; import com.xeiam.xchange.service.polling.PollingTradeService; import com.xeiam.xchange.service.polling.trade.DefaultTradeHistoryParamsTimeSpan; import com.xeiam.xchange.service.polling.trade.TradeHistoryParams; import com.xeiam.xchange.service.polling.trade.TradeHistoryParamsTimeSpan; /** * @author ObsessiveOrange */ public class CryptsyTradeService extends CryptsyTradeServiceRaw implements PollingTradeService { /** * Constructor * * @param exchangeSpecification * The {@link ExchangeSpecification} */ public CryptsyTradeService(ExchangeSpecification exchangeSpecification) { super(exchangeSpecification); } @Override public OpenOrders getOpenOrders() throws IOException, ExchangeException { CryptsyOpenOrdersReturn openOrdersReturnValue = getCryptsyOpenOrders(); return CryptsyAdapters.adaptOpenOrders(openOrdersReturnValue); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException, ExchangeException { throw new NotAvailableFromExchangeException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException, ExchangeException { CryptsyPlaceOrderReturn result = super.placeCryptsyLimitOrder(CryptsyCurrencyUtils.convertToMarketId(limitOrder.getCurrencyPair()), limitOrder.getType() == OrderType.ASK ? CryptsyOrderType.Sell : CryptsyOrderType.Buy, limitOrder.getTradableAmount(), limitOrder.getLimitPrice()); return Integer.toString(result.getReturnValue()); } @Override public boolean cancelOrder(String orderId) throws IOException, ExchangeException { CryptsyCancelOrderReturn ret = super.cancelSingleCryptsyLimitOrder(Integer.valueOf(orderId)); return ret.isSuccess(); } /** * @param arguments Vararg list of optional (nullable) arguments: * (Long) arguments[0] Number of transactions to return * (String) arguments[1] TradableIdentifier * (String) arguments[2] TransactionCurrency * (Long) arguments[3] Starting ID * @return Trades object * @throws IOException */ @Override public UserTrades getTradeHistory(final Object... arguments) throws IOException, ExchangeException { Date startDate = new Date(0); // default value Date endDate = new Date(); // default value if (arguments.length == 2) { startDate = (Date) arguments[0]; endDate = (Date) arguments[1]; } CryptsyTradeHistoryReturn tradeHistoryReturnData = super.getCryptsyTradeHistory(startDate, endDate); return CryptsyAdapters.adaptTradeHistory(tradeHistoryReturnData); } /** * @param params * Can optionally implement {@link TradeHistoryParamsTimeSpan}. All other * TradeHistoryParams types will be ignored. */ @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { CryptsyTradeHistoryReturn tradeHistoryReturnData; if (params instanceof TradeHistoryParamsTimeSpan) { TradeHistoryParamsTimeSpan timeSpan = (TradeHistoryParamsTimeSpan) params; tradeHistoryReturnData = super.getCryptsyTradeHistory(timeSpan.getStartTime(), timeSpan.getEndTime()); } else { tradeHistoryReturnData = super.getCryptsyTradeHistory(null, null); } return CryptsyAdapters.adaptTradeHistory(tradeHistoryReturnData); } /** * Create {@link TradeHistoryParams} that supports {@link TradeHistoryParamsTimeSpan}. */ @Override public com.xeiam.xchange.service.polling.trade.TradeHistoryParams createTradeHistoryParams() { return new DefaultTradeHistoryParamsTimeSpan(); } }
xchange-cryptsy/src/main/java/com/xeiam/xchange/cryptsy/service/polling/CryptsyTradeService.java
package com.xeiam.xchange.cryptsy.service.polling; import java.io.IOException; import java.util.Date; import com.xeiam.xchange.ExchangeException; import com.xeiam.xchange.ExchangeSpecification; import com.xeiam.xchange.NotAvailableFromExchangeException; import com.xeiam.xchange.NotYetImplementedForExchangeException; import com.xeiam.xchange.cryptsy.CryptsyAdapters; import com.xeiam.xchange.cryptsy.CryptsyCurrencyUtils; import com.xeiam.xchange.cryptsy.dto.CryptsyOrder.CryptsyOrderType; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyCancelOrderReturn; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyOpenOrdersReturn; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyPlaceOrderReturn; import com.xeiam.xchange.cryptsy.dto.trade.CryptsyTradeHistoryReturn; import com.xeiam.xchange.dto.Order.OrderType; import com.xeiam.xchange.dto.trade.LimitOrder; import com.xeiam.xchange.dto.trade.MarketOrder; import com.xeiam.xchange.dto.trade.OpenOrders; import com.xeiam.xchange.dto.trade.UserTrades; import com.xeiam.xchange.service.polling.PollingTradeService; import com.xeiam.xchange.service.polling.trade.TradeHistoryParams; /** * @author ObsessiveOrange */ public class CryptsyTradeService extends CryptsyTradeServiceRaw implements PollingTradeService { /** * Constructor * * @param exchangeSpecification * The {@link ExchangeSpecification} */ public CryptsyTradeService(ExchangeSpecification exchangeSpecification) { super(exchangeSpecification); } @Override public OpenOrders getOpenOrders() throws IOException, ExchangeException { CryptsyOpenOrdersReturn openOrdersReturnValue = getCryptsyOpenOrders(); return CryptsyAdapters.adaptOpenOrders(openOrdersReturnValue); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws IOException, ExchangeException { throw new NotAvailableFromExchangeException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws IOException, ExchangeException { CryptsyPlaceOrderReturn result = super.placeCryptsyLimitOrder(CryptsyCurrencyUtils.convertToMarketId(limitOrder.getCurrencyPair()), limitOrder.getType() == OrderType.ASK ? CryptsyOrderType.Sell : CryptsyOrderType.Buy, limitOrder.getTradableAmount(), limitOrder.getLimitPrice()); return Integer.toString(result.getReturnValue()); } @Override public boolean cancelOrder(String orderId) throws IOException, ExchangeException { CryptsyCancelOrderReturn ret = super.cancelSingleCryptsyLimitOrder(Integer.valueOf(orderId)); return ret.isSuccess(); } /** * @param arguments Vararg list of optional (nullable) arguments: * (Long) arguments[0] Number of transactions to return * (String) arguments[1] TradableIdentifier * (String) arguments[2] TransactionCurrency * (Long) arguments[3] Starting ID * @return Trades object * @throws IOException */ @Override public UserTrades getTradeHistory(final Object... arguments) throws IOException, ExchangeException { Date startDate = new Date(0); // default value Date endDate = new Date(); // default value if (arguments.length == 2) { startDate = (Date) arguments[0]; endDate = (Date) arguments[1]; } CryptsyTradeHistoryReturn tradeHistoryReturnData = super.getCryptsyTradeHistory(startDate, endDate); return CryptsyAdapters.adaptTradeHistory(tradeHistoryReturnData); } @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new NotYetImplementedForExchangeException(); } @Override public com.xeiam.xchange.service.polling.trade.TradeHistoryParams createTradeHistoryParams() { return null; } }
Implement TradeHistoryParams based query.
xchange-cryptsy/src/main/java/com/xeiam/xchange/cryptsy/service/polling/CryptsyTradeService.java
Implement TradeHistoryParams based query.
<ide><path>change-cryptsy/src/main/java/com/xeiam/xchange/cryptsy/service/polling/CryptsyTradeService.java <ide> import com.xeiam.xchange.dto.trade.OpenOrders; <ide> import com.xeiam.xchange.dto.trade.UserTrades; <ide> import com.xeiam.xchange.service.polling.PollingTradeService; <add>import com.xeiam.xchange.service.polling.trade.DefaultTradeHistoryParamsTimeSpan; <ide> import com.xeiam.xchange.service.polling.trade.TradeHistoryParams; <add>import com.xeiam.xchange.service.polling.trade.TradeHistoryParamsTimeSpan; <ide> <ide> /** <ide> * @author ObsessiveOrange <ide> return CryptsyAdapters.adaptTradeHistory(tradeHistoryReturnData); <ide> } <ide> <add> /** <add> * @param params <add> * Can optionally implement {@link TradeHistoryParamsTimeSpan}. All other <add> * TradeHistoryParams types will be ignored. <add> */ <add> <ide> @Override <ide> public UserTrades getTradeHistory(TradeHistoryParams params) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { <ide> <del> throw new NotYetImplementedForExchangeException(); <add> CryptsyTradeHistoryReturn tradeHistoryReturnData; <add> if (params instanceof TradeHistoryParamsTimeSpan) { <add> TradeHistoryParamsTimeSpan timeSpan = (TradeHistoryParamsTimeSpan) params; <add> tradeHistoryReturnData = super.getCryptsyTradeHistory(timeSpan.getStartTime(), timeSpan.getEndTime()); <add> } <add> else { <add> tradeHistoryReturnData = super.getCryptsyTradeHistory(null, null); <add> } <add> return CryptsyAdapters.adaptTradeHistory(tradeHistoryReturnData); <ide> } <add> <add> /** <add> * Create {@link TradeHistoryParams} that supports {@link TradeHistoryParamsTimeSpan}. <add> */ <ide> <ide> @Override <ide> public com.xeiam.xchange.service.polling.trade.TradeHistoryParams createTradeHistoryParams() { <ide> <del> return null; <add> return new DefaultTradeHistoryParamsTimeSpan(); <ide> } <ide> <ide> }
Java
apache-2.0
0c0452b0939f7d5888baef602032dcc17113ff45
0
jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb
package de.fernunihagen.dna.jkn.scalephant.distribution.membership; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fernunihagen.dna.jkn.scalephant.ScalephantService; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceAddEvent; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceDeleteEvent; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceEvent; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceEventCallback; import de.fernunihagen.dna.jkn.scalephant.network.client.ScalephantClient; public class MembershipConnectionService implements ScalephantService, DistributedInstanceEventCallback { /** * The server connections */ protected final Map<DistributedInstance, ScalephantClient> serverConnections; /** * The blacklisted instances, no connection will be created to these systems */ protected Set<DistributedInstance> blacklist = new HashSet<>(); /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(MembershipConnectionService.class); public MembershipConnectionService() { final HashMap<DistributedInstance, ScalephantClient> connectionMap = new HashMap<DistributedInstance, ScalephantClient>(); serverConnections = Collections.synchronizedMap(connectionMap); } /** * Add a system to the blacklist * @param distributedInstance */ public void addSystemToBlacklist(final DistributedInstance distributedInstance) { blacklist.add(distributedInstance); } /** * Init the subsystem */ @Override public void init() { DistributedInstanceManager.getInstance().registerListener(this); // Create connections to existing instances final Set<DistributedInstance> instances = DistributedInstanceManager.getInstance().getInstances(); if(instances.isEmpty()) { logger.warn("The list of instances is empty"); } for(DistributedInstance distributedInstance : instances) { createConnection(distributedInstance); } } /** * Shutdown the subsystem */ @Override public void shutdown() { DistributedInstanceManager.getInstance().removeListener(this); // Close all connections synchronized (serverConnections) { for(final DistributedInstance instance : serverConnections.keySet()) { final ScalephantClient client = serverConnections.get(instance); logger.info("Disconnecting from: " + instance); client.disconnect(); } serverConnections.clear(); } } /** * Get the name for the subsystem */ @Override public String getServicename() { return "Mambership Connection Service"; } /** * Add a new connection to a scalephant system * @param distributedInstance */ protected synchronized void createConnection(final DistributedInstance distributedInstance) { if(serverConnections.containsKey(distributedInstance)) { logger.info("We already have a connection to: " + distributedInstance); return; } if(blacklist.contains(distributedInstance)) { logger.info("Not creating a connection to the blacklisted sysetm: " + distributedInstance); return; } logger.info("Opening connection to new node: " + distributedInstance); final ScalephantClient client = new ScalephantClient(distributedInstance.getInetSocketAddress()); final boolean result = client.connect(); if(! result) { logger.info("Unable to open connection to: " + distributedInstance); } else { logger.info("Connection successfully established: " + distributedInstance); serverConnections.put(distributedInstance, client); } } /** * Terminate the connection to a missing scalephant system * @param distributedInstance */ protected synchronized void terminateConnection(final DistributedInstance distributedInstance) { logger.info("Closing connections to terminating node: " + distributedInstance); if(! serverConnections.containsKey(distributedInstance)) { return; } final ScalephantClient client = serverConnections.remove(distributedInstance); client.disconnect(); } /** * Handle membership events */ @Override public void distributedInstanceEvent(final DistributedInstanceEvent event) { if(event instanceof DistributedInstanceAddEvent) { createConnection(event.getInstance()); } else if(event instanceof DistributedInstanceDeleteEvent) { terminateConnection(event.getInstance()); } else { logger.warn("Unknown event: " + event); } } /** * Get the connection for the instance * @param instance * @return */ public ScalephantClient getConnectionForInstance(final DistributedInstance instance) { return serverConnections.get(instance); } /** * Return the number of connections * @return */ public int getNumberOfConnections() { return serverConnections.size(); } /** * Get all connections * @return */ public List<ScalephantClient> getAllConnections() { return new ArrayList<ScalephantClient>(serverConnections.values()); } /** * Get a list with all distributed instances we have connections to * @return */ public List<DistributedInstance> getAllInstances() { return new ArrayList<DistributedInstance>(serverConnections.keySet()); } }
src/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/membership/MembershipConnectionService.java
package de.fernunihagen.dna.jkn.scalephant.distribution.membership; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fernunihagen.dna.jkn.scalephant.ScalephantService; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceAddEvent; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceDeleteEvent; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceEvent; import de.fernunihagen.dna.jkn.scalephant.distribution.membership.event.DistributedInstanceEventCallback; import de.fernunihagen.dna.jkn.scalephant.network.client.ScalephantClient; public class MembershipConnectionService implements ScalephantService, DistributedInstanceEventCallback { /** * The server connections */ protected final Map<DistributedInstance, ScalephantClient> serverConnections; /** * The blacklisted instances, no connection will be created to these systems */ protected Set<DistributedInstance> blacklist = new HashSet<>(); /** * The Logger */ private final static Logger logger = LoggerFactory.getLogger(MembershipConnectionService.class); public MembershipConnectionService() { final HashMap<DistributedInstance, ScalephantClient> connectionMap = new HashMap<DistributedInstance, ScalephantClient>(); serverConnections = Collections.synchronizedMap(connectionMap); } /** * Add a system to the blacklist * @param distributedInstance */ public void addSystemToBlacklist(final DistributedInstance distributedInstance) { blacklist.add(distributedInstance); } /** * Init the subsystem */ @Override public void init() { DistributedInstanceManager.getInstance().registerListener(this); // Create connections to existing instances final Set<DistributedInstance> instances = DistributedInstanceManager.getInstance().getInstances(); for(DistributedInstance distributedInstance : instances) { createConnection(distributedInstance); } } /** * Shutdown the subsystem */ @Override public void shutdown() { DistributedInstanceManager.getInstance().removeListener(this); // Close all connections synchronized (serverConnections) { for(final DistributedInstance instance : serverConnections.keySet()) { final ScalephantClient client = serverConnections.get(instance); logger.info("Disconnecting from: " + instance); client.disconnect(); } serverConnections.clear(); } } /** * Get the name for the subsystem */ @Override public String getServicename() { return "Mambership Connection Service"; } /** * Add a new connection to a scalephant system * @param distributedInstance */ protected synchronized void createConnection(final DistributedInstance distributedInstance) { if(serverConnections.containsKey(distributedInstance)) { logger.info("We already have a connection to: " + distributedInstance); return; } if(blacklist.contains(distributedInstance)) { logger.info("Not creating a connection to the blacklisted sysetm: " + distributedInstance); return; } logger.info("Opening connection to new node: " + distributedInstance); final ScalephantClient client = new ScalephantClient(distributedInstance.getInetSocketAddress()); final boolean result = client.connect(); if(! result) { logger.info("Unable to open connection to: " + distributedInstance); } else { logger.info("Connection successfully established: " + distributedInstance); serverConnections.put(distributedInstance, client); } } /** * Terminate the connection to a missing scalephant system * @param distributedInstance */ protected synchronized void terminateConnection(final DistributedInstance distributedInstance) { logger.info("Closing connections to terminating node: " + distributedInstance); if(! serverConnections.containsKey(distributedInstance)) { return; } final ScalephantClient client = serverConnections.remove(distributedInstance); client.disconnect(); } /** * Handle membership events */ @Override public void distributedInstanceEvent(final DistributedInstanceEvent event) { if(event instanceof DistributedInstanceAddEvent) { createConnection(event.getInstance()); } else if(event instanceof DistributedInstanceDeleteEvent) { terminateConnection(event.getInstance()); } else { logger.warn("Unknown event: " + event); } } /** * Get the connection for the instance * @param instance * @return */ public ScalephantClient getConnectionForInstance(final DistributedInstance instance) { return serverConnections.get(instance); } /** * Return the number of connections * @return */ public int getNumberOfConnections() { return serverConnections.size(); } /** * Get all connections * @return */ public List<ScalephantClient> getAllConnections() { return new ArrayList<ScalephantClient>(serverConnections.values()); } /** * Get a list with all distributed instances we have connections to * @return */ public List<DistributedInstance> getAllInstances() { return new ArrayList<DistributedInstance>(serverConnections.keySet()); } }
Added log message on empty instance list
src/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/membership/MembershipConnectionService.java
Added log message on empty instance list
<ide><path>rc/main/java/de/fernunihagen/dna/jkn/scalephant/distribution/membership/MembershipConnectionService.java <ide> <ide> // Create connections to existing instances <ide> final Set<DistributedInstance> instances = DistributedInstanceManager.getInstance().getInstances(); <add> <add> if(instances.isEmpty()) { <add> logger.warn("The list of instances is empty"); <add> } <add> <ide> for(DistributedInstance distributedInstance : instances) { <ide> createConnection(distributedInstance); <ide> }
Java
bsd-3-clause
0cc616baf549746949107d31f183980453aed7e1
0
aic-sri-international/aic-expresso,aic-sri-international/aic-expresso
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.test.grinder.library; import java.util.Collection; import org.junit.Test; import com.sri.ai.brewer.api.Grammar; import com.sri.ai.brewer.core.CommonGrammar; import com.sri.ai.expresso.api.Expression; import com.sri.ai.grinder.api.RewritingProcess; import com.sri.ai.grinder.helper.GrinderUtil; import com.sri.ai.grinder.library.DirectCardinalityComputationFactory; import com.sri.ai.grinder.library.equality.cardinality.direct.CardinalityRewriter; import com.sri.ai.grinder.library.equality.cardinality.direct.core.CardinalityTypeOfLogicalVariable; import com.sri.ai.test.grinder.AbstractGrinderTest; import com.sri.ai.test.grinder.TestData; import com.sri.ai.util.Util; public class SimplifyAndCompleteSimplifyTest extends AbstractGrinderTest { @Override public Grammar makeGrammar() { return new CommonGrammar(); } @Test public void testSimplifyPassesBasicTests() { TestData[] tests = new TestData[] { // // Replaces 0*E' by 0 new SimplifyTestData( "0*2", "0"), new SimplifyTestData( "0*p(a)", "0"), new SimplifyTestData( "2*0", "0"), new SimplifyTestData( "p(a)*0", "0"), // // Replaces 1*E' by E' new SimplifyTestData( "1*2", "2"), new SimplifyTestData( "1*p(a)", "p(a)"), new SimplifyTestData( "2*1", "2"), new SimplifyTestData( "p(a)*1", "p(a)"), // // Replaces 0+E' by E' new SimplifyTestData( "0+2", "2"), new SimplifyTestData( "0+p(a)", "p(a)"), new SimplifyTestData( "2+0", "2"), new SimplifyTestData( "p(a)+0", "p(a)"), // // Replaces 0^E' by 0 new SimplifyTestData( "0^2", "0"), new SimplifyTestData( "0^p(a)", "0^p(a)"), // // Replace 0^0 by 1 // see: http://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power // for discussion. new SimplifyTestData( "0^0", "1"), // // Replaces E'^0 by 1 new SimplifyTestData( "2^0", "1"), new SimplifyTestData( "p(a)^0", "1"), // // Replaces E'^1 by E' new SimplifyTestData( "2^1", "2"), new SimplifyTestData( "p(a)^1", "p(a)"), // // Replaces E'/1 by E' new SimplifyTestData( "2/1", "2"), new SimplifyTestData( "p(a)/1", "p(a)"), // // Replaces --E' by E' // Test for resolved issue: JIRA ALBP-69 new SimplifyTestData( "--2", "2"), // TODO - need fix for ALBP-68, currently returns --p(a) // new SimplifyTestData( // "--p(a)", // "p(a)"), // // Replaces E'-0 by E' new SimplifyTestData( "2-0", "2"), new SimplifyTestData( "p(a)-0", "p(a)"), // // Replaces 0-E' by -E' // Note: I use (-2) here instead of 2 // as the result is the numeric valued // symbol -2. However, when I parse // "-2" directly I get the function appliction // -(2), which is correct but does not compare // correctly, so using (-2) gets around this. // Test for resolved issue: JIRA ALBP-69 new SimplifyTestData( "0-(-2)", "2"), // Test for resolved issue: JIRA ALBP-69 new SimplifyTestData( "0-p(a)", "-p(a)"), // // Replaces false and E' by false new SimplifyTestData( "false and p(a)", "false"), // // Replaces true and E' by E' new SimplifyTestData( "true and p(a)", "p(a)"), // // Replaces false or E' by E' new SimplifyTestData( "false or p(a)", "p(a)"), // // Replaces true or E' by true new SimplifyTestData( "true or p(a)", "true"), // // Replaces not not E' by E' new SimplifyTestData( "not not p(a)", "p(a)"), // // Replaces not true by false new SimplifyTestData( "not true", "false"), // // Replaces not false by true. new SimplifyTestData( "not false", "true"), // // Replaces if true then E' else E'' by E' new SimplifyTestData( "if true then p(a) else p(b)", "p(a)"), // // Replaces if false then E' else E'' by E'' new SimplifyTestData( "if false then p(a) else p(b)", "p(b)"), // // Replaces if C then E' else E' by E' new SimplifyTestData( "if p(b) then p(a) else p(a)", "p(a)"), new SimplifyTestData( "if X = Y then p(a) else p(a)", "p(a)"), // // Replaces function applications of numeric operations on // actual numbers by its result new SimplifyTestData( "4+2", "6"), new SimplifyTestData( "4-2", "2"), new SimplifyTestData( "4*2", "8"), new SimplifyTestData( "4/2", "2"), new SimplifyTestData( "4^2", "16"), // // Replaces function applications of boolean operations // on actual boolean values by its result // TODO - add tests // // Externalizes Conditionals // TODO - add tests // Tests for resolved issue: JIRA ALBP-31 new SimplifyTestData( "{ B, (if A = B then C else D) }", "if A = B then { B, C } else { B, D }"), new SimplifyTestData( "{ if A = B then C else D }", "if A = B then { C } else { D }"), // Tests for resolved issue: JIRA ALBP-51 new SimplifyTestData( "if A = B then if B = A then 1 else 2 else 3", "if A = B then 1 else 3"), // Tests for resolved issue: JIRA ALBP-51 new SimplifyTestData( "if B = A then {C} else if A = B then {D} else {E}", "if B = A then {C} else {E}"), // TODO - test injective functions. // TODO - test exclusive ranges. }; perform(tests); } @Test public void testSimplifyAsDescribedInPapers() { // // Tests based on how simplification should work, as described in: // /aic-smf/doc/papers/CP 2012/CP 2012 submitted version with revisions // /aic-smf/doc/papers/CP 2012/StaRAI-12 TestData[] tests = new TestData[] { // // Basic: 1. if-then-elses are externalized. new SimplifyTestData( "and(A = a, (if B = b then C = c else C = d), E = e)", "A = a and (B = b and C = c or B != b and C = d) and E = e"), //"B = b and A = a and C = c and E = e or B != b and A = a and C = d and E = e"), // Note: before FromConditionalFormulaToFormula, used to be // if B = b then and(A = a, C = c, E = e) else and(A = a, C = d, E = e) // // Basic: 2. Operations on constants are performed. new SimplifyTestData( "2 + 2", "4"), new SimplifyTestData( "not(0 = 1)", "true"), new SimplifyTestData( "0 = 1", "false"), new SimplifyTestData( "a = a", "true"), new SimplifyTestData( "a = b", "false"), new SimplifyTestData( "not(false)", "true"), new SimplifyTestData( "not(true)", "false"), new SimplifyTestData( "and(false, true)", "false"), new SimplifyTestData( "or(false, true)", "true"), new SimplifyTestData( "if true then 1 else 2", "1"), new SimplifyTestData( "if false then 1 else 2", "2"), // // Basic: 3. Operations whose results can be defined // by a subset of their arguments equal to certain constants. new SimplifyTestData( "and(false, X = Y)", "false"), new SimplifyTestData( "0 + 5", "5"), new SimplifyTestData( "5 - 0", "5"), new SimplifyTestData( "0 * 5", "0"), new SimplifyTestData( "0 * | X != a |", "0"), new SimplifyTestData( "1 * 5", "5"), new SimplifyTestData( "if true then | X = a | else 2", "| X = a |"), new SimplifyTestData( "if X != a then true else true", "true"), new SimplifyTestData( "if X != a then false else false", "false"), // // Basic: 4 equalities and disequalities on formulas new SimplifyTestData( "X = X", "true"), new SimplifyTestData( "X != X", "false"), // Note: as we support normalization (i.e. an ordering) // on equalities and disequalities the following // will simplify. new SimplifyTestData( "(X != x) = (x != X)", "true"), new SimplifyTestData( "(X != x) != (x != X)", "false"), // // Basic: 5 conjuncts with equality on different constants new SimplifyTestData( "and(X = a, X = b)", "false"), new SimplifyTestData( "and(X = a, b = X)", "false"), // // Basic: 6 conjuncts with equality and inequality on the same term new SimplifyTestData( "and(X = a, X != a)", "false"), new SimplifyTestData( "and(X = a, a != X)", "false"), new SimplifyTestData( "and(X = Y, X != Y)", "false"), new SimplifyTestData( "and(X = Y, Y != X)", "false"), // // Basic: 7 transitive equalities results in a contradiction // Note: requires complete simplification. // Note: replacement of transitive equalities in conjuncts, i.e: // // and(X != a, X = Y, Y != b) -> and(X != a, X = Y, X != b) // // has been decided not to be needed as R_implied_certainty // will pick out if its a contradiction anyway. So the // following case will not simplify. new SimplifyTestData( "and(X != a, X = Y, Y != b)", "and(X != a, X = Y, Y != b)"), // // Basic: 8. False if not satisfiable new SimplifyTestData( "true => false", "false"), new SimplifyTestData( "X = X => X != X", "false"), // // Basic: 9. True if not falsifiable new SimplifyTestData( "true => true", "true"), new SimplifyTestData( "X = X => X = X", "true"), // // Basic: 10. if-then-else, true false sub-formula replacement new SimplifyTestData( "if X = a then if X = b then 1 else 2 else 3", "if X = a then 2 else 3"), new SimplifyTestData( "if X = a then if X != b then 1 else 2 else 3", "if X = a then 1 else 3"), }; perform(tests); } @Test public void testSimplifyNonFormulaConditionalTests() { TestData[] tests = new TestData[] { // // Basic: new SimplifyTestData( "+((if not query then 1 else 0) * 2, (if query then 1 else 0) * 3)", "if not query then 2 else 3"), }; perform(tests); } @Test public void testCompleteSimplifyRequired() { TestData[] tests = new TestData[] { // Tests for resolved issue: JIRA ALBP-53 new CompleteSimplifyTestData( "if A = C then {Z1} else if B = C then if A = B then {Z2} else {Z3} else {Z4}", "if A = C then {Z1} else if B = C then {Z3} else {Z4}"), // // Basic: 7 transitive equalities results in a contradiction // Note: requires complete simplification. new CompleteSimplifyTestData( "and(X = a, X = Y, Y != a)", "false"), }; perform(tests); } @Test public void testCompleteSimplifyPerformance() { TestData[] tests = new TestData[] { // This is a contradiction new CompleteSimplifyTestDataWithContext( Util.list(parse("X"), parse("Y")), "Y != X and (X = dave and Y = bob or Y = dave and X = bob)", "Y != X and (X = dave and Y = bob or Y = dave and X = bob) and X = dave and Y = bob", "X = dave and Y = bob"), }; perform(tests); } @Test public void testCompleteSimplifyContradictions() { TestData[] tests = new TestData[] { // This is a contradiction new CompleteSimplifyTestData( "X = w7 => not(X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z))", "true"), // This is the same contradiction just formulated slightly differently new CompleteSimplifyTestData( "not(X != w7) => not(X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z))", "true"), new CompleteSimplifyTestData( "X = w7 and X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z)", "false"), new CompleteSimplifyTestData( "not(X != w7) and X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z)", "false"), }; perform(tests); } @Test public void testCompleteSimplifyUnreachableBranch() { TestData[] tests = new TestData[] { new CompleteSimplifyTestData( "if X = person1 or X = person2 or X = person3 then (if X != person1 and X != person2 and X != person3 then 1 else 2) else 3", "if X = person1 or X = person2 or X = person3 then 2 else 3"), new CompleteSimplifyTestData( "if X != w7 then 1 else (if (X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z)) then 2 else 3)", "if X != w7 then 1 else 3"), }; perform(tests); } // // PRIVATE METHODS // class SimplifyTestData extends TestData implements CardinalityTypeOfLogicalVariable.DomainSizeOfLogicalVariable { private String expressionString; private Expression expression; public SimplifyTestData(String expressionString, String expected) { super(false, expected); this.expressionString = expressionString; }; // // START-DomainSizeOfLogicalVariable @Override public Integer size(Expression logicalVariable, RewritingProcess process) { return 100; // Default to this } // END-DomainSizeOfLogicalVariable // @Override public Expression getTopExpression() { this.expression = parse(expressionString); return expression; } @Override public Expression callRewrite(RewritingProcess process) { // Ensure explicit counts added for all variable domains. CardinalityTypeOfLogicalVariable.registerDomainSizeOfLogicalVariableWithProcess(this, process); Expression result = DirectCardinalityComputationFactory.newCardinalityProcess(expression, process).rewrite(getSimplifyName(), expression); return result; } // // PROTECTED // protected String getSimplifyName() { return CardinalityRewriter.R_simplify; } }; class CompleteSimplifyTestData extends SimplifyTestData { public CompleteSimplifyTestData(String expressionString, String expected) { super(expressionString, expected); }; @Override protected String getSimplifyName() { return CardinalityRewriter.R_complete_simplify; } }; class CompleteSimplifyTestDataWithContext extends CompleteSimplifyTestData { private Expression context; private Collection<Expression> contextualVariables; public CompleteSimplifyTestDataWithContext(Collection<Expression> contextualVariables, String context, String expressionString, String expected) { super(expressionString, expected); this.contextualVariables = contextualVariables; this.context = parse(context); }; @Override public Expression callRewrite(RewritingProcess process) { process = GrinderUtil.extendContextualVariablesAndConstraint(contextualVariables, context, process); return super.callRewrite(process); } }; }
src/test/java/com/sri/ai/test/grinder/library/SimplifyAndCompleteSimplifyTest.java
/* * Copyright (c) 2013, SRI International * All rights reserved. * Licensed under the The BSD 3-Clause License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/BSD-3-Clause * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the aic-expresso nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sri.ai.test.grinder.library; import org.junit.Test; import com.sri.ai.brewer.api.Grammar; import com.sri.ai.brewer.core.CommonGrammar; import com.sri.ai.expresso.api.Expression; import com.sri.ai.grinder.api.RewritingProcess; import com.sri.ai.grinder.library.DirectCardinalityComputationFactory; import com.sri.ai.grinder.library.equality.cardinality.direct.CardinalityRewriter; import com.sri.ai.grinder.library.equality.cardinality.direct.core.CardinalityTypeOfLogicalVariable; import com.sri.ai.test.grinder.AbstractGrinderTest; import com.sri.ai.test.grinder.TestData; public class SimplifyAndCompleteSimplifyTest extends AbstractGrinderTest { @Override public Grammar makeGrammar() { return new CommonGrammar(); } @Test public void testSimplifyPassesBasicTests() { TestData[] tests = new TestData[] { // // Replaces 0*E' by 0 new SimplifyTestData( "0*2", "0"), new SimplifyTestData( "0*p(a)", "0"), new SimplifyTestData( "2*0", "0"), new SimplifyTestData( "p(a)*0", "0"), // // Replaces 1*E' by E' new SimplifyTestData( "1*2", "2"), new SimplifyTestData( "1*p(a)", "p(a)"), new SimplifyTestData( "2*1", "2"), new SimplifyTestData( "p(a)*1", "p(a)"), // // Replaces 0+E' by E' new SimplifyTestData( "0+2", "2"), new SimplifyTestData( "0+p(a)", "p(a)"), new SimplifyTestData( "2+0", "2"), new SimplifyTestData( "p(a)+0", "p(a)"), // // Replaces 0^E' by 0 new SimplifyTestData( "0^2", "0"), new SimplifyTestData( "0^p(a)", "0^p(a)"), // // Replace 0^0 by 1 // see: http://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power // for discussion. new SimplifyTestData( "0^0", "1"), // // Replaces E'^0 by 1 new SimplifyTestData( "2^0", "1"), new SimplifyTestData( "p(a)^0", "1"), // // Replaces E'^1 by E' new SimplifyTestData( "2^1", "2"), new SimplifyTestData( "p(a)^1", "p(a)"), // // Replaces E'/1 by E' new SimplifyTestData( "2/1", "2"), new SimplifyTestData( "p(a)/1", "p(a)"), // // Replaces --E' by E' // Test for resolved issue: JIRA ALBP-69 new SimplifyTestData( "--2", "2"), // TODO - need fix for ALBP-68, currently returns --p(a) // new SimplifyTestData( // "--p(a)", // "p(a)"), // // Replaces E'-0 by E' new SimplifyTestData( "2-0", "2"), new SimplifyTestData( "p(a)-0", "p(a)"), // // Replaces 0-E' by -E' // Note: I use (-2) here instead of 2 // as the result is the numeric valued // symbol -2. However, when I parse // "-2" directly I get the function appliction // -(2), which is correct but does not compare // correctly, so using (-2) gets around this. // Test for resolved issue: JIRA ALBP-69 new SimplifyTestData( "0-(-2)", "2"), // Test for resolved issue: JIRA ALBP-69 new SimplifyTestData( "0-p(a)", "-p(a)"), // // Replaces false and E' by false new SimplifyTestData( "false and p(a)", "false"), // // Replaces true and E' by E' new SimplifyTestData( "true and p(a)", "p(a)"), // // Replaces false or E' by E' new SimplifyTestData( "false or p(a)", "p(a)"), // // Replaces true or E' by true new SimplifyTestData( "true or p(a)", "true"), // // Replaces not not E' by E' new SimplifyTestData( "not not p(a)", "p(a)"), // // Replaces not true by false new SimplifyTestData( "not true", "false"), // // Replaces not false by true. new SimplifyTestData( "not false", "true"), // // Replaces if true then E' else E'' by E' new SimplifyTestData( "if true then p(a) else p(b)", "p(a)"), // // Replaces if false then E' else E'' by E'' new SimplifyTestData( "if false then p(a) else p(b)", "p(b)"), // // Replaces if C then E' else E' by E' new SimplifyTestData( "if p(b) then p(a) else p(a)", "p(a)"), new SimplifyTestData( "if X = Y then p(a) else p(a)", "p(a)"), // // Replaces function applications of numeric operations on // actual numbers by its result new SimplifyTestData( "4+2", "6"), new SimplifyTestData( "4-2", "2"), new SimplifyTestData( "4*2", "8"), new SimplifyTestData( "4/2", "2"), new SimplifyTestData( "4^2", "16"), // // Replaces function applications of boolean operations // on actual boolean values by its result // TODO - add tests // // Externalizes Conditionals // TODO - add tests // Tests for resolved issue: JIRA ALBP-31 new SimplifyTestData( "{ B, (if A = B then C else D) }", "if A = B then { B, C } else { B, D }"), new SimplifyTestData( "{ if A = B then C else D }", "if A = B then { C } else { D }"), // Tests for resolved issue: JIRA ALBP-51 new SimplifyTestData( "if A = B then if B = A then 1 else 2 else 3", "if A = B then 1 else 3"), // Tests for resolved issue: JIRA ALBP-51 new SimplifyTestData( "if B = A then {C} else if A = B then {D} else {E}", "if B = A then {C} else {E}"), // TODO - test injective functions. // TODO - test exclusive ranges. }; perform(tests); } @Test public void testSimplifyAsDescribedInPapers() { // // Tests based on how simplification should work, as described in: // /aic-smf/doc/papers/CP 2012/CP 2012 submitted version with revisions // /aic-smf/doc/papers/CP 2012/StaRAI-12 TestData[] tests = new TestData[] { // // Basic: 1. if-then-elses are externalized. new SimplifyTestData( "and(A = a, (if B = b then C = c else C = d), E = e)", "A = a and (B = b and C = c or B != b and C = d) and E = e"), //"B = b and A = a and C = c and E = e or B != b and A = a and C = d and E = e"), // Note: before FromConditionalFormulaToFormula, used to be // if B = b then and(A = a, C = c, E = e) else and(A = a, C = d, E = e) // // Basic: 2. Operations on constants are performed. new SimplifyTestData( "2 + 2", "4"), new SimplifyTestData( "not(0 = 1)", "true"), new SimplifyTestData( "0 = 1", "false"), new SimplifyTestData( "a = a", "true"), new SimplifyTestData( "a = b", "false"), new SimplifyTestData( "not(false)", "true"), new SimplifyTestData( "not(true)", "false"), new SimplifyTestData( "and(false, true)", "false"), new SimplifyTestData( "or(false, true)", "true"), new SimplifyTestData( "if true then 1 else 2", "1"), new SimplifyTestData( "if false then 1 else 2", "2"), // // Basic: 3. Operations whose results can be defined // by a subset of their arguments equal to certain constants. new SimplifyTestData( "and(false, X = Y)", "false"), new SimplifyTestData( "0 + 5", "5"), new SimplifyTestData( "5 - 0", "5"), new SimplifyTestData( "0 * 5", "0"), new SimplifyTestData( "0 * | X != a |", "0"), new SimplifyTestData( "1 * 5", "5"), new SimplifyTestData( "if true then | X = a | else 2", "| X = a |"), new SimplifyTestData( "if X != a then true else true", "true"), new SimplifyTestData( "if X != a then false else false", "false"), // // Basic: 4 equalities and disequalities on formulas new SimplifyTestData( "X = X", "true"), new SimplifyTestData( "X != X", "false"), // Note: as we support normalization (i.e. an ordering) // on equalities and disequalities the following // will simplify. new SimplifyTestData( "(X != x) = (x != X)", "true"), new SimplifyTestData( "(X != x) != (x != X)", "false"), // // Basic: 5 conjuncts with equality on different constants new SimplifyTestData( "and(X = a, X = b)", "false"), new SimplifyTestData( "and(X = a, b = X)", "false"), // // Basic: 6 conjuncts with equality and inequality on the same term new SimplifyTestData( "and(X = a, X != a)", "false"), new SimplifyTestData( "and(X = a, a != X)", "false"), new SimplifyTestData( "and(X = Y, X != Y)", "false"), new SimplifyTestData( "and(X = Y, Y != X)", "false"), // // Basic: 7 transitive equalities results in a contradiction // Note: requires complete simplification. // Note: replacement of transitive equalities in conjuncts, i.e: // // and(X != a, X = Y, Y != b) -> and(X != a, X = Y, X != b) // // has been decided not to be needed as R_implied_certainty // will pick out if its a contradiction anyway. So the // following case will not simplify. new SimplifyTestData( "and(X != a, X = Y, Y != b)", "and(X != a, X = Y, Y != b)"), // // Basic: 8. False if not satisfiable new SimplifyTestData( "true => false", "false"), new SimplifyTestData( "X = X => X != X", "false"), // // Basic: 9. True if not falsifiable new SimplifyTestData( "true => true", "true"), new SimplifyTestData( "X = X => X = X", "true"), // // Basic: 10. if-then-else, true false sub-formula replacement new SimplifyTestData( "if X = a then if X = b then 1 else 2 else 3", "if X = a then 2 else 3"), new SimplifyTestData( "if X = a then if X != b then 1 else 2 else 3", "if X = a then 1 else 3"), }; perform(tests); } @Test public void testSimplifyNonFormulaConditionalTests() { TestData[] tests = new TestData[] { // // Basic: new SimplifyTestData( "+((if not query then 1 else 0) * 2, (if query then 1 else 0) * 3)", "if not query then 2 else 3"), }; perform(tests); } @Test public void testCompleteSimplifyRequired() { TestData[] tests = new TestData[] { // Tests for resolved issue: JIRA ALBP-53 new CompleteSimplifyTestData( "if A = C then {Z1} else if B = C then if A = B then {Z2} else {Z3} else {Z4}", "if A = C then {Z1} else if B = C then {Z3} else {Z4}"), // // Basic: 7 transitive equalities results in a contradiction // Note: requires complete simplification. new CompleteSimplifyTestData( "and(X = a, X = Y, Y != a)", "false"), }; perform(tests); } @Test public void testCompleteSimplifyContradictions() { TestData[] tests = new TestData[] { // This is a contradiction new CompleteSimplifyTestData( "X = w7 => not(X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z))", "true"), // This is the same contradiction just formulated slightly differently new CompleteSimplifyTestData( "not(X != w7) => not(X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z))", "true"), new CompleteSimplifyTestData( "X = w7 and X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z)", "false"), new CompleteSimplifyTestData( "not(X != w7) and X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z)", "false"), }; perform(tests); } @Test public void testCompleteSimplifyUnreachableBranch() { TestData[] tests = new TestData[] { new CompleteSimplifyTestData( "if X = person1 or X = person2 or X = person3 then (if X != person1 and X != person2 and X != person3 then 1 else 2) else 3", "if X = person1 or X = person2 or X = person3 then 2 else 3"), new CompleteSimplifyTestData( "if X != w7 then 1 else (if (X0 != Y and X0 != Z and Z != Y and (X0 = w7 and X = Y or X0 = w7 and X = Z)) then 2 else 3)", "if X != w7 then 1 else 3"), }; perform(tests); } // // PRIVATE METHODS // class SimplifyTestData extends TestData implements CardinalityTypeOfLogicalVariable.DomainSizeOfLogicalVariable { private String expressionString; private Expression expression; public SimplifyTestData(String expressionString, String expected) { super(false, expected); this.expressionString = expressionString; }; // // START-DomainSizeOfLogicalVariable @Override public Integer size(Expression logicalVariable, RewritingProcess process) { return 100; // Default to this } // END-DomainSizeOfLogicalVariable // @Override public Expression getTopExpression() { this.expression = parse(expressionString); return expression; } @Override public Expression callRewrite(RewritingProcess process) { // Ensure explicit counts added for all variable domains. CardinalityTypeOfLogicalVariable.registerDomainSizeOfLogicalVariableWithProcess(this, process); Expression result = DirectCardinalityComputationFactory.newCardinalityProcess(expression, process).rewrite(getSimplifyName(), expression); return result; } // // PROTECTED // protected String getSimplifyName() { return CardinalityRewriter.R_simplify; } }; class CompleteSimplifyTestData extends SimplifyTestData { public CompleteSimplifyTestData(String expressionString, String expected) { super(expressionString, expected); }; @Override protected String getSimplifyName() { return CardinalityRewriter.R_complete_simplify; } }; }
Added a complete simplify performance test.
src/test/java/com/sri/ai/test/grinder/library/SimplifyAndCompleteSimplifyTest.java
Added a complete simplify performance test.
<ide><path>rc/test/java/com/sri/ai/test/grinder/library/SimplifyAndCompleteSimplifyTest.java <ide> */ <ide> package com.sri.ai.test.grinder.library; <ide> <add>import java.util.Collection; <add> <ide> import org.junit.Test; <ide> <ide> import com.sri.ai.brewer.api.Grammar; <ide> import com.sri.ai.brewer.core.CommonGrammar; <ide> import com.sri.ai.expresso.api.Expression; <ide> import com.sri.ai.grinder.api.RewritingProcess; <add>import com.sri.ai.grinder.helper.GrinderUtil; <ide> import com.sri.ai.grinder.library.DirectCardinalityComputationFactory; <ide> import com.sri.ai.grinder.library.equality.cardinality.direct.CardinalityRewriter; <ide> import com.sri.ai.grinder.library.equality.cardinality.direct.core.CardinalityTypeOfLogicalVariable; <ide> import com.sri.ai.test.grinder.AbstractGrinderTest; <ide> import com.sri.ai.test.grinder.TestData; <add>import com.sri.ai.util.Util; <ide> <ide> public class SimplifyAndCompleteSimplifyTest extends AbstractGrinderTest { <ide> <ide> }; <ide> <ide> perform(tests); <add> } <add> <add> @Test <add> public void testCompleteSimplifyPerformance() { <add> TestData[] tests = new TestData[] { <add> // This is a contradiction <add> new CompleteSimplifyTestDataWithContext( <add> Util.list(parse("X"), parse("Y")), <add> "Y != X and (X = dave and Y = bob or Y = dave and X = bob)", <add> "Y != X and (X = dave and Y = bob or Y = dave and X = bob) and X = dave and Y = bob", <add> "X = dave and Y = bob"), <add> }; <add> <add> perform(tests); <ide> } <ide> <ide> @Test <ide> return CardinalityRewriter.R_complete_simplify; <ide> } <ide> }; <add> <add> class CompleteSimplifyTestDataWithContext extends CompleteSimplifyTestData { <add> <add> private Expression context; <add> private Collection<Expression> contextualVariables; <add> <add> public CompleteSimplifyTestDataWithContext(Collection<Expression> contextualVariables, String context, String expressionString, String expected) { <add> super(expressionString, expected); <add> this.contextualVariables = contextualVariables; <add> this.context = parse(context); <add> }; <add> <add> @Override <add> public Expression callRewrite(RewritingProcess process) { <add> process = GrinderUtil.extendContextualVariablesAndConstraint(contextualVariables, context, process); <add> return super.callRewrite(process); <add> } <add> }; <ide> }
Java
epl-1.0
error: pathspec 'ms-common/src/test/java/net/trajano/ms/common/test/ErrorResponseTest.java' did not match any file(s) known to git
8ae0994cc0dff7bdc98011e77f9f26221d1c6092
1
trajano/app-ms,trajano/app-ms,trajano/app-ms
package net.trajano.ms.common.test; import net.trajano.ms.core.ErrorResponse; import org.junit.Test; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.UriInfo; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; public class ErrorResponseTest { @Test public void errorWithNoStackTraces() { ErrorResponse response = new ErrorResponse(new IOException("ahem"), mock(HttpHeaders.class), mock(UriInfo.class), false, false); assertNull(response.getStackTrace()); assertNull(response.getCause()); } @Test public void chainedErrorButNoStackTrace() { ErrorResponse response = new ErrorResponse(new IOException("ahem", new IllegalStateException()), mock(HttpHeaders.class), mock(UriInfo.class), false, false); assertNull(response.getStackTrace()); assertNull(response.getCause()); } @Test public void thrownError() { ErrorResponse response = new ErrorResponse(new IOException("ahem"), mock(HttpHeaders.class), mock(UriInfo.class), true, false); assertNotNull(response.getStackTrace()); assertNull(response.getCause()); } @Test public void chainedError() { ErrorResponse response = new ErrorResponse(new IOException("ahem", new IllegalStateException()), mock(HttpHeaders.class), mock(UriInfo.class), true, false); assertNotNull(response.getStackTrace()); assertNotNull(response.getCause()); } @Test public void simpleError() { ErrorResponse response = new ErrorResponse("error", "error description", "request id"); assertEquals("error", response.getError()); assertEquals("error description", response.getErrorDescription()); assertEquals("request id", response.getRequestId()); assertNull(response.getStackTrace()); assertNull(response.getCause()); } }
ms-common/src/test/java/net/trajano/ms/common/test/ErrorResponseTest.java
Added tests for error response
ms-common/src/test/java/net/trajano/ms/common/test/ErrorResponseTest.java
Added tests for error response
<ide><path>s-common/src/test/java/net/trajano/ms/common/test/ErrorResponseTest.java <add>package net.trajano.ms.common.test; <add> <add>import net.trajano.ms.core.ErrorResponse; <add>import org.junit.Test; <add> <add>import javax.ws.rs.core.HttpHeaders; <add>import javax.ws.rs.core.UriInfo; <add>import java.io.IOException; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add>import static org.junit.Assert.assertNull; <add>import static org.mockito.Mockito.mock; <add> <add>public class ErrorResponseTest { <add> @Test <add> public void errorWithNoStackTraces() { <add> ErrorResponse response = new ErrorResponse(new IOException("ahem"), mock(HttpHeaders.class), mock(UriInfo.class), false, false); <add> assertNull(response.getStackTrace()); <add> assertNull(response.getCause()); <add> } <add> @Test <add> public void chainedErrorButNoStackTrace() { <add> ErrorResponse response = new ErrorResponse(new IOException("ahem", new IllegalStateException()), mock(HttpHeaders.class), mock(UriInfo.class), false, false); <add> assertNull(response.getStackTrace()); <add> assertNull(response.getCause()); <add> } <add> <add> @Test <add> public void thrownError() { <add> ErrorResponse response = new ErrorResponse(new IOException("ahem"), mock(HttpHeaders.class), mock(UriInfo.class), true, false); <add> assertNotNull(response.getStackTrace()); <add> assertNull(response.getCause()); <add> } <add> <add> @Test <add> public void chainedError() { <add> ErrorResponse response = new ErrorResponse(new IOException("ahem", new IllegalStateException()), mock(HttpHeaders.class), mock(UriInfo.class), true, false); <add> assertNotNull(response.getStackTrace()); <add> assertNotNull(response.getCause()); <add> } <add> <add> @Test <add> public void simpleError() { <add> ErrorResponse response = new ErrorResponse("error", "error description", "request id"); <add> assertEquals("error", response.getError()); <add> assertEquals("error description", response.getErrorDescription()); <add> assertEquals("request id", response.getRequestId()); <add> assertNull(response.getStackTrace()); <add> assertNull(response.getCause()); <add> } <add> <add>}
JavaScript
apache-2.0
beb27334581d22270aa65cf1d882db8380b5b811
0
AndyDiamondstein/vitess,atyenoria/vitess,guokeno0/vitess,pivanof/vitess,xgwubin/vitess,applift/vitess,aaijazi/vitess,erzel/vitess,applift/vitess,ptomasroos/vitess,rnavarro/vitess,mlc0202/vitess,pivanof/vitess,michael-berlin/vitess,rnavarro/vitess,atyenoria/vitess,yaoshengzhe/vitess,tirsen/vitess,mapbased/vitess,vitessio/vitess,rnavarro/vitess,rnavarro/vitess,AndyDiamondstein/vitess,davygeek/vitess,mapbased/vitess,xgwubin/vitess,yaoshengzhe/vitess,yaoshengzhe/vitess,kmiku7/vitess-annotated,yaoshengzhe/vitess,cloudbearings/vitess,erzel/vitess,mlc0202/vitess,anusornc/vitess,skyportsystems/vitess,aaijazi/vitess,sougou/vitess,pivanof/vitess,cloudbearings/vitess,mattharden/vitess,erzel/vitess,mlc0202/vitess,mlc0202/vitess,mapbased/vitess,mattharden/vitess,tirsen/vitess,tirsen/vitess,michael-berlin/vitess,AndyDiamondstein/vitess,yangzhongj/vitess,vitessio/vitess,alainjobart/vitess,vitessio/vitess,nurblieh/vitess,tirsen/vitess,enisoc/vitess,tirsen/vitess,HubSpot/vitess,guokeno0/vitess,kuipertan/vitess,pivanof/vitess,fengshao0907/vitess,dumbunny/vitess,erzel/vitess,mattharden/vitess,dumbunny/vitess,mattharden/vitess,ptomasroos/vitess,tinyspeck/vitess,AndyDiamondstein/vitess,atyenoria/vitess,mapbased/vitess,mattharden/vitess,alainjobart/vitess,HubSpot/vitess,fengshao0907/vitess,kuipertan/vitess,yaoshengzhe/vitess,mahak/vitess,AndyDiamondstein/vitess,nurblieh/vitess,erzel/vitess,michael-berlin/vitess,fengshao0907/vitess,yangzhongj/vitess,fengshao0907/vitess,cloudbearings/vitess,mattharden/vitess,mahak/vitess,rnavarro/vitess,pivanof/vitess,HubSpot/vitess,applift/vitess,kmiku7/vitess-annotated,guokeno0/vitess,enisoc/vitess,anusornc/vitess,AndyDiamondstein/vitess,HubSpot/vitess,ptomasroos/vitess,anusornc/vitess,erzel/vitess,applift/vitess,enisoc/vitess,xgwubin/vitess,mapbased/vitess,michael-berlin/vitess,skyportsystems/vitess,cgvarela/vitess,dumbunny/vitess,HubSpot/vitess,skyportsystems/vitess,tirsen/vitess,kuipertan/vitess,mapbased/vitess,aaijazi/vitess,tinyspeck/vitess,atyenoria/vitess,tjyang/vitess,applift/vitess,tjyang/vitess,tjyang/vitess,cloudbearings/vitess,fengshao0907/vitess,sougou/vitess,AndyDiamondstein/vitess,cgvarela/vitess,guokeno0/vitess,cgvarela/vitess,cgvarela/vitess,ptomasroos/vitess,nurblieh/vitess,tjyang/vitess,dumbunny/vitess,kmiku7/vitess-annotated,anusornc/vitess,xgwubin/vitess,applift/vitess,HubSpot/vitess,yaoshengzhe/vitess,tirsen/vitess,nurblieh/vitess,nurblieh/vitess,dumbunny/vitess,HubSpot/vitess,kmiku7/vitess-annotated,xgwubin/vitess,yaoshengzhe/vitess,yangzhongj/vitess,atyenoria/vitess,kmiku7/vitess-annotated,anusornc/vitess,kmiku7/vitess-annotated,applift/vitess,yangzhongj/vitess,mlc0202/vitess,mattharden/vitess,tjyang/vitess,aaijazi/vitess,tinyspeck/vitess,alainjobart/vitess,aaijazi/vitess,xgwubin/vitess,tirsen/vitess,rnavarro/vitess,yangzhongj/vitess,xgwubin/vitess,guokeno0/vitess,kuipertan/vitess,tirsen/vitess,ptomasroos/vitess,mapbased/vitess,cgvarela/vitess,ptomasroos/vitess,alainjobart/vitess,anusornc/vitess,michael-berlin/vitess,mahak/vitess,dcadevil/vitess,ptomasroos/vitess,kuipertan/vitess,tjyang/vitess,pivanof/vitess,vitessio/vitess,guokeno0/vitess,mahak/vitess,michael-berlin/vitess,tjyang/vitess,enisoc/vitess,dcadevil/vitess,mattharden/vitess,cgvarela/vitess,mahak/vitess,cgvarela/vitess,anusornc/vitess,vitessio/vitess,dcadevil/vitess,vitessio/vitess,mahak/vitess,ptomasroos/vitess,atyenoria/vitess,tinyspeck/vitess,atyenoria/vitess,fengshao0907/vitess,pivanof/vitess,atyenoria/vitess,fengshao0907/vitess,mlc0202/vitess,erzel/vitess,tinyspeck/vitess,vitessio/vitess,nurblieh/vitess,aaijazi/vitess,tjyang/vitess,ptomasroos/vitess,dcadevil/vitess,erzel/vitess,alainjobart/vitess,yangzhongj/vitess,applift/vitess,mapbased/vitess,aaijazi/vitess,sougou/vitess,skyportsystems/vitess,yaoshengzhe/vitess,cgvarela/vitess,michael-berlin/vitess,alainjobart/vitess,mahak/vitess,cloudbearings/vitess,erzel/vitess,aaijazi/vitess,sougou/vitess,kmiku7/vitess-annotated,enisoc/vitess,rnavarro/vitess,dcadevil/vitess,skyportsystems/vitess,enisoc/vitess,nurblieh/vitess,cloudbearings/vitess,sougou/vitess,cgvarela/vitess,sougou/vitess,michael-berlin/vitess,mlc0202/vitess,dumbunny/vitess,davygeek/vitess,tinyspeck/vitess,cloudbearings/vitess,mlc0202/vitess,kuipertan/vitess,sougou/vitess,pivanof/vitess,davygeek/vitess,erzel/vitess,dumbunny/vitess,yangzhongj/vitess,skyportsystems/vitess,kuipertan/vitess,AndyDiamondstein/vitess,xgwubin/vitess,kmiku7/vitess-annotated,guokeno0/vitess,skyportsystems/vitess,tjyang/vitess,pivanof/vitess,yangzhongj/vitess,kuipertan/vitess,yangzhongj/vitess,davygeek/vitess,cloudbearings/vitess,mapbased/vitess,davygeek/vitess,skyportsystems/vitess,dumbunny/vitess,mahak/vitess,nurblieh/vitess,alainjobart/vitess,dcadevil/vitess,alainjobart/vitess,cloudbearings/vitess,vitessio/vitess,fengshao0907/vitess,kmiku7/vitess-annotated,applift/vitess,aaijazi/vitess,dumbunny/vitess,davygeek/vitess,guokeno0/vitess,xgwubin/vitess,dumbunny/vitess,davygeek/vitess,fengshao0907/vitess,rnavarro/vitess,tinyspeck/vitess,HubSpot/vitess,guokeno0/vitess,anusornc/vitess,mattharden/vitess,yaoshengzhe/vitess,nurblieh/vitess,skyportsystems/vitess,applift/vitess,atyenoria/vitess,dcadevil/vitess,anusornc/vitess,enisoc/vitess,sougou/vitess,michael-berlin/vitess,mapbased/vitess,AndyDiamondstein/vitess,mattharden/vitess,kuipertan/vitess,rnavarro/vitess,mlc0202/vitess
app.controller('ShardCtrl', function($scope, $routeParams, $timeout, $route, shards, tablets, tabletinfo, actions) { var keyspace = $routeParams.keyspace; var shard = $routeParams.shard; $scope.keyspace = {name: keyspace}; $scope.shard = {name: shard}; $scope.actions = actions; $scope.shardActions = [ {name: 'ValidateShard', title: 'Validate Shard'}, {name: 'ValidateSchemaShard', title: 'Validate Schema'}, {name: 'ValidateVersionShard', title: 'Validate Version'}, {name: 'ValidatePermissionsShard', title: 'Validate Permissions'}, ]; $scope.tabletActions = [ {name: 'Ping', title: 'Ping'}, {name: 'RefreshState', title: 'Refresh State', confirm: 'This will tell the tablet to re-read its topology record and adjust its state accordingly.'}, {name: 'ReloadSchema', title: 'Reload Schema', confirm: 'This will tell the tablet to refresh its schema cache by querying mysqld.'}, {name: 'ScrapTablet', title: 'Scrap', confirm: 'This will tell the tablet to remove itself from serving.'}, {name: 'ScrapTabletForce', title: 'Scrap (force)', confirm: 'This will externally remove the tablet from serving, without telling the tablet.'}, {name: 'DeleteTablet', title: 'Delete', confirm: 'This will delete the tablet record from topology.'}, ]; $scope.tabletType = function(tablet) { // Use streaming health result if present. if (tablet.streamHealth && tablet.streamHealth.$resolved) { if (!tablet.streamHealth.target) return 'spare'; if (tablet.streamHealth.target.tablet_type) return vtTabletTypes[tablet.streamHealth.target.tablet_type]; } return vtTabletTypes[tablet.type]; }; $scope.tabletHealthError = function(tablet) { if (tablet.streamHealth && tablet.streamHealth.realtime_stats && tablet.streamHealth.realtime_stats.health_error) { return tablet.streamHealth.realtime_stats.health_error; } return ''; }; $scope.tabletAccent = function(tablet) { if ($scope.tabletHealthError(tablet)) return 'md-warn md-hue-2'; switch ($scope.tabletType(tablet)) { case 'master': return 'md-hue-2'; case 'replica': return 'md-hue-3'; default: return 'md-hue-1'; } }; $scope.refreshData = function() { // Get the shard data. shards.get({keyspace: keyspace, shard: shard}, function(shardData) { shardData.name = shard; $scope.shard = shardData; }); // Get a list of tablet aliases in the shard, in all cells. tablets.query({shard: keyspace+'/'+shard}, function(tabletAliases) { // Group them by cell. var cellMap = {}; tabletAliases.forEach(function(tabletAlias) { if (cellMap[tabletAlias.cell] === undefined) cellMap[tabletAlias.cell] = []; cellMap[tabletAlias.cell].push(tabletAlias); }); // Turn the cell map into a list, sorted by cell name. var cellList = []; Object.keys(cellMap).sort().forEach(function(cellName) { // Sort the tablets within each cell. var tabletAliases = cellMap[cellName]; tabletAliases.sort(function(a, b) { return a.uid - b.uid; }); // Fetch tablet data. var tabletData = []; tabletAliases.forEach(function(tabletAlias) { var alias = tabletAlias.cell+'-'+tabletAlias.uid; var tablet = tablets.get({tablet: alias}, function(tablet) { // Annotate result with some extra stuff. tablet.links = vtconfig.tabletLinks(tablet); }); tablet.alias = tabletAlias; tabletData.push(tablet); }); // Add tablet data to the cell list. cellList.push({ name: cellName, tablets: tabletData }); }); $scope.cells = cellList; }); }; var selectedCell; $scope.setSelectedCell = function(cell) { selectedCell = cell; refreshStreamHealth(); }; function refreshStreamHealth() { if (selectedCell) { selectedCell.tablets.forEach(function (tablet) { if (tablet.alias) { // Get latest streaming health result. tabletinfo.get({tablet: tablet.alias.cell+'-'+tablet.alias.uid, info: 'health'}, function(health) { tablet.streamHealth = health; }); } }); } }; $scope.refreshData(); function periodicRefresh() { if ($route.current.name != 'shard') return; refreshStreamHealth(); $timeout(periodicRefresh, 3000); } periodicRefresh(); });
web/vtctld/shard.js
app.controller('ShardCtrl', function($scope, $routeParams, $timeout, $route, shards, tablets, tabletinfo, actions) { var keyspace = $routeParams.keyspace; var shard = $routeParams.shard; $scope.keyspace = {name: keyspace}; $scope.shard = {name: shard}; $scope.actions = actions; $scope.shardActions = [ {name: 'ValidateShard', title: 'Validate Shard'}, {name: 'ValidateSchemaShard', title: 'Validate Schema'}, {name: 'ValidateVersionShard', title: 'Validate Version'}, {name: 'ValidatePermissionsShard', title: 'Validate Permissions'}, ]; $scope.tabletActions = [ {name: 'Ping', title: 'Ping'}, {name: 'RefreshState', title: 'Refresh State', confirm: 'This will tell the tablet to re-read its topology record and adjust its state accordingly.'}, {name: 'ReloadSchema', title: 'Reload Schema', confirm: 'This will tell the tablet to refresh its schema cache by querying mysqld.'}, {name: 'ScrapTablet', title: 'Scrap', confirm: 'This will tell the tablet to remove itself from serving.'}, {name: 'ScrapTabletForce', title: 'Scrap (force)', confirm: 'This will externally remove the tablet from serving, without telling the tablet.'}, {name: 'DeleteTablet', title: 'Delete', confirm: 'This will delete the tablet record from topology.'}, ]; $scope.tabletType = function(tablet) { // Use streaming health result if present. if (tablet.streamHealth && tablet.streamHealth.$resolved) { if (!tablet.streamHealth.target) return 'spare'; if (tablet.streamHealth.target.tablet_type) return vtTabletTypes[tablet.streamHealth.target.tablet_type]; } return tablet.Type; }; $scope.tabletHealthError = function(tablet) { if (tablet.streamHealth && tablet.streamHealth.realtime_stats && tablet.streamHealth.realtime_stats.health_error) { return tablet.streamHealth.realtime_stats.health_error; } return ''; }; $scope.tabletAccent = function(tablet) { if ($scope.tabletHealthError(tablet)) return 'md-warn md-hue-2'; switch ($scope.tabletType(tablet)) { case 'master': return 'md-hue-2'; case 'replica': return 'md-hue-3'; default: return 'md-hue-1'; } }; $scope.refreshData = function() { // Get the shard data. shards.get({keyspace: keyspace, shard: shard}, function(shardData) { shardData.name = shard; $scope.shard = shardData; }); // Get a list of tablet aliases in the shard, in all cells. tablets.query({shard: keyspace+'/'+shard}, function(tabletAliases) { // Group them by cell. var cellMap = {}; tabletAliases.forEach(function(tabletAlias) { if (cellMap[tabletAlias.cell] === undefined) cellMap[tabletAlias.cell] = []; cellMap[tabletAlias.cell].push(tabletAlias); }); // Turn the cell map into a list, sorted by cell name. var cellList = []; Object.keys(cellMap).sort().forEach(function(cellName) { // Sort the tablets within each cell. var tabletAliases = cellMap[cellName]; tabletAliases.sort(function(a, b) { return a.uid - b.uid; }); // Fetch tablet data. var tabletData = []; tabletAliases.forEach(function(tabletAlias) { var alias = tabletAlias.cell+'-'+tabletAlias.uid; var tablet = tablets.get({tablet: alias}, function(tablet) { // Annotate result with some extra stuff. tablet.links = vtconfig.tabletLinks(tablet); }); tablet.Alias = tabletAlias; tabletData.push(tablet); }); // Add tablet data to the cell list. cellList.push({ name: cellName, tablets: tabletData }); }); $scope.cells = cellList; }); }; var selectedCell; $scope.setSelectedCell = function(cell) { selectedCell = cell; refreshStreamHealth(); }; function refreshStreamHealth() { if (selectedCell) { selectedCell.tablets.forEach(function (tablet) { if (tablet.Alias) { // Get latest streaming health result. tabletinfo.get({tablet: tablet.Alias.cell+'-'+tablet.Alias.uid, info: 'health'}, function(health) { tablet.streamHealth = health; }); } }); } }; $scope.refreshData(); function periodicRefresh() { if ($route.current.name != 'shard') return; refreshStreamHealth(); $timeout(periodicRefresh, 3000); } periodicRefresh(); });
web/vtctld: Fix shard dashboard for new topo structures.
web/vtctld/shard.js
web/vtctld: Fix shard dashboard for new topo structures.
<ide><path>eb/vtctld/shard.js <ide> if (tablet.streamHealth.target.tablet_type) <ide> return vtTabletTypes[tablet.streamHealth.target.tablet_type]; <ide> } <del> return tablet.Type; <add> return vtTabletTypes[tablet.type]; <ide> }; <ide> <ide> $scope.tabletHealthError = function(tablet) { <ide> // Annotate result with some extra stuff. <ide> tablet.links = vtconfig.tabletLinks(tablet); <ide> }); <del> tablet.Alias = tabletAlias; <add> tablet.alias = tabletAlias; <ide> <ide> tabletData.push(tablet); <ide> }); <ide> function refreshStreamHealth() { <ide> if (selectedCell) { <ide> selectedCell.tablets.forEach(function (tablet) { <del> if (tablet.Alias) { <add> if (tablet.alias) { <ide> // Get latest streaming health result. <del> tabletinfo.get({tablet: tablet.Alias.cell+'-'+tablet.Alias.uid, info: 'health'}, function(health) { <add> tabletinfo.get({tablet: tablet.alias.cell+'-'+tablet.alias.uid, info: 'health'}, function(health) { <ide> tablet.streamHealth = health; <ide> }); <ide> }
Java
mit
46d0b047d40bba8eba08bd9afdc3706ceac73d2b
0
MarquisLP/World-Scribe,MarquisLP/WorldScribe
package com.averi.worldscribe; import java.io.Serializable; import java.util.HashSet; /** * <p> * Created by mark on 31/07/16. * </p> * * <p> * Contains a list of all of the Articles that are linked to a certain Article through one * of the three types of links (Connection, Membership, or Residence). * </p> */ public class LinkedArticleList implements Serializable { private HashSet<String> personNames = new HashSet<>(); private HashSet<String> groupNames = new HashSet<>(); private HashSet<String> placeNames = new HashSet<>(); private HashSet<String> itemNames = new HashSet<>(); private HashSet<String> conceptNames = new HashSet<>(); /** * Adds an Article to this list. * @param category The {@link Category} of the Article. * @param name The name of the Article. */ public void addArticle(Category category, String name) { switch (category) { case Person: personNames.add(name); break; case Group: groupNames.add(name); break; case Place: placeNames.add(name); break; case Item: itemNames.add(name); break; case Concept: default: conceptNames.add(name); break; } } /** * Gets all Article links within a certain Category. * @param category The {@link Category} of Articles to return. * @return A HashSet containing all Article links of the specified Category. */ public HashSet<String> getAllLinksInCategory(Category category) { switch (category) { case Person: return personNames; case Group: return groupNames; case Place: return placeNames; case Item: return itemNames; case Concept: default: return conceptNames; } } }
app/src/main/java/com/averi/worldscribe/LinkedArticleList.java
package com.averi.worldscribe; import java.io.Serializable; import java.util.HashSet; /** * <p> * Created by mark on 31/07/16. * </p> * * <p> * Contains a list of all of the Articles that are linked to a certain Article through one * of the three types of links (Connection, Membership, or Residence). * </p> */ public class LinkedArticleList implements Serializable { private HashSet<String> personNames; private HashSet<String> groupNames; private HashSet<String> placeNames; private HashSet<String> itemNames; private HashSet<String> conceptNames; /** * Adds an Article to this list. * @param category The {@link Category} of the Article. * @param name The name of the Article. */ public void addArticle(Category category, String name) { switch (category) { case Person: personNames.add(name); break; case Group: groupNames.add(name); break; case Place: placeNames.add(name); break; case Item: itemNames.add(name); break; case Concept: default: conceptNames.add(name); break; } } /** * Gets all Article links within a certain Category. * @param category The {@link Category} of Articles to return. * @return A HashSet containing all Article links of the specified Category. */ public HashSet<String> getAllLinksInCategory(Category category) { switch (category) { case Person: return personNames; case Group: return groupNames; case Place: return placeNames; case Item: return itemNames; case Concept: default: return conceptNames; } } }
Initialize HashSets in LinkedArticleList
app/src/main/java/com/averi/worldscribe/LinkedArticleList.java
Initialize HashSets in LinkedArticleList
<ide><path>pp/src/main/java/com/averi/worldscribe/LinkedArticleList.java <ide> */ <ide> public class LinkedArticleList implements Serializable { <ide> <del> private HashSet<String> personNames; <del> private HashSet<String> groupNames; <del> private HashSet<String> placeNames; <del> private HashSet<String> itemNames; <del> private HashSet<String> conceptNames; <add> private HashSet<String> personNames = new HashSet<>(); <add> private HashSet<String> groupNames = new HashSet<>(); <add> private HashSet<String> placeNames = new HashSet<>(); <add> private HashSet<String> itemNames = new HashSet<>(); <add> private HashSet<String> conceptNames = new HashSet<>(); <ide> <ide> /** <ide> * Adds an Article to this list.
Java
apache-2.0
53269dca01c7c9e8b2fb58aad591ac17456c2906
0
chat-sdk/chat-sdk-android,chat-sdk/chat-sdk-android
package co.chatsdk.core.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your token includes here import com.google.android.gms.maps.model.LatLng; import org.greenrobot.greendao.DaoException; import org.greenrobot.greendao.annotation.Convert; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.ToMany; import org.greenrobot.greendao.annotation.ToOne; import org.greenrobot.greendao.annotation.Unique; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import co.chatsdk.core.interfaces.CoreEntity; import co.chatsdk.core.session.ChatSDK; import co.chatsdk.core.session.StorageManager; import co.chatsdk.core.types.MessageSendStatus; import co.chatsdk.core.types.MessageType; import co.chatsdk.core.types.ReadStatus; import co.chatsdk.core.utils.DaoDateTimeConverter; @Entity public class Message implements CoreEntity { @Id private Long id; @Unique private String entityID; @Convert(converter = DaoDateTimeConverter.class, columnType = Long.class) private DateTime date; private Boolean read; private Integer type; private Integer status; private Long senderId; private Long threadId; private Long nextMessageId; private Long lastMessageId; @ToMany(referencedJoinProperty = "messageId") private List<ReadReceiptUserLink> readReceiptLinks; @ToOne(joinProperty = "senderId") private User sender; @ToOne(joinProperty = "threadId") private Thread thread; @ToOne(joinProperty = "nextMessageId") private Message nextMessage; @ToOne(joinProperty = "lastMessageId") private Message lastMessage; @ToMany(referencedJoinProperty = "messageId") private List<MessageMetaValue> metaValues; /** Used to resolve relations */ @Generated(hash = 2040040024) private transient DaoSession daoSession; /** Used for active entity operations. */ @Generated(hash = 859287859) private transient MessageDao myDao; @Generated(hash = 842349170) public Message(Long id, String entityID, DateTime date, Boolean read, Integer type, Integer status, Long senderId, Long threadId, Long nextMessageId, Long lastMessageId) { this.id = id; this.entityID = entityID; this.date = date; this.read = read; this.type = type; this.status = status; this.senderId = senderId; this.threadId = threadId; this.nextMessageId = nextMessageId; this.lastMessageId = lastMessageId; } @Generated(hash = 637306882) public Message() { } @Generated(hash = 1974258785) private transient Long thread__resolvedKey; @Generated(hash = 880682693) private transient Long sender__resolvedKey; @Generated(hash = 992601680) private transient Long nextMessage__resolvedKey; @Generated(hash = 88977546) private transient Long lastMessage__resolvedKey; public boolean isRead() { ReadStatus status = readStatusForUser(ChatSDK.currentUser()); if (status != null && status.is(ReadStatus.read())) { return true; } else if (sender != null && sender.isMe()) { return true; } else if (read == null) { return false; } else { return read; } } @Override public String toString() { return String.format("Message, id: %s, type: %s, Sender: %s", id, type, getSender()); } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getEntityID() { return this.entityID; } public void setEntityID(String entityID) { this.entityID = entityID; } public DateTime getDate() { return this.date; } public void setDate(DateTime date) { this.date = date; } public HashMap<String, Object> getMetaValuesAsMap() { HashMap<String, Object> values = new HashMap<>(); for (MessageMetaValue v : getMetaValues()) { values.put(v.getKey(), v.getValue()); } return values; } public void setMetaValues(HashMap<String, Object> json) { for (String key : json.keySet()) { setMetaValue(key, json.get(key)); } } protected void setMetaValue(String key, Object value) { MessageMetaValue metaValue = (MessageMetaValue) metaValue(key); if (metaValue == null) { metaValue = StorageManager.shared().createEntity(MessageMetaValue.class); metaValue.setMessageId(this.getId()); getMetaValues().add(metaValue); } metaValue.setValue(MetaValueHelper.toString(value)); metaValue.setKey(key); metaValue.update(); update(); } protected MetaValue metaValue (String key) { ArrayList<MetaValue> values = new ArrayList<>(); values.addAll(getMetaValues()); return MetaValueHelper.metaValueForKey(key, values); } public Object valueForKey (String key) { MetaValue value = metaValue(key); if (value != null && value.getValue() != null) { return MetaValueHelper.toObject(value.getValue()); } else { return null; } } public String stringForKey (String key) { Object value = valueForKey(key); if (value == null) return ""; if (value instanceof String) { return (String) value; } return value.toString(); } public Double doubleForKey (String key) { Object value = valueForKey(key); if (value instanceof Double) { return (Double) value; } else { return (double) 0; } } public ReadReceiptUserLink linkForUser (User user) { for(ReadReceiptUserLink link : getReadReceiptLinks()) { User linkUser = link.getUser(); if (linkUser != null && user != null) { if(linkUser.equals(user)) { return link; } } } return null; } public void setUserReadStatus (User user, ReadStatus status, DateTime date) { ReadReceiptUserLink link = linkForUser(user); if(link == null) { link = StorageManager.shared().createEntity(ReadReceiptUserLink.class); link.setMessageId(this.getId()); getReadReceiptLinks().add(link); } link.setUser(user); link.setStatus(status.getValue()); link.setDate(date); link.update(); update(); } public LatLng getLocation () { Double latitude = doubleForKey(Keys.MessageLatitude); Double longitude = doubleForKey(Keys.MessageLongitude); return new LatLng(latitude, longitude); } public void setValueForKey (Object payload, String key) { setMetaValue(key, payload); } public String getText() { return stringForKey(Keys.MessageText); } public void setText(String text) { setValueForKey(text, Keys.MessageText); } public Integer getType () { return this.type; } public MessageType getMessageType() { if(this.type != null) { return new MessageType(this.type); } return new MessageType(MessageType.None); } public void setType(Integer type) { this.type = type; } public void setMessageType(MessageType type) { this.type = type.value(); } public Integer getStatus() { return this.status; } public MessageSendStatus getMessageStatus() { if(this.status != null) { return MessageSendStatus.values()[this.status]; } return MessageSendStatus.None; } public void setMessageStatus(MessageSendStatus status) { this.status = status.ordinal(); } public void setStatus(Integer status) { this.status = status; } public Long getThreadId() { return this.threadId; } public void setThreadId(Long threadId) { this.threadId = threadId; } public ReadStatus readStatusForUser (User user) { return readStatusForUser(user.getEntityID()); } public ReadStatus readStatusForUser (String userEntityID) { for(ReadReceiptUserLink link : getReadReceiptLinks()) { if(link.getUser() != null && link.getUser().getEntityID().equals(userEntityID)) { return new ReadStatus(link.getStatus()); } } return ReadStatus.notSet(); } public ReadStatus getReadStatus () { int total = 0; int userCount = getReadReceiptLinks().size(); for(ReadReceiptUserLink link : getReadReceiptLinks()) { total += link.getStatus(); } int status = ReadStatus.None; if(total >= ReadStatus.Delivered * userCount) { status = ReadStatus.Delivered; } if(total >= ReadStatus.Read * userCount) { status = ReadStatus.Read; } if (total == 0) { status = ReadStatus.None; } return new ReadStatus(status); } public Long getSenderId() { return this.senderId; } public void setSenderId(Long senderId) { this.senderId = senderId; } public Boolean getRead() { return this.read; } public void setRead(Boolean read) { this.read = read; } /** To-one relationship, resolved on first access. */ @Generated(hash = 1145839495) public User getSender() { Long __key = this.senderId; if (sender__resolvedKey == null || !sender__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } UserDao targetDao = daoSession.getUserDao(); User senderNew = targetDao.load(__key); synchronized (this) { sender = senderNew; sender__resolvedKey = __key; } } return sender; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 1434008871) public void setSender(User sender) { synchronized (this) { this.sender = sender; senderId = sender == null ? null : sender.getId(); sender__resolvedKey = senderId; } } /** To-one relationship, resolved on first access. */ @Generated(hash = 1483947909) public Thread getThread() { Long __key = this.threadId; if (thread__resolvedKey == null || !thread__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } ThreadDao targetDao = daoSession.getThreadDao(); Thread threadNew = targetDao.load(__key); synchronized (this) { thread = threadNew; thread__resolvedKey = __key; } } return thread; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 1938921797) public void setThread(Thread thread) { synchronized (this) { this.thread = thread; threadId = thread == null ? null : thread.getId(); thread__resolvedKey = threadId; } } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 128553479) public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 1942392019) public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 713229351) public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 747015224) public void __setDaoSession(DaoSession daoSession) { this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getMessageDao() : null; } /** * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ @Generated(hash = 2025183823) public List<ReadReceiptUserLink> getReadReceiptLinks() { if (readReceiptLinks == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } ReadReceiptUserLinkDao targetDao = daoSession.getReadReceiptUserLinkDao(); List<ReadReceiptUserLink> readReceiptLinksNew = targetDao ._queryMessage_ReadReceiptLinks(id); synchronized (this) { if (readReceiptLinks == null) { readReceiptLinks = readReceiptLinksNew; } } } return readReceiptLinks; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ @Generated(hash = 273652628) public synchronized void resetReadReceiptLinks() { readReceiptLinks = null; } public Long getNextMessageId() { return this.nextMessageId; } public void setNextMessageId(Long nextMessageId) { this.nextMessageId = nextMessageId; } public Long getLastMessageId() { return this.lastMessageId; } public void setLastMessageId(Long lastMessageId) { this.lastMessageId = lastMessageId; } /** To-one relationship, resolved on first access. */ @Generated(hash = 871948279) public Message getNextMessage() { Long __key = this.nextMessageId; if (nextMessage__resolvedKey == null || !nextMessage__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } MessageDao targetDao = daoSession.getMessageDao(); Message nextMessageNew = targetDao.load(__key); synchronized (this) { nextMessage = nextMessageNew; nextMessage__resolvedKey = __key; } } return nextMessage; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 1912932494) public void setNextMessage(Message nextMessage) { synchronized (this) { this.nextMessage = nextMessage; nextMessageId = nextMessage == null ? null : nextMessage.getId(); nextMessage__resolvedKey = nextMessageId; } } /** To-one relationship, resolved on first access. */ @Generated(hash = 1697405005) public Message getLastMessage() { Long __key = this.lastMessageId; if (lastMessage__resolvedKey == null || !lastMessage__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } MessageDao targetDao = daoSession.getMessageDao(); Message lastMessageNew = targetDao.load(__key); synchronized (this) { lastMessage = lastMessageNew; lastMessage__resolvedKey = __key; } } return lastMessage; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 944284900) public void setLastMessage(Message lastMessage) { synchronized (this) { this.lastMessage = lastMessage; lastMessageId = lastMessage == null ? null : lastMessage.getId(); lastMessage__resolvedKey = lastMessageId; } } /** * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ @Generated(hash = 2015206446) public List<MessageMetaValue> getMetaValues() { if (metaValues == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } MessageMetaValueDao targetDao = daoSession.getMessageMetaValueDao(); List<MessageMetaValue> metaValuesNew = targetDao._queryMessage_MetaValues(id); synchronized (this) { if (metaValues == null) { metaValues = metaValuesNew; } } } return metaValues; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ @Generated(hash = 365870950) public synchronized void resetMetaValues() { metaValues = null; } }
chat-sdk-core/src/main/java/co/chatsdk/core/dao/Message.java
package co.chatsdk.core.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your token includes here import com.google.android.gms.maps.model.LatLng; import org.greenrobot.greendao.DaoException; import org.greenrobot.greendao.annotation.Convert; import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Generated; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.ToMany; import org.greenrobot.greendao.annotation.ToOne; import org.greenrobot.greendao.annotation.Unique; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import co.chatsdk.core.interfaces.CoreEntity; import co.chatsdk.core.session.ChatSDK; import co.chatsdk.core.session.StorageManager; import co.chatsdk.core.types.MessageSendStatus; import co.chatsdk.core.types.MessageType; import co.chatsdk.core.types.ReadStatus; import co.chatsdk.core.utils.DaoDateTimeConverter; @Entity public class Message implements CoreEntity { @Id private Long id; @Unique private String entityID; @Convert(converter = DaoDateTimeConverter.class, columnType = Long.class) private DateTime date; private Boolean read; private Integer type; private Integer status; private Long senderId; private Long threadId; private Long nextMessageId; private Long lastMessageId; @ToMany(referencedJoinProperty = "messageId") private List<ReadReceiptUserLink> readReceiptLinks; @ToOne(joinProperty = "senderId") private User sender; @ToOne(joinProperty = "threadId") private Thread thread; @ToOne(joinProperty = "nextMessageId") private Message nextMessage; @ToOne(joinProperty = "lastMessageId") private Message lastMessage; @ToMany(referencedJoinProperty = "messageId") private List<MessageMetaValue> metaValues; /** Used to resolve relations */ @Generated(hash = 2040040024) private transient DaoSession daoSession; /** Used for active entity operations. */ @Generated(hash = 859287859) private transient MessageDao myDao; @Generated(hash = 842349170) public Message(Long id, String entityID, DateTime date, Boolean read, Integer type, Integer status, Long senderId, Long threadId, Long nextMessageId, Long lastMessageId) { this.id = id; this.entityID = entityID; this.date = date; this.read = read; this.type = type; this.status = status; this.senderId = senderId; this.threadId = threadId; this.nextMessageId = nextMessageId; this.lastMessageId = lastMessageId; } @Generated(hash = 637306882) public Message() { } @Generated(hash = 1974258785) private transient Long thread__resolvedKey; @Generated(hash = 880682693) private transient Long sender__resolvedKey; @Generated(hash = 992601680) private transient Long nextMessage__resolvedKey; @Generated(hash = 88977546) private transient Long lastMessage__resolvedKey; public boolean isRead() { ReadStatus status = readStatusForUser(ChatSDK.currentUser()); if (status != null && status.is(ReadStatus.read())) { return true; } else if (sender != null && sender.isMe()) { return true; } else if (read == null) { return false; } else { return read; } } @Override public String toString() { return String.format("Message, id: %s, type: %s, Sender: %s", id, type, getSender()); } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getEntityID() { return this.entityID; } public void setEntityID(String entityID) { this.entityID = entityID; } public DateTime getDate() { return this.date; } public void setDate(DateTime date) { this.date = date; } public HashMap<String, Object> getMetaValuesAsMap() { HashMap<String, Object> values = new HashMap<>(); for (MessageMetaValue v : getMetaValues()) { values.put(v.getKey(), v.getValue()); } return values; } public void setMetaValues(HashMap<String, Object> json) { for (String key : json.keySet()) { setMetaValue(key, json.get(key)); } } protected void setMetaValue(String key, Object value) { MessageMetaValue metaValue = (MessageMetaValue) metaValue(key); if (metaValue == null) { metaValue = StorageManager.shared().createEntity(MessageMetaValue.class); metaValue.setMessageId(this.getId()); getMetaValues().add(metaValue); } metaValue.setValue(MetaValueHelper.toString(value)); metaValue.setKey(key); metaValue.update(); update(); } protected MetaValue metaValue (String key) { ArrayList<MetaValue> values = new ArrayList<>(); values.addAll(getMetaValues()); return MetaValueHelper.metaValueForKey(key, values); } public Object valueForKey (String key) { MetaValue value = metaValue(key); if (value != null && value.getValue() != null) { return MetaValueHelper.toObject(value.getValue()); } else { return null; } } public String stringForKey (String key) { Object value = valueForKey(key); if (value instanceof String) { return (String) value; } else { return value.toString(); } } public Double doubleForKey (String key) { Object value = valueForKey(key); if (value instanceof Double) { return (Double) value; } else { return (double) 0; } } public ReadReceiptUserLink linkForUser (User user) { for(ReadReceiptUserLink link : getReadReceiptLinks()) { User linkUser = link.getUser(); if (linkUser != null && user != null) { if(linkUser.equals(user)) { return link; } } } return null; } public void setUserReadStatus (User user, ReadStatus status, DateTime date) { ReadReceiptUserLink link = linkForUser(user); if(link == null) { link = StorageManager.shared().createEntity(ReadReceiptUserLink.class); link.setMessageId(this.getId()); getReadReceiptLinks().add(link); } link.setUser(user); link.setStatus(status.getValue()); link.setDate(date); link.update(); update(); } public LatLng getLocation () { Double latitude = doubleForKey(Keys.MessageLatitude); Double longitude = doubleForKey(Keys.MessageLongitude); return new LatLng(latitude, longitude); } public void setValueForKey (Object payload, String key) { setMetaValue(key, payload); } public String getText() { return stringForKey(Keys.MessageText); } public void setText(String text) { setValueForKey(text, Keys.MessageText); } public Integer getType () { return this.type; } public MessageType getMessageType() { if(this.type != null) { return new MessageType(this.type); } return new MessageType(MessageType.None); } public void setType(Integer type) { this.type = type; } public void setMessageType(MessageType type) { this.type = type.value(); } public Integer getStatus() { return this.status; } public MessageSendStatus getMessageStatus() { if(this.status != null) { return MessageSendStatus.values()[this.status]; } return MessageSendStatus.None; } public void setMessageStatus(MessageSendStatus status) { this.status = status.ordinal(); } public void setStatus(Integer status) { this.status = status; } public Long getThreadId() { return this.threadId; } public void setThreadId(Long threadId) { this.threadId = threadId; } public ReadStatus readStatusForUser (User user) { return readStatusForUser(user.getEntityID()); } public ReadStatus readStatusForUser (String userEntityID) { for(ReadReceiptUserLink link : getReadReceiptLinks()) { if(link.getUser() != null && link.getUser().getEntityID().equals(userEntityID)) { return new ReadStatus(link.getStatus()); } } return ReadStatus.notSet(); } public ReadStatus getReadStatus () { int total = 0; int userCount = getReadReceiptLinks().size(); for(ReadReceiptUserLink link : getReadReceiptLinks()) { total += link.getStatus(); } int status = ReadStatus.None; if(total >= ReadStatus.Delivered * userCount) { status = ReadStatus.Delivered; } if(total >= ReadStatus.Read * userCount) { status = ReadStatus.Read; } if (total == 0) { status = ReadStatus.None; } return new ReadStatus(status); } public Long getSenderId() { return this.senderId; } public void setSenderId(Long senderId) { this.senderId = senderId; } public Boolean getRead() { return this.read; } public void setRead(Boolean read) { this.read = read; } /** To-one relationship, resolved on first access. */ @Generated(hash = 1145839495) public User getSender() { Long __key = this.senderId; if (sender__resolvedKey == null || !sender__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } UserDao targetDao = daoSession.getUserDao(); User senderNew = targetDao.load(__key); synchronized (this) { sender = senderNew; sender__resolvedKey = __key; } } return sender; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 1434008871) public void setSender(User sender) { synchronized (this) { this.sender = sender; senderId = sender == null ? null : sender.getId(); sender__resolvedKey = senderId; } } /** To-one relationship, resolved on first access. */ @Generated(hash = 1483947909) public Thread getThread() { Long __key = this.threadId; if (thread__resolvedKey == null || !thread__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } ThreadDao targetDao = daoSession.getThreadDao(); Thread threadNew = targetDao.load(__key); synchronized (this) { thread = threadNew; thread__resolvedKey = __key; } } return thread; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 1938921797) public void setThread(Thread thread) { synchronized (this) { this.thread = thread; threadId = thread == null ? null : thread.getId(); thread__resolvedKey = threadId; } } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 128553479) public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 1942392019) public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } /** * Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}. * Entity must attached to an entity context. */ @Generated(hash = 713229351) public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 747015224) public void __setDaoSession(DaoSession daoSession) { this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getMessageDao() : null; } /** * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ @Generated(hash = 2025183823) public List<ReadReceiptUserLink> getReadReceiptLinks() { if (readReceiptLinks == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } ReadReceiptUserLinkDao targetDao = daoSession.getReadReceiptUserLinkDao(); List<ReadReceiptUserLink> readReceiptLinksNew = targetDao ._queryMessage_ReadReceiptLinks(id); synchronized (this) { if (readReceiptLinks == null) { readReceiptLinks = readReceiptLinksNew; } } } return readReceiptLinks; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ @Generated(hash = 273652628) public synchronized void resetReadReceiptLinks() { readReceiptLinks = null; } public Long getNextMessageId() { return this.nextMessageId; } public void setNextMessageId(Long nextMessageId) { this.nextMessageId = nextMessageId; } public Long getLastMessageId() { return this.lastMessageId; } public void setLastMessageId(Long lastMessageId) { this.lastMessageId = lastMessageId; } /** To-one relationship, resolved on first access. */ @Generated(hash = 871948279) public Message getNextMessage() { Long __key = this.nextMessageId; if (nextMessage__resolvedKey == null || !nextMessage__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } MessageDao targetDao = daoSession.getMessageDao(); Message nextMessageNew = targetDao.load(__key); synchronized (this) { nextMessage = nextMessageNew; nextMessage__resolvedKey = __key; } } return nextMessage; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 1912932494) public void setNextMessage(Message nextMessage) { synchronized (this) { this.nextMessage = nextMessage; nextMessageId = nextMessage == null ? null : nextMessage.getId(); nextMessage__resolvedKey = nextMessageId; } } /** To-one relationship, resolved on first access. */ @Generated(hash = 1697405005) public Message getLastMessage() { Long __key = this.lastMessageId; if (lastMessage__resolvedKey == null || !lastMessage__resolvedKey.equals(__key)) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } MessageDao targetDao = daoSession.getMessageDao(); Message lastMessageNew = targetDao.load(__key); synchronized (this) { lastMessage = lastMessageNew; lastMessage__resolvedKey = __key; } } return lastMessage; } /** called by internal mechanisms, do not call yourself. */ @Generated(hash = 944284900) public void setLastMessage(Message lastMessage) { synchronized (this) { this.lastMessage = lastMessage; lastMessageId = lastMessage == null ? null : lastMessage.getId(); lastMessage__resolvedKey = lastMessageId; } } /** * To-many relationship, resolved on first access (and after reset). * Changes to to-many relations are not persisted, make changes to the target entity. */ @Generated(hash = 2015206446) public List<MessageMetaValue> getMetaValues() { if (metaValues == null) { final DaoSession daoSession = this.daoSession; if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } MessageMetaValueDao targetDao = daoSession.getMessageMetaValueDao(); List<MessageMetaValue> metaValuesNew = targetDao._queryMessage_MetaValues(id); synchronized (this) { if (metaValues == null) { metaValues = metaValuesNew; } } } return metaValues; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ @Generated(hash = 365870950) public synchronized void resetMetaValues() { metaValues = null; } }
Add null check
chat-sdk-core/src/main/java/co/chatsdk/core/dao/Message.java
Add null check
<ide><path>hat-sdk-core/src/main/java/co/chatsdk/core/dao/Message.java <ide> <ide> public String stringForKey (String key) { <ide> Object value = valueForKey(key); <add> if (value == null) return ""; <ide> if (value instanceof String) { <ide> return (String) value; <ide> } <del> else { <del> return value.toString(); <del> } <add> return value.toString(); <ide> } <ide> <ide> public Double doubleForKey (String key) {
Java
apache-2.0
0e18a4de0668f1d9ca30b9c45c7b852769cf0fc7
0
luj1985/dionysus,luj1985/dionysus,luj1985/dionysus
package com.huixinpn.dionysus.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.huixinpn.dionysus.domain.User; import com.huixinpn.dionysus.service.UserService; @Controller public class LoginController { private UserService userService; @Autowired public LoginController(UserService service) { this.userService = service; } @RequestMapping(value = "/login", method = RequestMethod.POST) public void login(@RequestBody User user) { userService.sign(user.getUsername(), user.getPassword()); } @RequestMapping(value = "/login/failure", method = RequestMethod.GET) public String loginFailure() { String message = "Login Failure!"; return "redirect:/login?message="+message; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout() { String message = "Logout Success!"; return "redirect:/login?message="+message; } @RequestMapping(value = "/validate/users", method = RequestMethod.POST) public boolean validate(@RequestBody User user) { return userService.userValidation( user.getUsername(), user.getPassword()); } @RequestMapping(value = "/register", method = RequestMethod.POST) public User register(@RequestBody User user) { return userService.register(user); } }
dionysus-webapp/src/main/java/com/huixinpn/dionysus/controller/LoginController.java
package com.huixinpn.dionysus.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.huixinpn.dionysus.domain.User; import com.huixinpn.dionysus.service.UserService; @Controller public class LoginController { private UserService userService; @Autowired public LoginController(UserService service) { this.userService = service; } @RequestMapping(value = "/login", method = RequestMethod.POST) public void login(@RequestBody User user) { userService.sign(user.getUsername(), user.getPassword()); } @RequestMapping(value = "/login/failure", method = RequestMethod.GET) public String loginFailure() { String message = "Login Failure!"; return "redirect:/login?message="+message; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout() { String message = "Logout Success!"; return "redirect:/login?message="+message; } @RequestMapping(value = "/validate/users", method = RequestMethod.POST) public boolean validate(@RequestBody User user) { return userService.userValidation( user.getUsername(), user.getPassword()); } }
Update login controller for register
dionysus-webapp/src/main/java/com/huixinpn/dionysus/controller/LoginController.java
Update login controller for register
<ide><path>ionysus-webapp/src/main/java/com/huixinpn/dionysus/controller/LoginController.java <ide> user.getUsername(), <ide> user.getPassword()); <ide> } <add> <add> @RequestMapping(value = "/register", method = RequestMethod.POST) <add> public User register(@RequestBody User user) { <add> return userService.register(user); <add> } <ide> }
Java
apache-2.0
96b9cf6ca9f459668fa9d027fe82f263cfcc034e
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jdo; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import javax.jdo.JDOException; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.jdbc.datasource.ConnectionHandle; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.jdbc.support.SQLExceptionTranslator; import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** * Default implementation of the {@link JdoDialect} interface. * Updated to build on JDO 2.0 or higher, as of Spring 2.5. * Used as default dialect by {@link JdoAccessor} and {@link JdoTransactionManager}. * * <p>Simply begins a standard JDO transaction in <code>beginTransaction</code>. * Returns a handle for a JDO2 DataStoreConnection on <code>getJdbcConnection</code>. * Calls the corresponding JDO2 PersistenceManager operation on <code>flush</code> * Ignores a given query timeout in <code>applyQueryTimeout</code>. * Uses a Spring SQLExceptionTranslator for exception translation, if applicable. * * <p>Note that, even with JDO2, vendor-specific subclasses are still necessary * for special transaction semantics and more sophisticated exception translation. * Furthermore, vendor-specific subclasses are encouraged to expose the native JDBC * Connection on <code>getJdbcConnection</code>, rather than JDO2's wrapper handle. * * <p>This class also implements the PersistenceExceptionTranslator interface, * as autodetected by Spring's PersistenceExceptionTranslationPostProcessor, * for AOP-based translation of native exceptions to Spring DataAccessExceptions. * Hence, the presence of a standard DefaultJdoDialect bean automatically enables * a PersistenceExceptionTranslationPostProcessor to translate JDO exceptions. * * @author Juergen Hoeller * @since 1.1 * @see #setJdbcExceptionTranslator * @see JdoAccessor#setJdoDialect * @see JdoTransactionManager#setJdoDialect * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor */ public class DefaultJdoDialect implements JdoDialect, PersistenceExceptionTranslator { // JDO 3.0 setTimeoutMillis method available? private static final Method setTimeoutMillisMethod = ClassUtils.getMethodIfAvailable(Query.class, "setTimeoutMillis", Integer.class); protected final Log logger = LogFactory.getLog(getClass()); private SQLExceptionTranslator jdbcExceptionTranslator; /** * Create a new DefaultJdoDialect. */ public DefaultJdoDialect() { } /** * Create a new DefaultJdoDialect. * @param connectionFactory the connection factory of the JDO PersistenceManagerFactory, * which is used to initialize the default JDBC exception translator * @see javax.jdo.PersistenceManagerFactory#getConnectionFactory() * @see PersistenceManagerFactoryUtils#newJdbcExceptionTranslator(Object) */ DefaultJdoDialect(Object connectionFactory) { this.jdbcExceptionTranslator = PersistenceManagerFactoryUtils.newJdbcExceptionTranslator(connectionFactory); } /** * Set the JDBC exception translator for this dialect. * <p>Applied to any SQLException root cause of a JDOException, if specified. * The default is to rely on the JDO provider's native exception translation. * @param jdbcExceptionTranslator exception translator * @see java.sql.SQLException * @see javax.jdo.JDOException#getCause() * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) { this.jdbcExceptionTranslator = jdbcExceptionTranslator; } /** * Return the JDBC exception translator for this dialect, if any. */ public SQLExceptionTranslator getJdbcExceptionTranslator() { return this.jdbcExceptionTranslator; } //------------------------------------------------------------------------- // Hooks for transaction management (used by JdoTransactionManager) //------------------------------------------------------------------------- /** * This implementation invokes the standard JDO <code>Transaction.begin</code> * method. Throws an InvalidIsolationLevelException if a non-default isolation * level is set. * @see javax.jdo.Transaction#begin * @see org.springframework.transaction.InvalidIsolationLevelException */ public Object beginTransaction(Transaction transaction, TransactionDefinition definition) throws JDOException, SQLException, TransactionException { if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { throw new InvalidIsolationLevelException( "Standard JDO does not support custom isolation levels: " + "use a special JdoDialect implementation for your JDO provider"); } transaction.begin(); return null; } /** * This implementation does nothing, as the default beginTransaction implementation * does not require any cleanup. * @see #beginTransaction */ public void cleanupTransaction(Object transactionData) { } /** * This implementation returns a DataStoreConnectionHandle for JDO2, * which will also work on JDO1 until actually accessing the JDBC Connection. * <p>For pre-JDO2 implementations, override this method to return the * Connection through the corresponding vendor-specific mechanism, or <code>null</code> * if the Connection is not retrievable. * <p><b>NOTE:</b> A JDO2 DataStoreConnection is always a wrapper, * never the native JDBC Connection. If you need access to the native JDBC * Connection (or the connection pool handle, to be unwrapped via a Spring * NativeJdbcExtractor), override this method to return the native * Connection through the corresponding vendor-specific mechanism. * <p>A JDO2 DataStoreConnection is only "borrowed" from the PersistenceManager: * it needs to be returned as early as possible. Effectively, JDO2 requires the * fetched Connection to be closed before continuing PersistenceManager work. * For this reason, the exposed ConnectionHandle eagerly releases its JDBC * Connection at the end of each JDBC data access operation (that is, on * <code>DataSourceUtils.releaseConnection</code>). * @see javax.jdo.PersistenceManager#getDataStoreConnection() * @see org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection */ public ConnectionHandle getJdbcConnection(PersistenceManager pm, boolean readOnly) throws JDOException, SQLException { return new DataStoreConnectionHandle(pm); } /** * This implementation does nothing, assuming that the Connection * will implicitly be closed with the PersistenceManager. * <p>If the JDO provider returns a Connection handle that it * expects the application to close, the dialect needs to invoke * <code>Connection.close</code> here. * @see java.sql.Connection#close() */ public void releaseJdbcConnection(ConnectionHandle conHandle, PersistenceManager pm) throws JDOException, SQLException { } /** * This implementation applies a JDO 3.0 query timeout, if available. Otherwise, * it sets the JPA 2.0 query hints "javax.persistence.lock.timeout" and * "javax.persistence.query.timeout", assuming that JDO providers are often * JPA providers as well. */ public void applyQueryTimeout(Query query, int remainingTimeInSeconds) throws JDOException { if (setTimeoutMillisMethod != null) { ReflectionUtils.invokeMethod(setTimeoutMillisMethod, query, remainingTimeInSeconds); } else { query.addExtension("javax.persistence.lock.timeout", remainingTimeInSeconds); query.addExtension("javax.persistence.query.timeout", remainingTimeInSeconds); } } //----------------------------------------------------------------------------------- // Hook for exception translation (used by JdoTransactionManager and JdoTemplate) //----------------------------------------------------------------------------------- /** * Implementation of the PersistenceExceptionTranslator interface, * as autodetected by Spring's PersistenceExceptionTranslationPostProcessor. * <p>Converts the exception if it is a JDOException, using this JdoDialect. * Else returns <code>null</code> to indicate an unknown exception. * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor * @see #translateException */ public DataAccessException translateExceptionIfPossible(RuntimeException ex) { if (ex instanceof JDOException) { return translateException((JDOException) ex); } return null; } /** * This implementation delegates to PersistenceManagerFactoryUtils. * @see PersistenceManagerFactoryUtils#convertJdoAccessException */ public DataAccessException translateException(JDOException ex) { if (getJdbcExceptionTranslator() != null && ex.getCause() instanceof SQLException) { return getJdbcExceptionTranslator().translate("JDO operation: " + ex.getMessage(), extractSqlStringFromException(ex), (SQLException) ex.getCause()); } return PersistenceManagerFactoryUtils.convertJdoAccessException(ex); } /** * Template method for extracting a SQL String from the given exception. * <p>Default implementation always returns <code>null</code>. Can be overridden in * subclasses to extract SQL Strings for vendor-specific exception classes. * @param ex the JDOException, containing a SQLException * @return the SQL String, or <code>null</code> if none found */ protected String extractSqlStringFromException(JDOException ex) { return null; } /** * ConnectionHandle implementation that fetches a new JDO2 DataStoreConnection * for every <code>getConnection</code> call and closes the Connection on * <code>releaseConnection</code>. This is necessary because JDO2 requires the * fetched Connection to be closed before continuing PersistenceManager work. * @see javax.jdo.PersistenceManager#getDataStoreConnection() */ private static class DataStoreConnectionHandle implements ConnectionHandle { private final PersistenceManager persistenceManager; public DataStoreConnectionHandle(PersistenceManager persistenceManager) { this.persistenceManager = persistenceManager; } public Connection getConnection() { return (Connection) this.persistenceManager.getDataStoreConnection(); } public void releaseConnection(Connection con) { JdbcUtils.closeConnection(con); } } }
org.springframework.orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java
/* * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jdo; import java.sql.Connection; import java.sql.SQLException; import javax.jdo.JDOException; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.jdbc.datasource.ConnectionHandle; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.jdbc.support.SQLExceptionTranslator; import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; /** * Default implementation of the {@link JdoDialect} interface. * Updated to build on JDO 2.0 or higher, as of Spring 2.5. * Used as default dialect by {@link JdoAccessor} and {@link JdoTransactionManager}. * * <p>Simply begins a standard JDO transaction in <code>beginTransaction</code>. * Returns a handle for a JDO2 DataStoreConnection on <code>getJdbcConnection</code>. * Calls the corresponding JDO2 PersistenceManager operation on <code>flush</code> * Ignores a given query timeout in <code>applyQueryTimeout</code>. * Uses a Spring SQLExceptionTranslator for exception translation, if applicable. * * <p>Note that, even with JDO2, vendor-specific subclasses are still necessary * for special transaction semantics and more sophisticated exception translation. * Furthermore, vendor-specific subclasses are encouraged to expose the native JDBC * Connection on <code>getJdbcConnection</code>, rather than JDO2's wrapper handle. * * <p>This class also implements the PersistenceExceptionTranslator interface, * as autodetected by Spring's PersistenceExceptionTranslationPostProcessor, * for AOP-based translation of native exceptions to Spring DataAccessExceptions. * Hence, the presence of a standard DefaultJdoDialect bean automatically enables * a PersistenceExceptionTranslationPostProcessor to translate JDO exceptions. * * @author Juergen Hoeller * @since 1.1 * @see #setJdbcExceptionTranslator * @see JdoAccessor#setJdoDialect * @see JdoTransactionManager#setJdoDialect * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor */ public class DefaultJdoDialect implements JdoDialect, PersistenceExceptionTranslator { protected final Log logger = LogFactory.getLog(getClass()); private SQLExceptionTranslator jdbcExceptionTranslator; /** * Create a new DefaultJdoDialect. */ public DefaultJdoDialect() { } /** * Create a new DefaultJdoDialect. * @param connectionFactory the connection factory of the JDO PersistenceManagerFactory, * which is used to initialize the default JDBC exception translator * @see javax.jdo.PersistenceManagerFactory#getConnectionFactory() * @see PersistenceManagerFactoryUtils#newJdbcExceptionTranslator(Object) */ DefaultJdoDialect(Object connectionFactory) { this.jdbcExceptionTranslator = PersistenceManagerFactoryUtils.newJdbcExceptionTranslator(connectionFactory); } /** * Set the JDBC exception translator for this dialect. * <p>Applied to any SQLException root cause of a JDOException, if specified. * The default is to rely on the JDO provider's native exception translation. * @param jdbcExceptionTranslator exception translator * @see java.sql.SQLException * @see javax.jdo.JDOException#getCause() * @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator * @see org.springframework.jdbc.support.SQLStateSQLExceptionTranslator */ public void setJdbcExceptionTranslator(SQLExceptionTranslator jdbcExceptionTranslator) { this.jdbcExceptionTranslator = jdbcExceptionTranslator; } /** * Return the JDBC exception translator for this dialect, if any. */ public SQLExceptionTranslator getJdbcExceptionTranslator() { return this.jdbcExceptionTranslator; } //------------------------------------------------------------------------- // Hooks for transaction management (used by JdoTransactionManager) //------------------------------------------------------------------------- /** * This implementation invokes the standard JDO <code>Transaction.begin</code> * method. Throws an InvalidIsolationLevelException if a non-default isolation * level is set. * @see javax.jdo.Transaction#begin * @see org.springframework.transaction.InvalidIsolationLevelException */ public Object beginTransaction(Transaction transaction, TransactionDefinition definition) throws JDOException, SQLException, TransactionException { if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { throw new InvalidIsolationLevelException( "Standard JDO does not support custom isolation levels: " + "use a special JdoDialect implementation for your JDO provider"); } transaction.begin(); return null; } /** * This implementation does nothing, as the default beginTransaction implementation * does not require any cleanup. * @see #beginTransaction */ public void cleanupTransaction(Object transactionData) { } /** * This implementation returns a DataStoreConnectionHandle for JDO2, * which will also work on JDO1 until actually accessing the JDBC Connection. * <p>For pre-JDO2 implementations, override this method to return the * Connection through the corresponding vendor-specific mechanism, or <code>null</code> * if the Connection is not retrievable. * <p><b>NOTE:</b> A JDO2 DataStoreConnection is always a wrapper, * never the native JDBC Connection. If you need access to the native JDBC * Connection (or the connection pool handle, to be unwrapped via a Spring * NativeJdbcExtractor), override this method to return the native * Connection through the corresponding vendor-specific mechanism. * <p>A JDO2 DataStoreConnection is only "borrowed" from the PersistenceManager: * it needs to be returned as early as possible. Effectively, JDO2 requires the * fetched Connection to be closed before continuing PersistenceManager work. * For this reason, the exposed ConnectionHandle eagerly releases its JDBC * Connection at the end of each JDBC data access operation (that is, on * <code>DataSourceUtils.releaseConnection</code>). * @see javax.jdo.PersistenceManager#getDataStoreConnection() * @see org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection */ public ConnectionHandle getJdbcConnection(PersistenceManager pm, boolean readOnly) throws JDOException, SQLException { return new DataStoreConnectionHandle(pm); } /** * This implementation does nothing, assuming that the Connection * will implicitly be closed with the PersistenceManager. * <p>If the JDO provider returns a Connection handle that it * expects the application to close, the dialect needs to invoke * <code>Connection.close</code> here. * @see java.sql.Connection#close() */ public void releaseJdbcConnection(ConnectionHandle conHandle, PersistenceManager pm) throws JDOException, SQLException { } /** * This implementation sets the JPA 2.0 query hints "javax.persistence.lock.timeout" * and "javax.persistence.query.timeout", assuming that JDO 2.1 providers are often * JPA providers as well. */ public void applyQueryTimeout(Query query, int remainingTimeInSeconds) throws JDOException { query.addExtension("javax.persistence.lock.timeout", remainingTimeInSeconds); query.addExtension("javax.persistence.query.timeout", remainingTimeInSeconds); } //----------------------------------------------------------------------------------- // Hook for exception translation (used by JdoTransactionManager and JdoTemplate) //----------------------------------------------------------------------------------- /** * Implementation of the PersistenceExceptionTranslator interface, * as autodetected by Spring's PersistenceExceptionTranslationPostProcessor. * <p>Converts the exception if it is a JDOException, using this JdoDialect. * Else returns <code>null</code> to indicate an unknown exception. * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor * @see #translateException */ public DataAccessException translateExceptionIfPossible(RuntimeException ex) { if (ex instanceof JDOException) { return translateException((JDOException) ex); } return null; } /** * This implementation delegates to PersistenceManagerFactoryUtils. * @see PersistenceManagerFactoryUtils#convertJdoAccessException */ public DataAccessException translateException(JDOException ex) { if (getJdbcExceptionTranslator() != null && ex.getCause() instanceof SQLException) { return getJdbcExceptionTranslator().translate("JDO operation: " + ex.getMessage(), extractSqlStringFromException(ex), (SQLException) ex.getCause()); } return PersistenceManagerFactoryUtils.convertJdoAccessException(ex); } /** * Template method for extracting a SQL String from the given exception. * <p>Default implementation always returns <code>null</code>. Can be overridden in * subclasses to extract SQL Strings for vendor-specific exception classes. * @param ex the JDOException, containing a SQLException * @return the SQL String, or <code>null</code> if none found */ protected String extractSqlStringFromException(JDOException ex) { return null; } /** * ConnectionHandle implementation that fetches a new JDO2 DataStoreConnection * for every <code>getConnection</code> call and closes the Connection on * <code>releaseConnection</code>. This is necessary because JDO2 requires the * fetched Connection to be closed before continuing PersistenceManager work. * @see javax.jdo.PersistenceManager#getDataStoreConnection() */ private static class DataStoreConnectionHandle implements ConnectionHandle { private final PersistenceManager persistenceManager; public DataStoreConnectionHandle(PersistenceManager persistenceManager) { this.persistenceManager = persistenceManager; } public Connection getConnection() { return (Connection) this.persistenceManager.getDataStoreConnection(); } public void releaseConnection(Connection con) { JdbcUtils.closeConnection(con); } } }
DefaultJdoDialect supports JDO 3.0 query timeout facility (as supported by DataNucleus 2.1)
org.springframework.orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java
DefaultJdoDialect supports JDO 3.0 query timeout facility (as supported by DataNucleus 2.1)
<ide><path>rg.springframework.orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java <ide> /* <del> * Copyright 2002-2009 the original author or authors. <add> * Copyright 2002-2010 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.orm.jdo; <ide> <add>import java.lang.reflect.Method; <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import javax.jdo.JDOException; <ide> import org.springframework.transaction.InvalidIsolationLevelException; <ide> import org.springframework.transaction.TransactionDefinition; <ide> import org.springframework.transaction.TransactionException; <add>import org.springframework.util.ClassUtils; <add>import org.springframework.util.ReflectionUtils; <ide> <ide> /** <ide> * Default implementation of the {@link JdoDialect} interface. <ide> * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor <ide> */ <ide> public class DefaultJdoDialect implements JdoDialect, PersistenceExceptionTranslator { <add> <add> // JDO 3.0 setTimeoutMillis method available? <add> private static final Method setTimeoutMillisMethod = <add> ClassUtils.getMethodIfAvailable(Query.class, "setTimeoutMillis", Integer.class); <ide> <ide> protected final Log logger = LogFactory.getLog(getClass()); <ide> <ide> } <ide> <ide> /** <del> * This implementation sets the JPA 2.0 query hints "javax.persistence.lock.timeout" <del> * and "javax.persistence.query.timeout", assuming that JDO 2.1 providers are often <add> * This implementation applies a JDO 3.0 query timeout, if available. Otherwise, <add> * it sets the JPA 2.0 query hints "javax.persistence.lock.timeout" and <add> * "javax.persistence.query.timeout", assuming that JDO providers are often <ide> * JPA providers as well. <ide> */ <ide> public void applyQueryTimeout(Query query, int remainingTimeInSeconds) throws JDOException { <del> query.addExtension("javax.persistence.lock.timeout", remainingTimeInSeconds); <del> query.addExtension("javax.persistence.query.timeout", remainingTimeInSeconds); <add> if (setTimeoutMillisMethod != null) { <add> ReflectionUtils.invokeMethod(setTimeoutMillisMethod, query, remainingTimeInSeconds); <add> } <add> else { <add> query.addExtension("javax.persistence.lock.timeout", remainingTimeInSeconds); <add> query.addExtension("javax.persistence.query.timeout", remainingTimeInSeconds); <add> } <ide> } <ide> <ide>
Java
apache-2.0
0f200dfede41b6f7327a359c196fb1c76c1329a9
0
NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.script; import java.io.*; import java.util.*; import org.apache.commons.collections4.map.LazyMap; import org.apache.commons.lang3.StringUtils; import generic.jar.ResourceFile; import generic.util.Path; import ghidra.framework.Application; import ghidra.program.model.listing.Program; import ghidra.util.Msg; import ghidra.util.SystemUtilities; import ghidra.util.classfinder.ClassSearcher; import ghidra.util.task.TaskMonitor; /** * A utility class for managing script directories and ScriptInfo objects. */ public class GhidraScriptUtil { private static final String SCRIPTS_SUBDIR_NAME = "ghidra_scripts"; private static final String DEV_SCRIPTS_SUBDIR_NAME = "developer_scripts"; private static final String BIN_DIR_NAME = "bin"; private static List<GhidraScriptProvider> providers = null; /** * User's home scripts directory */ public static String USER_SCRIPTS_DIR = buildUserScriptsDirectory(); /** * The default compile output directory */ //@formatter:off public static String USER_SCRIPTS_BIN_DIR = StringUtils.joinWith(File.separator, Application.getUserSettingsDirectory(), "dev", SCRIPTS_SUBDIR_NAME, BIN_DIR_NAME); //@formatter:on private static void createUserScriptsDirs() { File scriptsDir = new File(USER_SCRIPTS_DIR); scriptsDir.mkdirs(); File binDir = new File(USER_SCRIPTS_BIN_DIR); binDir.mkdirs(); } private static List<Path> scriptDirectoryPaths = new ArrayList<>(); static Map<ResourceFile, ScriptInfo> scriptFileToInfoMap = new HashMap<>(); static Map<String, List<ResourceFile>> scriptNameToFilesMap = LazyMap.lazyMap(new HashMap<String, List<ResourceFile>>(), () -> new ArrayList<>()); static { createUserScriptsDirs(); scriptDirectoryPaths = getDefaultScriptDirectories(); } /** The last time a request was made to refresh */ private static long lastRefreshRequestTimestamp = System.currentTimeMillis(); /** * User's home scripts directory. Some tests may override the default using the * SystemUtilities.USER_SCRIPTS_DIR system property. * @return the path to the default user scripts directory */ private static String buildUserScriptsDirectory() { String root = System.getProperty("user.home"); String override = System.getProperty(GhidraScriptConstants.USER_SCRIPTS_DIR_PROPERTY); if (override != null) { Msg.debug(GhidraScriptUtil.class, "Using Ghidra script source directory: " + root); root = override; } String sourcePath = StringUtils.joinWith(File.separator, root, SCRIPTS_SUBDIR_NAME); return sourcePath; } /** * Stores the time of the refresh request so that clients may later ask when the last * refresh took place. */ public static void refreshRequested() { lastRefreshRequestTimestamp = System.currentTimeMillis(); } public static long getLastRefreshRequestTimestamp() { return lastRefreshRequestTimestamp; } /** * Returns a list of the default script directories. * @return a list of the default script directories */ public static List<Path> getDefaultScriptDirectories() { List<Path> pathsList = new ArrayList<>(); addScriptPaths(pathsList, SCRIPTS_SUBDIR_NAME); addScriptPaths(pathsList, DEV_SCRIPTS_SUBDIR_NAME); Collections.sort(pathsList); // this one should always be first pathsList.add(0, new Path(new ResourceFile(USER_SCRIPTS_DIR), true, false, false)); return pathsList; } private static void addScriptPaths(List<Path> pathsList, String directoryName) { Iterable<ResourceFile> files = Application.findModuleSubDirectories(directoryName); for (ResourceFile file : files) { pathsList.add(new Path(file, true, false, true)); } } /** * Determine if the specified file is contained within the Ghidra installation. * @param file script file or directory * @return true if file contained within Ghidra installation area */ public static boolean isSystemScriptPath(ResourceFile file) { return isSystemFile(file); } /** * Determine if the specified file is contained within the Ghidra installation. * @param file file or directory to check * @return true if file is contained within Ghidra application root. */ private static boolean isSystemFile(ResourceFile file) { try { String filePath = file.getCanonicalPath().replace('\\', '/'); if (filePath.startsWith(USER_SCRIPTS_DIR)) { // a script inside of the user scripts dir is not a 'system' script return false; } Collection<ResourceFile> roots = Application.getApplicationRootDirectories(); for (ResourceFile resourceFile : roots) { String installPath = resourceFile.getCanonicalPath().replace('\\', '/'); if (filePath.startsWith(installPath)) { return true; } } return false; } catch (IOException e) { Msg.error(null, "Unexpected Exception: " + e.getMessage(), e); return true; } } /** * Returns a list of the current script directories. * @return a list of the current script directories */ public static List<ResourceFile> getScriptSourceDirectories() { ArrayList<ResourceFile> dirs = new ArrayList<>(); for (Path path : scriptDirectoryPaths) { dirs.add(path.getPath()); } return dirs; } /** * Sets the script directories to the new paths. * @param newPaths the new script directories */ public static void setScriptDirectories(List<Path> newPaths) { scriptDirectoryPaths = new ArrayList<>(newPaths); } /** * Returns the PATH for the specified directory. * @param directory the directory * @return the path for the specified directory */ public static Path getScriptPath(ResourceFile directory) { if (directory.isDirectory()) { for (Path path : scriptDirectoryPaths) { if (path.getPath().equals(directory)) { return path; } } } return null; } /** * Returns the output directory to which the given script file's generated .class file should * be written * @param scriptFile the script file * @return the directory */ public static ResourceFile getScriptCompileOutputDirectory(ResourceFile scriptFile) { return new ResourceFile(USER_SCRIPTS_BIN_DIR); } static ResourceFile getClassFile(ResourceFile sourceFile, String rawName) { if (sourceFile != null) { // prefer resource files when they exist, as we know exactly which file we want to load return GhidraScriptUtil.getClassFileByResourceFile(sourceFile, rawName); } return getClassFileByName(rawName); } /** * Uses the given {@link ResourceFile} to find its class file. This method is needed * due to the fact that we sometimes can find a class file in more than one location, * such as when using an installation version of Ghidra in the same environment as * a development version of Ghidra. We get better debugging when we use the class file * that is associated with the given source file. * * @param sourceFile the source file for which to find the generated class file. * @param rawName the name of the class, without file extension or path info. * @return the class file generated from the given source file. */ static ResourceFile getClassFileByResourceFile(ResourceFile sourceFile, String rawName) { String javaAbsolutePath = sourceFile.getAbsolutePath(); String classAbsolutePath = javaAbsolutePath.replace(".java", ".class"); String path = rawName.replace('.', '/'); String className = path + ".class"; ResourceFile classFile = findClassFile(getDevelopmentScriptBinDirectories(), classAbsolutePath, className); if (classFile != null) { Msg.trace(GhidraScriptUtil.class, "Resource file " + sourceFile + " class found at " + classFile); return classFile; } ResourceFile defaultCompilerDirectory = getScriptCompileOutputDirectory(sourceFile); classFile = new ResourceFile(new File(defaultCompilerDirectory.getAbsolutePath(), className)); if (classFile.exists()) { // This should always exist when we compile the script ourselves Msg.trace(GhidraScriptUtil.class, "Resource file " + sourceFile + " class found at " + classFile); return classFile; } classFile = findClassFile(getScriptBinDirectories(), classAbsolutePath, className); if (classFile != null) { Msg.trace(GhidraScriptUtil.class, "Resource file " + sourceFile + " class found at " + classFile); return classFile; } // default to a non-existent file return new ResourceFile(GhidraScriptUtil.USER_SCRIPTS_BIN_DIR + "/" + className); } private static ResourceFile getClassFileByName(String rawName) { String path = rawName.replace('.', '/'); String className = path + ".class"; // // Note: in this case, we *only* want to search the script bin dirs, as we do not want // to find other class elements that may be in the development environment. For // example, we do not want to find non-script classes in the development bin dirs, // as those are loaded by our parent class loader. If we load them, then they will // not be the same class instances. // Set<ResourceFile> matchingClassFiles = new HashSet<>(); Collection<ResourceFile> userBinDirectories = GhidraScriptUtil.getScriptBinDirectories(); for (ResourceFile file : userBinDirectories) { ResourceFile testFile = new ResourceFile(file, className); if (testFile.exists()) { matchingClassFiles.add(testFile); } } return maybeWarnAboutNameConflict(className, matchingClassFiles); } private static ResourceFile findClassFile(Collection<ResourceFile> binDirs, String classAbsolutePath, String className) { Set<ResourceFile> matchingClassFiles = new HashSet<>(); for (ResourceFile binDir : binDirs) { ResourceFile binParentFile = binDir.getParentFile(); String absoluteParentPath = binParentFile.getAbsolutePath(); if (classAbsolutePath.startsWith(absoluteParentPath)) { ResourceFile potentialFile = new ResourceFile(binDir, className); if (potentialFile.exists()) { matchingClassFiles.add(potentialFile); } } } return maybeWarnAboutNameConflict(className, matchingClassFiles); } private static ResourceFile maybeWarnAboutNameConflict(String className, Set<ResourceFile> matchingClassFiles) { int matchCount = matchingClassFiles.size(); if (matchCount == 1) { return matchingClassFiles.iterator().next(); } else if (matchCount > 1) { // // Unusual Code: When running from Eclipse we need to use the class file that is // in the Eclipse project's bin. If not, then users cannot debug // the scripts, as Eclipse doesn't know how to find the source. This // can happen when users link source into the scripts project. // We don't know if we are running from Eclipse, which means that this // will give out the wrong file in the case where we are not, but there // happen to be two different class files with the same name. // ResourceFile preferredFile = null; for (ResourceFile file : matchingClassFiles) { if (file.getParentFile() .getAbsolutePath() .equals( GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) { preferredFile = file; break; } } if (preferredFile == null) { // just pick one preferredFile = matchingClassFiles.iterator().next(); } Msg.warn(GhidraScriptUtil.class, "Found " + matchCount + " class files named " + className + ". Using: " + preferredFile); return preferredFile; } return null; } /** * Returns the list of directories to which scripts are compiled. * @return the list * * @see #getScriptCompileOutputDirectory(ResourceFile) */ public static List<ResourceFile> getScriptBinDirectories() { return Arrays.asList(new ResourceFile(USER_SCRIPTS_BIN_DIR)); } /** * Returns a list of directories. Development directories differ from standard script * directories in that the former have a bin directory at a different location from * the latter, due to the setup of the development environment. * * @return Returns a list of directories */ static Collection<ResourceFile> getDevelopmentScriptBinDirectories() { if (!SystemUtilities.isInDevelopmentMode() || SystemUtilities.isInTestingMode()) { return Collections.emptyList(); } Set<ResourceFile> dirs = new HashSet<>(); for (Path path : scriptDirectoryPaths) { // // Assumed structure of script dir path: // /some/path/Ghidra/Features/Module/ghidra_scripts // // Desired path: // /some/path/Ghidra/Features/Module/bin/scripts ResourceFile scriptDir = path.getPath(); ResourceFile moduleDir = scriptDir.getParentFile(); dirs.add(new ResourceFile(moduleDir, BIN_DIR_NAME + File.separator + "scripts")); } return dirs; } /** * Deletes all script class files. */ public static void clean() { scriptFileToInfoMap.clear(); // clear our cache of old files scriptNameToFilesMap.clear(); File userdir = new File(USER_SCRIPTS_DIR); File[] classFiles = userdir.listFiles( (FileFilter) pathname -> pathname.getName().toLowerCase().endsWith(".class")); for (File classFile : classFiles) { classFile.delete(); } } /** * Returns the base name give a script file. * For example, given "C:\Temp\SomeClass.java", * it will return "SomeClass". * @param script the script * @return the base name */ public static String getBaseName(ResourceFile script) { String name = script.getName(); int pos = name.lastIndexOf('.'); if (pos == -1) { return name; } return name.substring(0, pos); } /** * Returns true if a ScriptInfo object exists for * the specified script file. * @param scriptFile the script file * @return true if a ScriptInfo object exists */ public static boolean contains(ResourceFile scriptFile) { return scriptFileToInfoMap.containsKey(scriptFile); } /** * Removes the ScriptInfo object for the specified file * @param scriptFile the script file */ public static void unloadScript(ResourceFile scriptFile) { scriptFileToInfoMap.remove(scriptFile); Iterator<ResourceFile> iter = scriptNameToFilesMap.get(scriptFile.getName()).iterator(); while (iter.hasNext()) { ResourceFile rFile = iter.next(); if (scriptFile.equals(rFile)) { iter.remove(); break; } } } /** * Returns an iterator over all script info objects. * @return an iterator over all script info objects */ public static Iterator<ScriptInfo> getScriptInfoIterator() { return scriptFileToInfoMap.values().iterator(); } /** * Returns the script info object for the specified script file * * @param scriptFile the script file * @return the script info object for the specified script file */ public static ScriptInfo getScriptInfo(ResourceFile scriptFile) { ScriptInfo info = scriptFileToInfoMap.get(scriptFile); if (info != null) { return info; } GhidraScriptProvider gsp = getProvider(scriptFile); info = new ScriptInfo(gsp, scriptFile); scriptFileToInfoMap.put(scriptFile, info); String name = scriptFile.getName(); List<ResourceFile> matchingFiles = scriptNameToFilesMap.get(name); matchingFiles.add(scriptFile); markAnyDuplicates(matchingFiles); return info; } private static void markAnyDuplicates(List<ResourceFile> files) { boolean isDuplicate = files.size() > 1; files.forEach(f -> scriptFileToInfoMap.get(f).setDuplicate(isDuplicate)); } /** * Returns a list of all Ghidra script providers * * @return a list of all Ghidra script providers */ // Note: this method is synchronized so that two threads do not try to create the list when null public synchronized static List<GhidraScriptProvider> getProviders() { if (providers == null) { List<GhidraScriptProvider> newProviders = new ArrayList<>(ClassSearcher.getInstances(GhidraScriptProvider.class)); Collections.sort(newProviders); providers = newProviders; } return providers; } /** * Returns the corresponding Ghidra script providers * for the specified script file. * @param scriptFile the script file * @return the Ghidra script provider */ public static GhidraScriptProvider getProvider(ResourceFile scriptFile) { String scriptFileName = scriptFile.getName().toLowerCase(); for (GhidraScriptProvider provider : getProviders()) { if (scriptFileName.endsWith(provider.getExtension().toLowerCase())) { return provider; } } return null; } /** * Returns true if a provider exists that can process the specified file. * * @param scriptFile the script file * @return true if a provider exists that can process the specified file */ public static boolean hasScriptProvider(ResourceFile scriptFile) { String scriptFileName = scriptFile.getName().toLowerCase(); for (GhidraScriptProvider provider : getProviders()) { if (scriptFileName.endsWith(provider.getExtension().toLowerCase())) { return true; } } return false; } /** * Creates a new script with a unique name using the specified provider in the * specified directory. * @param provider the Ghidra script provider * @param parentDirectory the directory where the new script will be created. * @param scriptDirectories The list of directories containing scripts (used to find a * unique name). * @return the newly created script file * @throws IOException if an i/o error occurs */ public static ResourceFile createNewScript(GhidraScriptProvider provider, ResourceFile parentDirectory, List<Path> scriptDirectories) throws IOException { String baseName = GhidraScriptConstants.DEFAULT_SCRIPT_NAME; String extension = provider.getExtension(); return createNewScript(baseName, extension, parentDirectory, scriptDirectories); } private static ResourceFile createNewScript(String scriptName, String extension, ResourceFile parentDirctory, List<Path> scriptDirectories) throws IOException { String baseName = scriptName; String className = baseName + extension; // we want to pick a name that is unique in *any* of the script directories int counter = 1; boolean exists = findScriptFileInPaths(scriptDirectories, className) != null; while (exists) { baseName = scriptName + counter++; className = baseName + extension; exists = findScriptFileInPaths(scriptDirectories, className) != null; if (counter > 1000) { throw new IOException( "Unable to create new script file, temporary files exceeded."); } } return new ResourceFile(parentDirctory, className); } /** Returns true if the given filename exists in any of the given directories */ private static ResourceFile findScriptFileInPaths(List<Path> scriptDirectories, String filename) { String validatedName = fixupName(filename); for (Path path : scriptDirectories) { ResourceFile file = new ResourceFile(path.getPath(), validatedName); if (file.exists()) { return file; } } return null; } /** * Fixup name issues, such as package parts in the name and inner class names. * <p> * This method can handle names with or without '.java' at the end; names with * '$' (inner classes) and names with '.' characters for package separators * * @param name the name of the script * @return the name as a '.java' file path (with '/'s and not '.'s) */ static String fixupName(String name) { if (name.endsWith(".java")) { name = name.substring(0, name.length() - 5); } String path = name.replace('.', '/'); int innerClassIndex = path.indexOf('$'); if (innerClassIndex != -1) { path = path.substring(0, innerClassIndex); } return path + ".java"; } /** * Uses the given name to find a matching script. This method only works because of the * limitation that all script names in Ghidra must be unique. If the given name has multiple * script matches, then a warning will be logged. * * @param name The name for which to find a script * @return The ScriptInfo that has the given name */ public static ScriptInfo findScriptByName(String name) { List<ResourceFile> matchingFiles = scriptNameToFilesMap.get(name); if (matchingFiles != null && !matchingFiles.isEmpty()) { ScriptInfo info = scriptFileToInfoMap.get(matchingFiles.get(0)); if (matchingFiles.size() > 1) { Msg.warn(GhidraScriptUtil.class, "Found duplicate scripts for name: " + name + ". Binding to script: " + info.getSourceFile()); } return info; } ResourceFile file = findScriptFileInPaths(scriptDirectoryPaths, name); if (file == null) { return null; } return getScriptInfo(file); // this will cache the created info } public static List<ResourceFile> getAllScripts() { List<ResourceFile> scriptList = new ArrayList<>(); for (Path dirPath : scriptDirectoryPaths) { updateAvailableScriptFilesForDirectory(scriptList, dirPath.getPath()); } return scriptList; } private static void updateAvailableScriptFilesForDirectory(List<ResourceFile> scriptAccumulator, ResourceFile directory) { ResourceFile[] files = directory.listFiles(); if (files == null) { return; } for (ResourceFile scriptFile : files) { if (scriptFile.isFile() && hasScriptProvider(scriptFile)) { scriptAccumulator.add(scriptFile); } } } /** * Looks through all of the current {@link ScriptInfo}s to see if one already exists with * the given name. * @param scriptName The name to check * @return true if the name is not taken by an existing {@link ScriptInfo}. */ public static boolean alreadyExists(String scriptName) { return getExistingScriptInfo(scriptName) != null; } /** * Returns the existing script info for the given name. The script environment limits * scripts such that names are unique. If this method returns a non-null value, then the * name given name is taken. * * @param scriptName the name of the script for which to get a ScriptInfo * @return a ScriptInfo matching the given name; null if no script by that name is known to * the script manager */ public static ScriptInfo getExistingScriptInfo(String scriptName) { List<ResourceFile> matchingFiles = scriptNameToFilesMap.get(scriptName); if (matchingFiles.isEmpty()) { return null; } return scriptFileToInfoMap.get(matchingFiles.get(0)); } /** * Runs the specified script with the specified state * * @param scriptState state representing environment variables that the script is able to access * @param script Script to be run * @param writer the writer to which warning and error messages will be written * @param originator the client class requesting the script run; used for logging * @param monitor the task monitor * @return whether the script successfully completed running */ public static boolean runScript(GhidraState scriptState, GhidraScript script, PrintWriter writer, Object originator, TaskMonitor monitor) { ResourceFile srcFile = script.getSourceFile(); String scriptName = srcFile != null ? srcFile.getAbsolutePath() : (script.getClass().getName() + ".class"); try { Msg.info(originator, "SCRIPT: " + scriptName); script.execute(scriptState, monitor, writer); writer.flush(); } catch (Exception exc) { Program prog = scriptState.getCurrentProgram(); String path = (prog != null ? prog.getExecutablePath() : "Current program is null."); String logErrorMsg = path + "\nREPORT SCRIPT ERROR: " + scriptName + " : " + exc.getMessage(); Msg.error(originator, logErrorMsg, exc); return false; } return true; } /** * Updates every known script's duplicate value. */ public static void refreshDuplicates() { scriptNameToFilesMap.values().forEach(files -> { boolean isDuplicate = files.size() > 1; files.forEach(file -> scriptFileToInfoMap.get(file).setDuplicate(isDuplicate)); }); } }
Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.script; import java.io.*; import java.util.*; import org.apache.commons.collections4.map.LazyMap; import org.apache.commons.lang3.StringUtils; import generic.jar.ResourceFile; import generic.util.Path; import ghidra.framework.Application; import ghidra.program.model.listing.Program; import ghidra.util.Msg; import ghidra.util.SystemUtilities; import ghidra.util.classfinder.ClassSearcher; import ghidra.util.task.TaskMonitor; /** * A utility class for managing script directories and ScriptInfo objects. */ public class GhidraScriptUtil { private static final String SCRIPTS_SUBDIR_NAME = "ghidra_scripts"; private static final String DEV_SCRIPTS_SUBDIR_NAME = "developer_scripts"; private static final String BIN_DIR_NAME = "bin"; private static List<GhidraScriptProvider> providers = null; /** * User's home scripts directory */ public static String USER_SCRIPTS_DIR = buildUserScriptsDirectory(); /** * The default compile output directory */ //@formatter:off public static String USER_SCRIPTS_BIN_DIR = StringUtils.joinWith(File.separator, Application.getUserSettingsDirectory(), "dev", SCRIPTS_SUBDIR_NAME, BIN_DIR_NAME); //@formatter:on private static void createUserScriptsDirs() { File scriptsDir = new File(USER_SCRIPTS_DIR); scriptsDir.mkdirs(); File binDir = new File(USER_SCRIPTS_BIN_DIR); binDir.mkdirs(); } private static List<Path> scriptDirectoryPaths = new ArrayList<>(); static Map<ResourceFile, ScriptInfo> scriptFileToInfoMap = new HashMap<>(); static Map<String, List<ResourceFile>> scriptNameToFilesMap = LazyMap.lazyMap(new HashMap<String, List<ResourceFile>>(), () -> new ArrayList<>()); static { createUserScriptsDirs(); scriptDirectoryPaths = getDefaultScriptDirectories(); } /** The last time a request was made to refresh */ private static long lastRefreshRequestTimestamp = System.currentTimeMillis(); /** * User's home scripts directory. Some tests may override the default using the * SystemUtilities.USER_SCRIPTS_DIR system property. * @return the path to the default user scripts directory */ private static String buildUserScriptsDirectory() { String root = System.getProperty("user.home"); String override = System.getProperty(GhidraScriptConstants.USER_SCRIPTS_DIR_PROPERTY); if (override != null) { Msg.debug(GhidraScriptUtil.class, "Using Ghidra script source directory: " + root); root = override; } String sourcePath = StringUtils.joinWith(File.separator, root, SCRIPTS_SUBDIR_NAME); return sourcePath; } /** * Stores the time of the refresh request so that clients may later ask when the last * refresh took place. */ public static void refreshRequested() { lastRefreshRequestTimestamp = System.currentTimeMillis(); } public static long getLastRefreshRequestTimestamp() { return lastRefreshRequestTimestamp; } /** * Returns a list of the default script directories. * @return a list of the default script directories */ public static List<Path> getDefaultScriptDirectories() { List<Path> pathsList = new ArrayList<>(); addScriptPaths(pathsList, SCRIPTS_SUBDIR_NAME); addScriptPaths(pathsList, DEV_SCRIPTS_SUBDIR_NAME); Collections.sort(pathsList); // this one should always be first pathsList.add(0, new Path(new ResourceFile(USER_SCRIPTS_DIR), true, false, false)); return pathsList; } private static void addScriptPaths(List<Path> pathsList, String directoryName) { Iterable<ResourceFile> files = Application.findModuleSubDirectories(directoryName); for (ResourceFile file : files) { pathsList.add(new Path(file, true, false, true)); } } /** * Determine if the specified file is contained within the Ghidra installation. * @param file script file or directory * @return true if file contained within Ghidra installation area */ public static boolean isSystemScriptPath(ResourceFile file) { return isSystemFile(file); } /** * Determine if the specified file is contained within the Ghidra installation. * @param file - file or directory to check * @return true if file is contained within Ghidra application root. */ public static boolean isSystemFile(ResourceFile file) { try { String filePath = file.getCanonicalPath().replace('\\', '/'); Collection<ResourceFile> roots = Application.getApplicationRootDirectories(); for (ResourceFile resourceFile : roots) { String installPath = resourceFile.getCanonicalPath().replace('\\', '/'); if (filePath.startsWith(installPath)) { return true; } } return false; } catch (IOException e) { Msg.error(null, "Unexpected Exception: " + e.getMessage(), e); return true; } } /** * Returns a list of the current script directories. * @return a list of the current script directories */ public static List<ResourceFile> getScriptSourceDirectories() { ArrayList<ResourceFile> dirs = new ArrayList<>(); for (Path path : scriptDirectoryPaths) { dirs.add(path.getPath()); } return dirs; } /** * Sets the script directories to the new paths. * @param newPaths the new script directories */ public static void setScriptDirectories(List<Path> newPaths) { scriptDirectoryPaths = new ArrayList<>(newPaths); } /** * Returns the PATH for the specified directory. * @param directory the directory * @return the path for the specified directory */ public static Path getScriptPath(ResourceFile directory) { if (directory.isDirectory()) { for (Path path : scriptDirectoryPaths) { if (path.getPath().equals(directory)) { return path; } } } return null; } /** * Returns the output directory to which the given script file's generated .class file should * be written * @param scriptFile the script file * @return the directory */ public static ResourceFile getScriptCompileOutputDirectory(ResourceFile scriptFile) { return new ResourceFile(USER_SCRIPTS_BIN_DIR); } static ResourceFile getClassFile(ResourceFile sourceFile, String rawName) { if (sourceFile != null) { // prefer resource files when they exist, as we know exactly which file we want to load return GhidraScriptUtil.getClassFileByResourceFile(sourceFile, rawName); } return getClassFileByName(rawName); } /** * Uses the given {@link ResourceFile} to find its class file. This method is needed * due to the fact that we sometimes can find a class file in more than one location, * such as when using an installation version of Ghidra in the same environment as * a development version of Ghidra. We get better debugging when we use the class file * that is associated with the given source file. * * @param sourceFile the source file for which to find the generated class file. * @param rawName the name of the class, without file extension or path info. * @return the class file generated from the given source file. */ static ResourceFile getClassFileByResourceFile(ResourceFile sourceFile, String rawName) { String javaAbsolutePath = sourceFile.getAbsolutePath(); String classAbsolutePath = javaAbsolutePath.replace(".java", ".class"); String path = rawName.replace('.', '/'); String className = path + ".class"; ResourceFile classFile = findClassFile(getDevelopmentScriptBinDirectories(), classAbsolutePath, className); if (classFile != null) { Msg.trace(GhidraScriptUtil.class, "Resource file " + sourceFile + " class found at " + classFile); return classFile; } ResourceFile defaultCompilerDirectory = getScriptCompileOutputDirectory(sourceFile); classFile = new ResourceFile(new File(defaultCompilerDirectory.getAbsolutePath(), className)); if (classFile.exists()) { // This should always exist when we compile the script ourselves Msg.trace(GhidraScriptUtil.class, "Resource file " + sourceFile + " class found at " + classFile); return classFile; } classFile = findClassFile(getScriptBinDirectories(), classAbsolutePath, className); if (classFile != null) { Msg.trace(GhidraScriptUtil.class, "Resource file " + sourceFile + " class found at " + classFile); return classFile; } // default to a non-existent file return new ResourceFile(GhidraScriptUtil.USER_SCRIPTS_BIN_DIR + "/" + className); } private static ResourceFile getClassFileByName(String rawName) { String path = rawName.replace('.', '/'); String className = path + ".class"; // // Note: in this case, we *only* want to search the script bin dirs, as we do not want // to find other class elements that may be in the development environment. For // example, we do not want to find non-script classes in the development bin dirs, // as those are loaded by our parent class loader. If we load them, then they will // not be the same class instances. // Set<ResourceFile> matchingClassFiles = new HashSet<>(); Collection<ResourceFile> userBinDirectories = GhidraScriptUtil.getScriptBinDirectories(); for (ResourceFile file : userBinDirectories) { ResourceFile testFile = new ResourceFile(file, className); if (testFile.exists()) { matchingClassFiles.add(testFile); } } return maybeWarnAboutNameConflict(className, matchingClassFiles); } private static ResourceFile findClassFile(Collection<ResourceFile> binDirs, String classAbsolutePath, String className) { Set<ResourceFile> matchingClassFiles = new HashSet<>(); for (ResourceFile binDir : binDirs) { ResourceFile binParentFile = binDir.getParentFile(); String absoluteParentPath = binParentFile.getAbsolutePath(); if (classAbsolutePath.startsWith(absoluteParentPath)) { ResourceFile potentialFile = new ResourceFile(binDir, className); if (potentialFile.exists()) { matchingClassFiles.add(potentialFile); } } } return maybeWarnAboutNameConflict(className, matchingClassFiles); } private static ResourceFile maybeWarnAboutNameConflict(String className, Set<ResourceFile> matchingClassFiles) { int matchCount = matchingClassFiles.size(); if (matchCount == 1) { return matchingClassFiles.iterator().next(); } else if (matchCount > 1) { // // Unusual Code: When running from Eclipse we need to use the class file that is // in the Eclipse project's bin. If not, then users cannot debug // the scripts, as Eclipse doesn't know how to find the source. This // can happen when users link source into the scripts project. // We don't know if we are running from Eclipse, which means that this // will give out the wrong file in the case where we are not, but there // happen to be two different class files with the same name. // ResourceFile preferredFile = null; for (ResourceFile file : matchingClassFiles) { if (file.getParentFile().getAbsolutePath().equals( GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) { preferredFile = file; break; } } if (preferredFile == null) { // just pick one preferredFile = matchingClassFiles.iterator().next(); } Msg.warn(GhidraScriptUtil.class, "Found " + matchCount + " class files named " + className + ". Using: " + preferredFile); return preferredFile; } return null; } /** * Returns the list of directories to which scripts are compiled. * @return the list * * @see #getScriptCompileOutputDirectory(ResourceFile) */ public static List<ResourceFile> getScriptBinDirectories() { return Arrays.asList(new ResourceFile(USER_SCRIPTS_BIN_DIR)); } /** * Returns a list of directories. Development directories differ from standard script * directories in that the former have a bin directory at a different location from * the latter, due to the setup of the development environment. * * @return Returns a list of directories */ static Collection<ResourceFile> getDevelopmentScriptBinDirectories() { if (!SystemUtilities.isInDevelopmentMode() || SystemUtilities.isInTestingMode()) { return Collections.emptyList(); } Set<ResourceFile> dirs = new HashSet<>(); for (Path path : scriptDirectoryPaths) { // // Assumed structure of script dir path: // /some/path/Ghidra/Features/Module/ghidra_scripts // // Desired path: // /some/path/Ghidra/Features/Module/bin/scripts ResourceFile scriptDir = path.getPath(); ResourceFile moduleDir = scriptDir.getParentFile(); dirs.add(new ResourceFile(moduleDir, BIN_DIR_NAME + File.separator + "scripts")); } return dirs; } /** * Deletes all script class files. */ public static void clean() { scriptFileToInfoMap.clear(); // clear our cache of old files scriptNameToFilesMap.clear(); File userdir = new File(USER_SCRIPTS_DIR); File[] classFiles = userdir.listFiles( (FileFilter) pathname -> pathname.getName().toLowerCase().endsWith(".class")); for (File classFile : classFiles) { classFile.delete(); } } /** * Returns the base name give a script file. * For example, given "C:\Temp\SomeClass.java", * it will return "SomeClass". * @param script the script * @return the base name */ public static String getBaseName(ResourceFile script) { String name = script.getName(); int pos = name.lastIndexOf('.'); if (pos == -1) { return name; } return name.substring(0, pos); } /** * Returns true if a ScriptInfo object exists for * the specified script file. * @param scriptFile the script file * @return true if a ScriptInfo object exists */ public static boolean contains(ResourceFile scriptFile) { return scriptFileToInfoMap.containsKey(scriptFile); } /** * Removes the ScriptInfo object for the specified file * @param scriptFile the script file */ public static void unloadScript(ResourceFile scriptFile) { scriptFileToInfoMap.remove(scriptFile); Iterator<ResourceFile> iter = scriptNameToFilesMap.get(scriptFile.getName()).iterator(); while (iter.hasNext()) { ResourceFile rFile = iter.next(); if (scriptFile.equals(rFile)) { iter.remove(); break; } } } /** * Returns an iterator over all script info objects. * @return an iterator over all script info objects */ public static Iterator<ScriptInfo> getScriptInfoIterator() { return scriptFileToInfoMap.values().iterator(); } /** * Returns the script info object for the specified script file * * @param scriptFile the script file * @return the script info object for the specified script file */ public static ScriptInfo getScriptInfo(ResourceFile scriptFile) { ScriptInfo info = scriptFileToInfoMap.get(scriptFile); if (info != null) { return info; } GhidraScriptProvider gsp = getProvider(scriptFile); info = new ScriptInfo(gsp, scriptFile); scriptFileToInfoMap.put(scriptFile, info); String name = scriptFile.getName(); List<ResourceFile> matchingFiles = scriptNameToFilesMap.get(name); matchingFiles.add(scriptFile); markAnyDuplicates(matchingFiles); return info; } private static void markAnyDuplicates(List<ResourceFile> files) { boolean isDuplicate = files.size() > 1; files.forEach(f -> scriptFileToInfoMap.get(f).setDuplicate(isDuplicate)); } /** * Returns a list of all Ghidra script providers * * @return a list of all Ghidra script providers */ // Note: this method is synchronized so that two threads do not try to create the list when null public synchronized static List<GhidraScriptProvider> getProviders() { if (providers == null) { List<GhidraScriptProvider> newProviders = new ArrayList<>(ClassSearcher.getInstances(GhidraScriptProvider.class)); Collections.sort(newProviders); providers = newProviders; } return providers; } /** * Returns the corresponding Ghidra script providers * for the specified script file. * @param scriptFile the script file * @return the Ghidra script provider */ public static GhidraScriptProvider getProvider(ResourceFile scriptFile) { String scriptFileName = scriptFile.getName().toLowerCase(); for (GhidraScriptProvider provider : getProviders()) { if (scriptFileName.endsWith(provider.getExtension().toLowerCase())) { return provider; } } return null; } /** * Returns true if a provider exists that can process the specified file. * * @param scriptFile the script file * @return true if a provider exists that can process the specified file */ public static boolean hasScriptProvider(ResourceFile scriptFile) { String scriptFileName = scriptFile.getName().toLowerCase(); for (GhidraScriptProvider provider : getProviders()) { if (scriptFileName.endsWith(provider.getExtension().toLowerCase())) { return true; } } return false; } /** * Creates a new script with a unique name using the specified provider in the * specified directory. * @param provider the Ghidra script provider * @param parentDirectory the directory where the new script will be created. * @param scriptDirectories The list of directories containing scripts (used to find a * unique name). * @return the newly created script file * @throws IOException if an i/o error occurs */ public static ResourceFile createNewScript(GhidraScriptProvider provider, ResourceFile parentDirectory, List<Path> scriptDirectories) throws IOException { String baseName = GhidraScriptConstants.DEFAULT_SCRIPT_NAME; String extension = provider.getExtension(); return createNewScript(baseName, extension, parentDirectory, scriptDirectories); } private static ResourceFile createNewScript(String scriptName, String extension, ResourceFile parentDirctory, List<Path> scriptDirectories) throws IOException { String baseName = scriptName; String className = baseName + extension; // we want to pick a name that is unique in *any* of the script directories int counter = 1; boolean exists = findScriptFileInPaths(scriptDirectories, className) != null; while (exists) { baseName = scriptName + counter++; className = baseName + extension; exists = findScriptFileInPaths(scriptDirectories, className) != null; if (counter > 1000) { throw new IOException( "Unable to create new script file, temporary files exceeded."); } } return new ResourceFile(parentDirctory, className); } /** Returns true if the given filename exists in any of the given directories */ private static ResourceFile findScriptFileInPaths(List<Path> scriptDirectories, String filename) { String validatedName = fixupName(filename); for (Path path : scriptDirectories) { ResourceFile file = new ResourceFile(path.getPath(), validatedName); if (file.exists()) { return file; } } return null; } /** * Fixup name issues, such as package parts in the name and inner class names. * <p> * This method can handle names with or without '.java' at the end; names with * '$' (inner classes) and names with '.' characters for package separators * * @param name the name of the script * @return the name as a '.java' file path (with '/'s and not '.'s) */ static String fixupName(String name) { if (name.endsWith(".java")) { name = name.substring(0, name.length() - 5); } String path = name.replace('.', '/'); int innerClassIndex = path.indexOf('$'); if (innerClassIndex != -1) { path = path.substring(0, innerClassIndex); } return path + ".java"; } /** * Uses the given name to find a matching script. This method only works because of the * limitation that all script names in Ghidra must be unique. If the given name has multiple * script matches, then a warning will be logged. * * @param name The name for which to find a script * @return The ScriptInfo that has the given name */ public static ScriptInfo findScriptByName(String name) { List<ResourceFile> matchingFiles = scriptNameToFilesMap.get(name); if (matchingFiles != null && !matchingFiles.isEmpty()) { ScriptInfo info = scriptFileToInfoMap.get(matchingFiles.get(0)); if (matchingFiles.size() > 1) { Msg.warn(GhidraScriptUtil.class, "Found duplicate scripts for name: " + name + ". Binding to script: " + info.getSourceFile()); } return info; } ResourceFile file = findScriptFileInPaths(scriptDirectoryPaths, name); if (file == null) { return null; } return getScriptInfo(file); // this will cache the created info } public static List<ResourceFile> getAllScripts() { List<ResourceFile> scriptList = new ArrayList<>(); for (Path dirPath : scriptDirectoryPaths) { updateAvailableScriptFilesForDirectory(scriptList, dirPath.getPath()); } return scriptList; } private static void updateAvailableScriptFilesForDirectory(List<ResourceFile> scriptAccumulator, ResourceFile directory) { ResourceFile[] files = directory.listFiles(); if (files == null) { return; } for (ResourceFile scriptFile : files) { if (scriptFile.isFile() && hasScriptProvider(scriptFile)) { scriptAccumulator.add(scriptFile); } } } /** * Looks through all of the current {@link ScriptInfo}s to see if one already exists with * the given name. * @param scriptName The name to check * @return true if the name is not taken by an existing {@link ScriptInfo}. */ public static boolean alreadyExists(String scriptName) { return getExistingScriptInfo(scriptName) != null; } /** * Returns the existing script info for the given name. The script environment limits * scripts such that names are unique. If this method returns a non-null value, then the * name given name is taken. * * @param scriptName the name of the script for which to get a ScriptInfo * @return a ScriptInfo matching the given name; null if no script by that name is known to * the script manager */ public static ScriptInfo getExistingScriptInfo(String scriptName) { List<ResourceFile> matchingFiles = scriptNameToFilesMap.get(scriptName); if (matchingFiles.isEmpty()) { return null; } return scriptFileToInfoMap.get(matchingFiles.get(0)); } /** * Runs the specified script with the specified state * * @param scriptState state representing environment variables that the script is able to access * @param script Script to be run * @param writer the writer to which warning and error messages will be written * @param originator the client class requesting the script run; used for logging * @param monitor the task monitor * @return whether the script successfully completed running */ public static boolean runScript(GhidraState scriptState, GhidraScript script, PrintWriter writer, Object originator, TaskMonitor monitor) { ResourceFile srcFile = script.getSourceFile(); String scriptName = srcFile != null ? srcFile.getAbsolutePath() : (script.getClass().getName() + ".class"); try { Msg.info(originator, "SCRIPT: " + scriptName); script.execute(scriptState, monitor, writer); writer.flush(); } catch (Exception exc) { Program prog = scriptState.getCurrentProgram(); String path = (prog != null ? prog.getExecutablePath() : "Current program is null."); String logErrorMsg = path + "\nREPORT SCRIPT ERROR: " + scriptName + " : " + exc.getMessage(); Msg.error(originator, logErrorMsg, exc); return false; } return true; } /** * Updates every known script's duplicate value. */ public static void refreshDuplicates() { scriptNameToFilesMap.values().forEach(files -> { boolean isDuplicate = files.size() > 1; files.forEach(file -> scriptFileToInfoMap.get(file).setDuplicate(isDuplicate)); }); } }
Tests - fixed script test failing due to odd remote test directory structure
Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java
Tests - fixed script test failing due to odd remote test directory structure
<ide><path>hidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java <ide> <ide> /** <ide> * Determine if the specified file is contained within the Ghidra installation. <del> * @param file - file or directory to check <add> * @param file file or directory to check <ide> * @return true if file is contained within Ghidra application root. <ide> */ <del> public static boolean isSystemFile(ResourceFile file) { <add> private static boolean isSystemFile(ResourceFile file) { <ide> try { <ide> String filePath = file.getCanonicalPath().replace('\\', '/'); <add> if (filePath.startsWith(USER_SCRIPTS_DIR)) { <add> // a script inside of the user scripts dir is not a 'system' script <add> return false; <add> } <add> <ide> Collection<ResourceFile> roots = Application.getApplicationRootDirectories(); <ide> for (ResourceFile resourceFile : roots) { <ide> String installPath = resourceFile.getCanonicalPath().replace('\\', '/'); <ide> // <ide> ResourceFile preferredFile = null; <ide> for (ResourceFile file : matchingClassFiles) { <del> if (file.getParentFile().getAbsolutePath().equals( <del> GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) { <add> if (file.getParentFile() <add> .getAbsolutePath() <add> .equals( <add> GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) { <ide> preferredFile = file; <ide> break; <ide> }
Java
apache-2.0
28d4b08ddba78a21cc1e792548ac8607be2243a9
0
open-keychain/openpgp-api
/* * Copyright (C) 2014-2015 Dominik Schürmann <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openintents.openpgp.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.ParcelFileDescriptor; import android.util.Log; import org.openintents.openpgp.IOpenPgpService2; import org.openintents.openpgp.OpenPgpError; public class OpenPgpApi { public static final String TAG = "OpenPgp API"; public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2"; /** * see CHANGELOG.md */ public static final int API_VERSION = 11; /** * General extras * -------------- * * required extras: * int EXTRA_API_VERSION (always required) * * returned extras: * int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED) * OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR) * PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED) */ /** * This action performs no operation, but can be used to check if the App has permission * to access the API in general, returning a user interaction PendingIntent otherwise. * This can be used to trigger the permission dialog explicitly. * * This action uses no extras. */ public static final String ACTION_CHECK_PERMISSION = "org.openintents.openpgp.action.CHECK_PERMISSION"; @Deprecated public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN"; /** * Sign text resulting in a cleartext signature * Some magic pre-processing of the text is done to convert it to a format usable for * cleartext signatures per RFC 4880 before the text is actually signed: * - end cleartext with newline * - remove whitespaces on line endings * * required extras: * long EXTRA_SIGN_KEY_ID (key id of signing key) * * optional extras: * char[] EXTRA_PASSPHRASE (key passphrase) */ public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN"; /** * Sign text or binary data resulting in a detached signature. * No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)! * The detached signature is returned separately in RESULT_DETACHED_SIGNATURE. * * required extras: * long EXTRA_SIGN_KEY_ID (key id of signing key) * * optional extras: * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature) * char[] EXTRA_PASSPHRASE (key passphrase) * * returned extras: * byte[] RESULT_DETACHED_SIGNATURE * String RESULT_SIGNATURE_MICALG (contains the name of the used signature algorithm as a string) */ public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN"; /** * Encrypt * * required extras: * String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT) * or * long[] EXTRA_KEY_IDS * * optional extras: * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output) * char[] EXTRA_PASSPHRASE (key passphrase) * String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata) * boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true) */ public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT"; /** * Sign and encrypt * * required extras: * String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT) * or * long[] EXTRA_KEY_IDS * * optional extras: * long EXTRA_SIGN_KEY_ID (key id of signing key) * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output) * char[] EXTRA_PASSPHRASE (key passphrase) * String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata) * boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true) */ public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT"; public static final String ACTION_QUERY_AUTOCRYPT_STATUS = "org.openintents.openpgp.action.QUERY_AUTOCRYPT_STATUS"; /** * Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted, * and also signed-only input. * OutputStream is optional, e.g., for verifying detached signatures! * * If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING * in addition a PendingIntent is returned via RESULT_INTENT to download missing keys. * On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open * the key view in OpenKeychain. * * optional extras: * byte[] EXTRA_DETACHED_SIGNATURE (detached signature) * * returned extras: * OpenPgpSignatureResult RESULT_SIGNATURE * OpenPgpDecryptionResult RESULT_DECRYPTION * OpenPgpDecryptMetadata RESULT_METADATA * String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any) */ public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY"; /** * Decrypts the header of an encrypted file to retrieve metadata such as original filename. * * This does not decrypt the actual content of the file. * * returned extras: * OpenPgpDecryptMetadata RESULT_METADATA * String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any) */ public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA"; /** * Select key id for signing * * optional extras: * String EXTRA_USER_ID * * returned extras: * long EXTRA_SIGN_KEY_ID */ public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID"; /** * Get key ids based on given user ids (=emails) * * required extras: * String[] EXTRA_USER_IDS * * returned extras: * long[] RESULT_KEY_IDS */ public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS"; /** * This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key * corresponding to the given key id in its database. * * It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key. * The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver. * * If an Output stream has been defined the whole public key is returned. * required extras: * long EXTRA_KEY_ID * * optional extras: * String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor) */ public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY"; /** * Backup all keys given by EXTRA_KEY_IDS and if requested their secret parts. * The encrypted backup will be written to the OutputStream. * The client app has no access to the backup code used to encrypt the backup! * This operation always requires user interaction with RESULT_CODE_USER_INTERACTION_REQUIRED! * * required extras: * long[] EXTRA_KEY_IDS (keys that should be included in the backup) * boolean EXTRA_BACKUP_SECRET (also backup secret keys) */ public static final String ACTION_BACKUP = "org.openintents.openpgp.action.BACKUP"; public static final String ACTION_UPDATE_AUTOCRYPT_PEER = "org.openintents.openpgp.action.UPDATE_AUTOCRYPT_PEER"; /* Intent extras */ public static final String EXTRA_API_VERSION = "api_version"; // ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY // request ASCII Armor for output // OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53) public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor"; // ACTION_DETACHED_SIGN public static final String RESULT_DETACHED_SIGNATURE = "detached_signature"; public static final String RESULT_SIGNATURE_MICALG = "signature_micalg"; // ENCRYPT, SIGN_AND_ENCRYPT, QUERY_AUTOCRYPT_STATUS public static final String EXTRA_USER_IDS = "user_ids"; public static final String EXTRA_KEY_IDS = "key_ids"; public static final String EXTRA_KEY_IDS_SELECTED = "key_ids_selected"; public static final String EXTRA_SIGN_KEY_ID = "sign_key_id"; public static final String RESULT_KEYS_CONFIRMED = "keys_confirmed"; public static final String RESULT_AUTOCRYPT_STATUS = "autocrypt_status"; public static final int AUTOCRYPT_STATUS_UNAVAILABLE = 0; public static final int AUTOCRYPT_STATUS_DISCOURAGE = 1; public static final int AUTOCRYPT_STATUS_AVAILABLE = 2; public static final int AUTOCRYPT_STATUS_MUTUAL = 3; // optional extras: public static final String EXTRA_PASSPHRASE = "passphrase"; public static final String EXTRA_ORIGINAL_FILENAME = "original_filename"; public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression"; public static final String EXTRA_OPPORTUNISTIC_ENCRYPTION = "opportunistic"; // GET_SIGN_KEY_ID public static final String EXTRA_USER_ID = "user_id"; // GET_KEY public static final String EXTRA_KEY_ID = "key_id"; public static final String EXTRA_MINIMIZE = "minimize"; public static final String EXTRA_MINIMIZE_USER_ID = "minimize_user_id"; public static final String RESULT_KEY_IDS = "key_ids"; // BACKUP public static final String EXTRA_BACKUP_SECRET = "backup_secret"; /* Service Intent returns */ public static final String RESULT_CODE = "result_code"; // get actual error object from RESULT_ERROR public static final int RESULT_CODE_ERROR = 0; // success! public static final int RESULT_CODE_SUCCESS = 1; // get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult, // and execute service method again in onActivityResult public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2; public static final String RESULT_ERROR = "error"; public static final String RESULT_INTENT = "intent"; // DECRYPT_VERIFY public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature"; public static final String EXTRA_PROGRESS_MESSENGER = "progress_messenger"; public static final String EXTRA_DATA_LENGTH = "data_length"; public static final String EXTRA_DECRYPTION_RESULT = "decryption_result"; public static final String EXTRA_SENDER_ADDRESS = "sender_address"; public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning"; public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id"; public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update"; public static final String EXTRA_AUTOCRYPT_PEER_GOSSIP_UPDATES = "autocrypt_peer_gossip_updates"; public static final String RESULT_SIGNATURE = "signature"; public static final String RESULT_DECRYPTION = "decryption"; public static final String RESULT_METADATA = "metadata"; public static final String RESULT_INSECURE_DETAIL_INTENT = "insecure_detail_intent"; public static final String RESULT_OVERRIDE_CRYPTO_WARNING = "override_crypto_warning"; // This will be the charset which was specified in the headers of ascii armored input, if any public static final String RESULT_CHARSET = "charset"; // INTERNAL, must not be used public static final String EXTRA_CALL_UUID1 = "call_uuid1"; public static final String EXTRA_CALL_UUID2 = "call_uuid2"; IOpenPgpService2 mService; Context mContext; final AtomicInteger mPipeIdGen = new AtomicInteger(); public OpenPgpApi(Context context, IOpenPgpService2 service) { this.mContext = context; this.mService = service; } public interface IOpenPgpCallback { void onReturn(final Intent result); } private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> { Intent data; InputStream is; OutputStream os; IOpenPgpCallback callback; private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) { this.data = data; this.is = is; this.os = os; this.callback = callback; } @Override protected Intent doInBackground(Void... unused) { return executeApi(data, is, os); } protected void onPostExecute(Intent result) { callback.onReturn(result); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) { OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback); // don't serialize async tasks! // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } else { task.execute((Void[]) null); } } public Intent executeApi(Intent data, InputStream is, OutputStream os) { ParcelFileDescriptor input = null; try { if (is != null) { input = ParcelFileDescriptorUtil.pipeFrom(is); } return executeApi(data, input, os); } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return result; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } } } } /** * InputStream and OutputStreams are always closed after operating on them! */ public Intent executeApi(Intent data, ParcelFileDescriptor input, OutputStream os) { ParcelFileDescriptor output = null; try { // always send version from client data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION); Intent result; Thread pumpThread = null; int outputPipeId = 0; if (os != null) { outputPipeId = mPipeIdGen.incrementAndGet(); output = mService.createOutputPipe(outputPipeId); pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output); } // blocks until result is ready result = mService.execute(data, input, outputPipeId); // set class loader to current context to allow unparcelling // of OpenPgpError and OpenPgpSignatureResult // http://stackoverflow.com/a/3806769 result.setExtrasClassLoader(mContext.getClassLoader()); //wait for ALL data being pumped from remote side if (pumpThread != null) { pumpThread.join(); } return result; } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return result; } finally { // close() is required to halt the TransferThread if (output != null) { try { output.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } } } } }
openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpApi.java
/* * Copyright (C) 2014-2015 Dominik Schürmann <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openintents.openpgp.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.ParcelFileDescriptor; import android.util.Log; import org.openintents.openpgp.IOpenPgpService2; import org.openintents.openpgp.OpenPgpError; public class OpenPgpApi { public static final String TAG = "OpenPgp API"; public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2"; /** * see CHANGELOG.md */ public static final int API_VERSION = 11; /** * General extras * -------------- * * required extras: * int EXTRA_API_VERSION (always required) * * returned extras: * int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED) * OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR) * PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED) */ /** * This action performs no operation, but can be used to check if the App has permission * to access the API in general, returning a user interaction PendingIntent otherwise. * This can be used to trigger the permission dialog explicitly. * * This action uses no extras. */ public static final String ACTION_CHECK_PERMISSION = "org.openintents.openpgp.action.CHECK_PERMISSION"; @Deprecated public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN"; /** * Sign text resulting in a cleartext signature * Some magic pre-processing of the text is done to convert it to a format usable for * cleartext signatures per RFC 4880 before the text is actually signed: * - end cleartext with newline * - remove whitespaces on line endings * * required extras: * long EXTRA_SIGN_KEY_ID (key id of signing key) * * optional extras: * char[] EXTRA_PASSPHRASE (key passphrase) */ public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN"; /** * Sign text or binary data resulting in a detached signature. * No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)! * The detached signature is returned separately in RESULT_DETACHED_SIGNATURE. * * required extras: * long EXTRA_SIGN_KEY_ID (key id of signing key) * * optional extras: * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature) * char[] EXTRA_PASSPHRASE (key passphrase) * * returned extras: * byte[] RESULT_DETACHED_SIGNATURE * String RESULT_SIGNATURE_MICALG (contains the name of the used signature algorithm as a string) */ public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN"; /** * Encrypt * * required extras: * String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT) * or * long[] EXTRA_KEY_IDS * * optional extras: * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output) * char[] EXTRA_PASSPHRASE (key passphrase) * String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata) * boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true) */ public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT"; /** * Sign and encrypt * * required extras: * String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT) * or * long[] EXTRA_KEY_IDS * * optional extras: * long EXTRA_SIGN_KEY_ID (key id of signing key) * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output) * char[] EXTRA_PASSPHRASE (key passphrase) * String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata) * boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true) */ public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT"; public static final String ACTION_QUERY_AUTOCRYPT_STATUS = "org.openintents.openpgp.action.QUERY_AUTOCRYPT_STATUS"; /** * Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted, * and also signed-only input. * OutputStream is optional, e.g., for verifying detached signatures! * * If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING * in addition a PendingIntent is returned via RESULT_INTENT to download missing keys. * On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open * the key view in OpenKeychain. * * optional extras: * byte[] EXTRA_DETACHED_SIGNATURE (detached signature) * * returned extras: * OpenPgpSignatureResult RESULT_SIGNATURE * OpenPgpDecryptionResult RESULT_DECRYPTION * OpenPgpDecryptMetadata RESULT_METADATA * String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any) */ public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY"; /** * Decrypts the header of an encrypted file to retrieve metadata such as original filename. * * This does not decrypt the actual content of the file. * * returned extras: * OpenPgpDecryptMetadata RESULT_METADATA * String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any) */ public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA"; /** * Select key id for signing * * optional extras: * String EXTRA_USER_ID * * returned extras: * long EXTRA_SIGN_KEY_ID */ public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID"; /** * Get key ids based on given user ids (=emails) * * required extras: * String[] EXTRA_USER_IDS * * returned extras: * long[] RESULT_KEY_IDS */ public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS"; /** * This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key * corresponding to the given key id in its database. * * It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key. * The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver. * * If an Output stream has been defined the whole public key is returned. * required extras: * long EXTRA_KEY_ID * * optional extras: * String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor) */ public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY"; /** * Backup all keys given by EXTRA_KEY_IDS and if requested their secret parts. * The encrypted backup will be written to the OutputStream. * The client app has no access to the backup code used to encrypt the backup! * This operation always requires user interaction with RESULT_CODE_USER_INTERACTION_REQUIRED! * * required extras: * long[] EXTRA_KEY_IDS (keys that should be included in the backup) * boolean EXTRA_BACKUP_SECRET (also backup secret keys) */ public static final String ACTION_BACKUP = "org.openintents.openpgp.action.BACKUP"; public static final String ACTION_UPDATE_AUTOCRYPT_PEER = "org.openintents.openpgp.action.UPDATE_AUTOCRYPT_PEER"; /* Intent extras */ public static final String EXTRA_API_VERSION = "api_version"; // ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY // request ASCII Armor for output // OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53) public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor"; // ACTION_DETACHED_SIGN public static final String RESULT_DETACHED_SIGNATURE = "detached_signature"; public static final String RESULT_SIGNATURE_MICALG = "signature_micalg"; // ENCRYPT, SIGN_AND_ENCRYPT, QUERY_AUTOCRYPT_STATUS public static final String EXTRA_USER_IDS = "user_ids"; public static final String EXTRA_KEY_IDS = "key_ids"; public static final String EXTRA_KEY_IDS_SELECTED = "key_ids_selected"; public static final String EXTRA_SIGN_KEY_ID = "sign_key_id"; public static final String RESULT_KEYS_CONFIRMED = "keys_confirmed"; public static final String RESULT_AUTOCRYPT_STATUS = "autocrypt_status"; public static final int AUTOCRYPT_STATUS_UNAVAILABLE = 0; public static final int AUTOCRYPT_STATUS_DISCOURAGE = 1; public static final int AUTOCRYPT_STATUS_AVAILABLE = 2; public static final int AUTOCRYPT_STATUS_MUTUAL = 3; // optional extras: public static final String EXTRA_PASSPHRASE = "passphrase"; public static final String EXTRA_ORIGINAL_FILENAME = "original_filename"; public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression"; public static final String EXTRA_OPPORTUNISTIC_ENCRYPTION = "opportunistic"; // GET_SIGN_KEY_ID public static final String EXTRA_USER_ID = "user_id"; // GET_KEY public static final String EXTRA_KEY_ID = "key_id"; public static final String EXTRA_MINIMIZE = "minimize"; public static final String EXTRA_MINIMIZE_USER_ID = "minimize_user_id"; public static final String RESULT_KEY_IDS = "key_ids"; // BACKUP public static final String EXTRA_BACKUP_SECRET = "backup_secret"; /* Service Intent returns */ public static final String RESULT_CODE = "result_code"; // get actual error object from RESULT_ERROR public static final int RESULT_CODE_ERROR = 0; // success! public static final int RESULT_CODE_SUCCESS = 1; // get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult, // and execute service method again in onActivityResult public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2; public static final String RESULT_ERROR = "error"; public static final String RESULT_INTENT = "intent"; // DECRYPT_VERIFY public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature"; public static final String EXTRA_PROGRESS_MESSENGER = "progress_messenger"; public static final String EXTRA_DATA_LENGTH = "data_length"; public static final String EXTRA_DECRYPTION_RESULT = "decryption_result"; public static final String EXTRA_SENDER_ADDRESS = "sender_address"; public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning"; public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id"; public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update"; public static final String RESULT_SIGNATURE = "signature"; public static final String RESULT_DECRYPTION = "decryption"; public static final String RESULT_METADATA = "metadata"; public static final String RESULT_INSECURE_DETAIL_INTENT = "insecure_detail_intent"; public static final String RESULT_OVERRIDE_CRYPTO_WARNING = "override_crypto_warning"; // This will be the charset which was specified in the headers of ascii armored input, if any public static final String RESULT_CHARSET = "charset"; // INTERNAL, must not be used public static final String EXTRA_CALL_UUID1 = "call_uuid1"; public static final String EXTRA_CALL_UUID2 = "call_uuid2"; IOpenPgpService2 mService; Context mContext; final AtomicInteger mPipeIdGen = new AtomicInteger(); public OpenPgpApi(Context context, IOpenPgpService2 service) { this.mContext = context; this.mService = service; } public interface IOpenPgpCallback { void onReturn(final Intent result); } private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> { Intent data; InputStream is; OutputStream os; IOpenPgpCallback callback; private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) { this.data = data; this.is = is; this.os = os; this.callback = callback; } @Override protected Intent doInBackground(Void... unused) { return executeApi(data, is, os); } protected void onPostExecute(Intent result) { callback.onReturn(result); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) { OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback); // don't serialize async tasks! // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } else { task.execute((Void[]) null); } } public Intent executeApi(Intent data, InputStream is, OutputStream os) { ParcelFileDescriptor input = null; try { if (is != null) { input = ParcelFileDescriptorUtil.pipeFrom(is); } return executeApi(data, input, os); } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return result; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } } } } /** * InputStream and OutputStreams are always closed after operating on them! */ public Intent executeApi(Intent data, ParcelFileDescriptor input, OutputStream os) { ParcelFileDescriptor output = null; try { // always send version from client data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION); Intent result; Thread pumpThread = null; int outputPipeId = 0; if (os != null) { outputPipeId = mPipeIdGen.incrementAndGet(); output = mService.createOutputPipe(outputPipeId); pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output); } // blocks until result is ready result = mService.execute(data, input, outputPipeId); // set class loader to current context to allow unparcelling // of OpenPgpError and OpenPgpSignatureResult // http://stackoverflow.com/a/3806769 result.setExtrasClassLoader(mContext.getClassLoader()); //wait for ALL data being pumped from remote side if (pumpThread != null) { pumpThread.join(); } return result; } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return result; } finally { // close() is required to halt the TransferThread if (output != null) { try { output.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } } } } }
add extra for gossip updates
openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpApi.java
add extra for gossip updates
<ide><path>penpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpApi.java <ide> public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning"; <ide> public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id"; <ide> public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update"; <add> public static final String EXTRA_AUTOCRYPT_PEER_GOSSIP_UPDATES = "autocrypt_peer_gossip_updates"; <ide> public static final String RESULT_SIGNATURE = "signature"; <ide> public static final String RESULT_DECRYPTION = "decryption"; <ide> public static final String RESULT_METADATA = "metadata";
Java
agpl-3.0
error: pathspec 'src/main/java/com/imcode/imcms/domain/exception/SortNotSupportedException.java' did not match any file(s) known to git
8f6d5fa5fa7a9f62c2a90c501e86e19f8ee8b826
1
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
package com.imcode.imcms.domain.exception; public class SortNotSupportedException extends RuntimeException { private static final long serialVersionUID = 3599379164719922771L; public SortNotSupportedException(String message) { super(message); } }
src/main/java/com/imcode/imcms/domain/exception/SortNotSupportedException.java
Issue IMCMS-484: Improve the menu-administration - Create exception;
src/main/java/com/imcode/imcms/domain/exception/SortNotSupportedException.java
Issue IMCMS-484: Improve the menu-administration - Create exception;
<ide><path>rc/main/java/com/imcode/imcms/domain/exception/SortNotSupportedException.java <add>package com.imcode.imcms.domain.exception; <add> <add>public class SortNotSupportedException extends RuntimeException { <add> private static final long serialVersionUID = 3599379164719922771L; <add> <add> public SortNotSupportedException(String message) { <add> super(message); <add> } <add>}
Java
apache-2.0
15a93172063b7a7b2f1ba041d2263b314179d81a
0
atsolakid/jena,apache/jena,apache/jena,tr3vr/jena,kidaa/jena,jianglili007/jena,tr3vr/jena,CesarPantoja/jena,atsolakid/jena,kidaa/jena,kamir/jena,samaitra/jena,samaitra/jena,adrapereira/jena,adrapereira/jena,adrapereira/jena,atsolakid/jena,tr3vr/jena,samaitra/jena,jianglili007/jena,apache/jena,CesarPantoja/jena,samaitra/jena,apache/jena,jianglili007/jena,atsolakid/jena,kamir/jena,tr3vr/jena,kidaa/jena,CesarPantoja/jena,tr3vr/jena,kidaa/jena,atsolakid/jena,kamir/jena,kidaa/jena,tr3vr/jena,apache/jena,CesarPantoja/jena,jianglili007/jena,samaitra/jena,kamir/jena,CesarPantoja/jena,tr3vr/jena,jianglili007/jena,apache/jena,adrapereira/jena,kamir/jena,kamir/jena,adrapereira/jena,apache/jena,jianglili007/jena,samaitra/jena,apache/jena,jianglili007/jena,kamir/jena,CesarPantoja/jena,atsolakid/jena,kidaa/jena,CesarPantoja/jena,kidaa/jena,samaitra/jena,adrapereira/jena,atsolakid/jena,adrapereira/jena
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.fuseki.server; import org.apache.jena.atlas.lib.FileOps ; import org.apache.jena.atlas.lib.StrUtils ; import com.hp.hpl.jena.query.Dataset ; import com.hp.hpl.jena.tdb.TDB ; import com.hp.hpl.jena.tdb.TDBFactory ; import com.hp.hpl.jena.tdb.base.file.Location ; import com.hp.hpl.jena.tdb.transaction.DatasetGraphTransaction ; public class SystemState { private static String SystemDatabaseLocation ; // Testing may reset this. public static Location location ; private static Dataset dataset = null ; private static DatasetGraphTransaction dsg = null ; public static Dataset getDataset() { init() ; return dataset ; } public static DatasetGraphTransaction getDatasetGraph() { init() ; return dsg ; } private static boolean initialized = false ; private static void init() { init$() ; } public /* for testing */ static void init$() { if ( initialized ) return ; initialized = true ; if ( location == null ) location = Location.create(FusekiServer.dirSystemDatabase.toString()) ; if ( ! location.isMem() ) FileOps.ensureDir(location.getDirectoryPath()) ; dataset = TDBFactory.createDataset(location) ; dsg = (DatasetGraphTransaction)(dataset.asDatasetGraph()) ; dsg.getContext().set(TDB.symUnionDefaultGraph, false) ; } public static String PREFIXES = StrUtils.strjoinNL ("BASE <http://example/base#>", "PREFIX ja: <http://jena.hpl.hp.com/2005/11/Assembler#>", "PREFIX fu: <http://jena.apache.org/fuseki#>", "PREFIX fuseki: <http://jena.apache.org/fuseki#>", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>", "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>", "PREFIX tdb: <http://jena.hpl.hp.com/2008/tdb#>", "PREFIX sdb: <http://jena.hpl.hp.com/20087/sdb#>", "PREFIX list: <http://jena.hpl.hp.com/ARQ/list#>", "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>", "PREFIX apf: <http://jena.hpl.hp.com/ARQ/property#>", "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#>", "") ; }
jena-fuseki2/src/main/java/org/apache/jena/fuseki/server/SystemState.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.fuseki.server; import org.apache.jena.atlas.lib.FileOps ; import org.apache.jena.atlas.lib.StrUtils ; import com.hp.hpl.jena.query.Dataset ; import com.hp.hpl.jena.tdb.TDB ; import com.hp.hpl.jena.tdb.TDBFactory ; import com.hp.hpl.jena.tdb.base.file.Location ; import com.hp.hpl.jena.tdb.transaction.DatasetGraphTransaction ; public class SystemState { private static String SystemDatabaseLocation ; // Testing may reset this. public static Location location ; private static Dataset dataset = null ; private static DatasetGraphTransaction dsg = null ; public static Dataset getDataset() { init() ; return dataset ; } public static DatasetGraphTransaction getDatasetGraph() { init() ; return dsg ; } private static boolean initialized = false ; private static void init() { init$() ; } public /* for testing */ static void init$() { if ( initialized ) return ; initialized = true ; if ( location == null ) location = new Location(FusekiServer.dirSystemDatabase.toString()) ; if ( ! location.isMem() ) FileOps.ensureDir(location.getDirectoryPath()) ; dataset = TDBFactory.createDataset(location) ; dsg = (DatasetGraphTransaction)(dataset.asDatasetGraph()) ; dsg.getContext().set(TDB.symUnionDefaultGraph, false) ; } public static String PREFIXES = StrUtils.strjoinNL ("BASE <http://example/base#>", "PREFIX ja: <http://jena.hpl.hp.com/2005/11/Assembler#>", "PREFIX fu: <http://jena.apache.org/fuseki#>", "PREFIX fuseki: <http://jena.apache.org/fuseki#>", "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>", "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>", "PREFIX tdb: <http://jena.hpl.hp.com/2008/tdb#>", "PREFIX sdb: <http://jena.hpl.hp.com/20087/sdb#>", "PREFIX list: <http://jena.hpl.hp.com/ARQ/list#>", "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>", "PREFIX apf: <http://jena.hpl.hp.com/ARQ/property#>", "PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#>", "") ; }
Sync with Location changes in TDB.
jena-fuseki2/src/main/java/org/apache/jena/fuseki/server/SystemState.java
Sync with Location changes in TDB.
<ide><path>ena-fuseki2/src/main/java/org/apache/jena/fuseki/server/SystemState.java <ide> initialized = true ; <ide> <ide> if ( location == null ) <del> location = new Location(FusekiServer.dirSystemDatabase.toString()) ; <add> location = Location.create(FusekiServer.dirSystemDatabase.toString()) ; <ide> <ide> if ( ! location.isMem() ) <ide> FileOps.ensureDir(location.getDirectoryPath()) ;
Java
apache-2.0
b10d92fa2ae5f3ece24e832785b5df9ec8b4f007
0
gsheldon/optaplanner,glamperi/optaplanner,codeaudit/optaplanner,eshen1991/optaplanner,baldimir/optaplanner,tkobayas/optaplanner,baldimir/optaplanner,tomasdavidorg/optaplanner,elsam/drools-planner-old,gsheldon/optaplanner,tkobayas/optaplanner,elsam/drools-planner-old,kunallimaye/optaplanner,bernardator/optaplanner,snurkabill/optaplanner,oskopek/optaplanner,droolsjbpm/optaplanner,baldimir/optaplanner,glamperi/optaplanner,eshen1991/optaplanner,bernardator/optaplanner,codeaudit/optaplanner,kunallimaye/optaplanner,droolsjbpm/optaplanner,elsam/drools-planner-old,netinept/Court-Scheduler,tkobayas/optaplanner,DieterDePaepe/optaplanner,netinept/Court-Scheduler,DieterDePaepe/optaplanner,kunallimaye/optaplanner,droolsjbpm/optaplanner,gsheldon/optaplanner,oskopek/optaplanner,tkobayas/optaplanner,tomasdavidorg/optaplanner,droolsjbpm/optaplanner,baldimir/optaplanner,tomasdavidorg/optaplanner,codeaudit/optaplanner,oskopek/optaplanner,oskopek/optaplanner,netinept/Court-Scheduler,glamperi/optaplanner,snurkabill/optaplanner,snurkabill/optaplanner,bernardator/optaplanner,eshen1991/optaplanner,gsheldon/optaplanner
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.planner.examples.traindesign.persistence; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.planner.core.solution.Solution; import org.drools.planner.examples.common.persistence.AbstractTxtSolutionImporter; import org.drools.planner.examples.pas.domain.AdmissionPart; import org.drools.planner.examples.pas.domain.Bed; import org.drools.planner.examples.pas.domain.BedDesignation; import org.drools.planner.examples.pas.domain.Department; import org.drools.planner.examples.pas.domain.DepartmentSpecialism; import org.drools.planner.examples.pas.domain.Equipment; import org.drools.planner.examples.pas.domain.Gender; import org.drools.planner.examples.pas.domain.GenderLimitation; import org.drools.planner.examples.pas.domain.Night; import org.drools.planner.examples.pas.domain.Patient; import org.drools.planner.examples.pas.domain.PreferredPatientEquipment; import org.drools.planner.examples.pas.domain.RequiredPatientEquipment; import org.drools.planner.examples.pas.domain.Room; import org.drools.planner.examples.pas.domain.RoomEquipment; import org.drools.planner.examples.pas.domain.RoomSpecialism; import org.drools.planner.examples.pas.domain.Specialism; import org.drools.planner.examples.traindesign.domain.RailArc; import org.drools.planner.examples.traindesign.domain.RailNode; import org.drools.planner.examples.traindesign.domain.TrainDesign; public class TrainDesignSolutionImporter extends AbstractTxtSolutionImporter { private static final String INPUT_FILE_SUFFIX = ".csv"; public static void main(String[] args) { new TrainDesignSolutionImporter().convertAll(); } public TrainDesignSolutionImporter() { super(new TrainDesignDaoImpl()); } @Override protected String getInputFileSuffix() { return INPUT_FILE_SUFFIX; } public TxtInputBuilder createTxtInputBuilder() { return new TrainDesignInputBuilder(); } public class TrainDesignInputBuilder extends TxtInputBuilder { private TrainDesign trainDesign; private Map<String, RailNode> nameToRailNodeMap = null; public Solution readSolution() throws IOException { trainDesign = new TrainDesign(); trainDesign.setId(0L); readRailNodeList(); readCarBlockList(); readRailArcList(); // createBedDesignationList(); logger.info("TrainDesign with {} rail nodes and {} rail arcs.", new Object[]{trainDesign.getRailNodeList().size(), trainDesign.getRailArcList().size()}); // BigInteger possibleSolutionSize = BigInteger.valueOf(trainDesign.getBedList().size()).pow( // trainDesign.getAdmissionPartList().size()); // String flooredPossibleSolutionSize = "10^" + (possibleSolutionSize.toString().length() - 1); // logger.info("TrainDesign with flooredPossibleSolutionSize ({}) and possibleSolutionSize({}).", // flooredPossibleSolutionSize, possibleSolutionSize); return trainDesign; } private void readRailNodeList() throws IOException { readConstantLine("\"Network Nodes\";;;;;;"); readConstantLine("\"Node \";\"BlockSwap Cost\";;;;;"); List<RailNode> railNodeList = new ArrayList<RailNode>(); nameToRailNodeMap = new HashMap<String, RailNode>(); String line = bufferedReader.readLine(); long id = 0L; while (!line.equals(";;;;;;")) { String[] lineTokens = splitBySemicolonSeparatedValue(line, 7); RailNode railNode = new RailNode(); railNode.setId(id); id++; railNode.setName(lineTokens[0]); railNode.setBlockSwapCost(Integer.parseInt(lineTokens[2])); railNodeList.add(railNode); nameToRailNodeMap.put(railNode.getName(), railNode); line = bufferedReader.readLine(); } trainDesign.setRailNodeList(railNodeList); } private void readCarBlockList() throws IOException { readConstantLine("\"Blocks\";;;;;;"); readConstantLine("\"BlockID\";\"Origin\";\"Destination\";\"# of Cars\";\"Total Length (Feet)\";\"Total Tonnage (Tons)\";\"Shortest Distance (Miles)\""); // List<RailNode> railNodeList = new ArrayList<RailNode>(); // nameToRailNodeMap = new HashMap<String, RailNode>(); String line = bufferedReader.readLine(); long id = 0L; while (!line.equals(";;;;;;")) { String[] lineTokens = splitBySemicolonSeparatedValue(line, 7); // RailNode railNode = new RailNode(); // railNode.setId(id); // id++; // railNode.setName(lineTokens[0]); // railNode.setBlockSwapCost(Integer.parseInt(lineTokens[2])); // railNodeList.add(railNode); // nameToRailNodeMap.put(railNode.getName(), railNode); line = bufferedReader.readLine(); } // trainDesign.setRailNodeList(railNodeList); } private void readRailArcList() throws IOException { readConstantLine("\"Network\";;;;;;"); readConstantLine("\"Origin\";\"Destination\";\"Distance (Miles)\";\"Max Train Length(Feet)\";\"Max Tonnage (Tons)\";\"Max # of Trains\";"); List<RailArc> railArcListList = new ArrayList<RailArc>(); String line = bufferedReader.readLine(); long id = 0L; while (!line.equals(";;;;;;")) { String[] lineTokens = splitBySemicolonSeparatedValue(line, 7); RailArc railArc = new RailArc(); railArc.setId(id); id++; RailNode origin = nameToRailNodeMap.get(lineTokens[0]); if (origin == null) { throw new IllegalArgumentException("Read line (" + line + ") has a non existing origin (" + lineTokens[0] + ")."); } railArc.setOrigin(origin); RailNode destination = nameToRailNodeMap.get(lineTokens[1]); if (destination == null) { throw new IllegalArgumentException("Read line (" + line + ") has a non existing destination (" + lineTokens[1] + ")."); } railArc.setDestination(destination); railArc.setDistance(Integer.parseInt(lineTokens[2])); railArc.setMaximumTrainLength(Integer.parseInt(lineTokens[3])); railArc.setMaximumTonnage(Integer.parseInt(lineTokens[4])); railArc.setMaximumNumberOfTrains(Integer.parseInt(lineTokens[5])); railArcListList.add(railArc); line = bufferedReader.readLine(); } trainDesign.setRailArcList(railArcListList); } // private void createBedDesignationList() { // List<AdmissionPart> admissionPartList = trainDesign.getAdmissionPartList(); // List<BedDesignation> bedDesignationList = new ArrayList<BedDesignation>(admissionPartList.size()); // long id = 0L; // for (AdmissionPart admissionPart : admissionPartList) { // BedDesignation bedDesignation = new BedDesignation(); // bedDesignation.setId(id); // id++; // bedDesignation.setAdmissionPart(admissionPart); // // Notice that we leave the PlanningVariable properties on null // bedDesignationList.add(bedDesignation); // } // trainDesign.setBedDesignationList(bedDesignationList); // } } }
drools-planner-examples/src/main/java/org/drools/planner/examples/traindesign/persistence/TrainDesignSolutionImporter.java
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.planner.examples.traindesign.persistence; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.planner.core.solution.Solution; import org.drools.planner.examples.common.persistence.AbstractTxtSolutionImporter; import org.drools.planner.examples.pas.domain.AdmissionPart; import org.drools.planner.examples.pas.domain.Bed; import org.drools.planner.examples.pas.domain.BedDesignation; import org.drools.planner.examples.pas.domain.Department; import org.drools.planner.examples.pas.domain.DepartmentSpecialism; import org.drools.planner.examples.pas.domain.Equipment; import org.drools.planner.examples.pas.domain.Gender; import org.drools.planner.examples.pas.domain.GenderLimitation; import org.drools.planner.examples.pas.domain.Night; import org.drools.planner.examples.pas.domain.Patient; import org.drools.planner.examples.pas.domain.PreferredPatientEquipment; import org.drools.planner.examples.pas.domain.RequiredPatientEquipment; import org.drools.planner.examples.pas.domain.Room; import org.drools.planner.examples.pas.domain.RoomEquipment; import org.drools.planner.examples.pas.domain.RoomSpecialism; import org.drools.planner.examples.pas.domain.Specialism; import org.drools.planner.examples.traindesign.domain.RailArc; import org.drools.planner.examples.traindesign.domain.RailNode; import org.drools.planner.examples.traindesign.domain.TrainDesign; public class TrainDesignSolutionImporter extends AbstractTxtSolutionImporter { public static void main(String[] args) { new TrainDesignSolutionImporter().convertAll(); } public TrainDesignSolutionImporter() { super(new TrainDesignDaoImpl()); } public TxtInputBuilder createTxtInputBuilder() { return new TrainDesignInputBuilder(); } public class TrainDesignInputBuilder extends TxtInputBuilder { private TrainDesign trainDesign; private Map<String, RailNode> nameToRailNodeMap = null; public Solution readSolution() throws IOException { trainDesign = new TrainDesign(); trainDesign.setId(0L); readRailNodeList(); readCarBlockList(); readRailArcList(); // createBedDesignationList(); logger.info("TrainDesign with {} rail nodes and {} rail arcs.", new Object[]{trainDesign.getRailNodeList().size(), trainDesign.getRailArcList().size()}); // BigInteger possibleSolutionSize = BigInteger.valueOf(trainDesign.getBedList().size()).pow( // trainDesign.getAdmissionPartList().size()); // String flooredPossibleSolutionSize = "10^" + (possibleSolutionSize.toString().length() - 1); // logger.info("TrainDesign with flooredPossibleSolutionSize ({}) and possibleSolutionSize({}).", // flooredPossibleSolutionSize, possibleSolutionSize); return trainDesign; } private void readRailNodeList() throws IOException { readConstantLine("\"Network Nodes\";;;;;;"); readConstantLine("\"Node \";\"BlockSwap Cost\";;;;;"); List<RailNode> railNodeList = new ArrayList<RailNode>(); nameToRailNodeMap = new HashMap<String, RailNode>(); String line = bufferedReader.readLine(); long id = 0L; while (!line.equals(";;;;;;")) { String[] lineTokens = splitBySemicolonSeparatedValue(line, 7); RailNode railNode = new RailNode(); railNode.setId(id); id++; railNode.setName(lineTokens[0]); railNode.setBlockSwapCost(Integer.parseInt(lineTokens[2])); railNodeList.add(railNode); nameToRailNodeMap.put(railNode.getName(), railNode); line = bufferedReader.readLine(); } trainDesign.setRailNodeList(railNodeList); } private void readCarBlockList() throws IOException { readConstantLine("\"Blocks\";;;;;;"); readConstantLine("\"BlockID\";\"Origin\";\"Destination\";\"# of Cars\";\"Total Length (Feet)\";\"Total Tonnage (Tons)\";\"Shortest Distance (Miles)\""); // List<RailNode> railNodeList = new ArrayList<RailNode>(); // nameToRailNodeMap = new HashMap<String, RailNode>(); String line = bufferedReader.readLine(); long id = 0L; while (!line.equals(";;;;;;")) { String[] lineTokens = splitBySemicolonSeparatedValue(line, 7); // RailNode railNode = new RailNode(); // railNode.setId(id); // id++; // railNode.setName(lineTokens[0]); // railNode.setBlockSwapCost(Integer.parseInt(lineTokens[2])); // railNodeList.add(railNode); // nameToRailNodeMap.put(railNode.getName(), railNode); line = bufferedReader.readLine(); } // trainDesign.setRailNodeList(railNodeList); } private void readRailArcList() throws IOException { readConstantLine("\"Network\";;;;;;"); readConstantLine("\"Origin\";\"Destination\";\"Distance (Miles)\";\"Max Train Length(Feet)\";\"Max Tonnage (Tons)\";\"Max # of Trains\";"); List<RailArc> railArcListList = new ArrayList<RailArc>(); String line = bufferedReader.readLine(); long id = 0L; while (!line.equals(";;;;;;")) { String[] lineTokens = splitBySemicolonSeparatedValue(line, 7); RailArc railArc = new RailArc(); railArc.setId(id); id++; RailNode origin = nameToRailNodeMap.get(lineTokens[0]); if (origin == null) { throw new IllegalArgumentException("Read line (" + line + ") has a non existing origin (" + lineTokens[0] + ")."); } railArc.setOrigin(origin); RailNode destination = nameToRailNodeMap.get(lineTokens[1]); if (destination == null) { throw new IllegalArgumentException("Read line (" + line + ") has a non existing destination (" + lineTokens[1] + ")."); } railArc.setDestination(destination); railArc.setDistance(Integer.parseInt(lineTokens[2])); railArc.setMaximumTrainLength(Integer.parseInt(lineTokens[3])); railArc.setMaximumTonnage(Integer.parseInt(lineTokens[4])); railArc.setMaximumNumberOfTrains(Integer.parseInt(lineTokens[5])); railArcListList.add(railArc); line = bufferedReader.readLine(); } trainDesign.setRailArcList(railArcListList); } // private void createBedDesignationList() { // List<AdmissionPart> admissionPartList = trainDesign.getAdmissionPartList(); // List<BedDesignation> bedDesignationList = new ArrayList<BedDesignation>(admissionPartList.size()); // long id = 0L; // for (AdmissionPart admissionPart : admissionPartList) { // BedDesignation bedDesignation = new BedDesignation(); // bedDesignation.setId(id); // id++; // bedDesignation.setAdmissionPart(admissionPart); // // Notice that we leave the PlanningVariable properties on null // bedDesignationList.add(bedDesignation); // } // trainDesign.setBedDesignationList(bedDesignationList); // } } }
TrainDesign (RAS 2011): importer file suffix
drools-planner-examples/src/main/java/org/drools/planner/examples/traindesign/persistence/TrainDesignSolutionImporter.java
TrainDesign (RAS 2011): importer file suffix
<ide><path>rools-planner-examples/src/main/java/org/drools/planner/examples/traindesign/persistence/TrainDesignSolutionImporter.java <ide> <ide> public class TrainDesignSolutionImporter extends AbstractTxtSolutionImporter { <ide> <add> private static final String INPUT_FILE_SUFFIX = ".csv"; <add> <ide> public static void main(String[] args) { <ide> new TrainDesignSolutionImporter().convertAll(); <ide> } <ide> <ide> public TrainDesignSolutionImporter() { <ide> super(new TrainDesignDaoImpl()); <add> } <add> <add> @Override <add> protected String getInputFileSuffix() { <add> return INPUT_FILE_SUFFIX; <ide> } <ide> <ide> public TxtInputBuilder createTxtInputBuilder() {
Java
apache-2.0
91387c8a2a2e9fa803e72b6a6016c3d1d3d443f3
0
WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules
/* * Copyright (c) 2015 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.apikey; import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.ldk.ExtendedSimpleModule; import org.labkey.api.module.DefaultModule; import org.labkey.api.module.ModuleContext; import org.labkey.api.view.WebPartFactory; import org.labkey.apikey.api.ApiKeyService; import org.labkey.apikey.api.JsonService; import org.labkey.apikey.api.JsonServiceManager; import org.labkey.apikey.service.ApiKeyServiceImpl; import org.labkey.apikey.service.JsonServiceManagerImpl; import java.util.Collection; import java.util.Collections; import java.util.Set; public class ApiKeyModule extends ExtendedSimpleModule { public static final String NAME = "ApiKey"; @Override public String getName() { return NAME; } @Override public double getVersion() { return 15.11; } @Override public boolean hasScripts() { return true; } @Override @NotNull protected Collection<WebPartFactory> createWebPartFactories() { return Collections.emptyList(); } @Override protected void init() { addController(ApiKeyController.NAME, ApiKeyController.class); JsonServiceManager.set(new JsonServiceManagerImpl()); ApiKeyService.set(new ApiKeyServiceImpl()); } @Override public void doStartupAfterSpringConfig(ModuleContext moduleContext) { // add a container listener so we'll know when our container is deleted: ContainerManager.addContainerListener(new ApiKeyContainerListener()); } @Override @NotNull public Collection<String> getSummary(Container c) { return Collections.emptyList(); } @Override @NotNull public Set<String> getSchemaNames() { return Collections.singleton(ApiKeySchema.NAME); } }
ApiKey/src/org/labkey/apikey/ApiKeyModule.java
/* * Copyright (c) 2015 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.apikey; import org.jetbrains.annotations.NotNull; import org.labkey.api.data.Container; import org.labkey.api.data.ContainerManager; import org.labkey.api.ldk.ExtendedSimpleModule; import org.labkey.api.module.DefaultModule; import org.labkey.api.module.ModuleContext; import org.labkey.api.view.WebPartFactory; import org.labkey.apikey.api.JsonService; import org.labkey.apikey.api.JsonServiceManager; import org.labkey.apikey.service.JsonServiceManagerImpl; import java.util.Collection; import java.util.Collections; import java.util.Set; public class ApiKeyModule extends ExtendedSimpleModule { public static final String NAME = "ApiKey"; @Override public String getName() { return NAME; } @Override public double getVersion() { return 15.11; } @Override public boolean hasScripts() { return true; } @Override @NotNull protected Collection<WebPartFactory> createWebPartFactories() { return Collections.emptyList(); } @Override protected void init() { addController(ApiKeyController.NAME, ApiKeyController.class); JsonServiceManager.set(new JsonServiceManagerImpl()); } @Override public void doStartupAfterSpringConfig(ModuleContext moduleContext) { // add a container listener so we'll know when our container is deleted: ContainerManager.addContainerListener(new ApiKeyContainerListener()); } @Override @NotNull public Collection<String> getSummary(Container c) { return Collections.emptyList(); } @Override @NotNull public Set<String> getSchemaNames() { return Collections.singleton(ApiKeySchema.NAME); } }
Actually populate the ApiKeyService on startup.
ApiKey/src/org/labkey/apikey/ApiKeyModule.java
Actually populate the ApiKeyService on startup.
<ide><path>piKey/src/org/labkey/apikey/ApiKeyModule.java <ide> import org.labkey.api.module.DefaultModule; <ide> import org.labkey.api.module.ModuleContext; <ide> import org.labkey.api.view.WebPartFactory; <add>import org.labkey.apikey.api.ApiKeyService; <ide> import org.labkey.apikey.api.JsonService; <ide> import org.labkey.apikey.api.JsonServiceManager; <add>import org.labkey.apikey.service.ApiKeyServiceImpl; <ide> import org.labkey.apikey.service.JsonServiceManagerImpl; <ide> <ide> import java.util.Collection; <ide> addController(ApiKeyController.NAME, ApiKeyController.class); <ide> <ide> JsonServiceManager.set(new JsonServiceManagerImpl()); <add> ApiKeyService.set(new ApiKeyServiceImpl()); <ide> } <ide> <ide> @Override
Java
apache-2.0
328fae3b025e6bb9847aff67ec37de422c808f13
0
IrynaIeremeichuk/java_pft
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import ru.stqa.pft.addressbook.model.GroupData; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by Sviatoslav on 07.12.2016. */ public class GroupHelper extends HelperBase { public GroupHelper(WebDriver wd) { super(wd); } public void returnToGroupPage() { click(By.linkText("group page")); } public void submitGroupCreation() { click(By.name("submit")); } public void fillGroupForm(GroupData groupData) { type(By.name("group_name"), groupData.getName()); type(By.name("group_header"), groupData.getHeader()); type(By.name("group_footer"), groupData.getFooter()); } public void initGroupCreation() { click(By.name("new")); } public void deleteSelectedGroups() { click(By.name("delete")); } public void initGroupModification() { click(By.name("edit")); } public void submitGroupModification() { click(By.name("update")); } public void create(GroupData group) { initGroupCreation(); fillGroupForm(group); submitGroupCreation(); returnToGroupPage(); } public void modify(GroupData group) { selectGroupById(group.getId()); initGroupModification(); fillGroupForm(group); submitGroupModification(); returnToGroupPage(); } public void delete(GroupData group) { selectGroupById(group.getId()); deleteSelectedGroups(); returnToGroupPage(); } public void selectGroupById(int id){ wd.findElement(By.cssSelector("input[value='"+ id +"']")).click(); } public boolean isThereAGroup() { return isElementPresent(By.name("selected[]")); } public int getGroupCount() { return wd.findElements(By.name("selected[]")).size(); } public Set<GroupData> all() { Set<GroupData> groups = new HashSet<>(); List<WebElement> elements = wd.findElements(By.cssSelector("span.group")); for(WebElement element: elements) { String name = element.getText(); int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); groups.add(new GroupData().withId(id).withName(name)); } return groups; } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java
package ru.stqa.pft.addressbook.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import ru.stqa.pft.addressbook.model.GroupData; import java.util.ArrayList; import java.util.List; /** * Created by Sviatoslav on 07.12.2016. */ public class GroupHelper extends HelperBase { public GroupHelper(WebDriver wd) { super(wd); } public void returnToGroupPage() { click(By.linkText("group page")); } public void submitGroupCreation() { click(By.name("submit")); } public void fillGroupForm(GroupData groupData) { type(By.name("group_name"), groupData.getName()); type(By.name("group_header"), groupData.getHeader()); type(By.name("group_footer"), groupData.getFooter()); } public void initGroupCreation() { click(By.name("new")); } public void deleteSelectedGroups() { click(By.name("delete")); } public void selectGroup(int index) { wd.findElements(By.name("selected[]")).get(index).click(); } public void initGroupModification() { click(By.name("edit")); } public void submitGroupModification() { click(By.name("update")); } public void create(GroupData group) { initGroupCreation(); fillGroupForm(group); submitGroupCreation(); returnToGroupPage(); } public void modify(int index, GroupData group) { selectGroup(index); initGroupModification(); fillGroupForm(group); submitGroupModification(); returnToGroupPage(); } public void delete(int index) { selectGroup(index); deleteSelectedGroups(); returnToGroupPage(); } public boolean isThereAGroup() { return isElementPresent(By.name("selected[]")); } public int getGroupCount() { return wd.findElements(By.name("selected[]")).size(); } public List<GroupData> list() { List<GroupData> groups = new ArrayList<GroupData>(); List<WebElement> elements = wd.findElements(By.cssSelector("span.group")); for(WebElement element: elements) { String name = element.getText(); int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); GroupData group = new GroupData().withId(id).withName(name); groups.add(group); } return groups; } }
List заменен на Set, откорректирован методы modify и delete (без index)
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java
List заменен на Set, откорректирован методы modify и delete (без index)
<ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/GroupHelper.java <ide> import ru.stqa.pft.addressbook.model.GroupData; <ide> <ide> import java.util.ArrayList; <add>import java.util.HashSet; <ide> import java.util.List; <add>import java.util.Set; <ide> <ide> /** <ide> * Created by Sviatoslav on 07.12.2016. <ide> click(By.name("delete")); <ide> } <ide> <del> public void selectGroup(int index) { <del> wd.findElements(By.name("selected[]")).get(index).click(); <del> } <del> <ide> public void initGroupModification() { <ide> click(By.name("edit")); <ide> } <ide> } <ide> <ide> <del> public void modify(int index, GroupData group) { <del> selectGroup(index); <add> public void modify(GroupData group) { <add> selectGroupById(group.getId()); <ide> initGroupModification(); <ide> fillGroupForm(group); <ide> submitGroupModification(); <ide> returnToGroupPage(); <ide> } <del> public void delete(int index) { <del> selectGroup(index); <add> <add> public void delete(GroupData group) { <add> selectGroupById(group.getId()); <ide> deleteSelectedGroups(); <ide> returnToGroupPage(); <add> } <add> <add> public void selectGroupById(int id){ <add> wd.findElement(By.cssSelector("input[value='"+ id +"']")).click(); <ide> } <ide> <ide> public boolean isThereAGroup() { <ide> return wd.findElements(By.name("selected[]")).size(); <ide> } <ide> <del> public List<GroupData> list() { <del> List<GroupData> groups = new ArrayList<GroupData>(); <add> public Set<GroupData> all() { <add> Set<GroupData> groups = new HashSet<>(); <ide> List<WebElement> elements = wd.findElements(By.cssSelector("span.group")); <ide> for(WebElement element: elements) { <del> String name = element.getText(); <del> int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); <del> GroupData group = new GroupData().withId(id).withName(name); <del> groups.add(group); <add> String name = element.getText(); <add> int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value")); <add> groups.add(new GroupData().withId(id).withName(name)); <ide> } <ide> return groups; <ide> <ide> } <add> <add> <ide> } <ide> <ide>
Java
bsd-2-clause
33a22292e09a12daab7892235d8aa3dc36989378
0
zlamalp/perun-wui,zlamalp/perun-wui,zlamalp/perun-wui
package cz.metacentrum.perun.wui.registrar.pages.steps; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import cz.metacentrum.perun.wui.json.Events; import cz.metacentrum.perun.wui.model.GeneralObject; import cz.metacentrum.perun.wui.model.PerunException; import cz.metacentrum.perun.wui.model.beans.Group; import cz.metacentrum.perun.wui.model.common.PerunPrincipal; import cz.metacentrum.perun.wui.registrar.client.resources.PerunRegistrarTranslation; import cz.metacentrum.perun.wui.registrar.pages.FormView; import cz.metacentrum.perun.wui.widgets.PerunButton; import cz.metacentrum.perun.wui.widgets.resources.PerunButtonType; import org.gwtbootstrap3.client.ui.Column; import org.gwtbootstrap3.client.ui.Heading; import org.gwtbootstrap3.client.ui.Icon; import org.gwtbootstrap3.client.ui.ListGroup; import org.gwtbootstrap3.client.ui.ListGroupItem; import org.gwtbootstrap3.client.ui.constants.ColumnOffset; import org.gwtbootstrap3.client.ui.constants.ColumnSize; import org.gwtbootstrap3.client.ui.constants.HeadingSize; import org.gwtbootstrap3.client.ui.constants.IconSize; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.constants.ListGroupItemType; import org.gwtbootstrap3.client.ui.constants.Pull; import org.gwtbootstrap3.client.ui.html.Text; /** * Represents a final step in registration process. Show info. * Contains methods caseXxx(...) e.g. caseVoInitGroupInit is called in usecase [ VO initial application -> Group application ] etc. * * @author Ondrej Velisek <[email protected]> */ public class SummaryStep implements Step { private FormView formView; private PerunRegistrarTranslation translation; private final String TARGET_EXISTING = "targetexisting"; private final String TARGET_NEW = "targetnew"; private final String TARGET_EXTENDED = "targetextended"; public SummaryStep(FormView formView) { this.formView = formView; this.translation = formView.getTranslation(); } @Override public void call(final PerunPrincipal pp, Summary summary, Events<Result> events) { Heading title = new Heading(HeadingSize.H2); ListGroup messages = new ListGroup(); if (summary.containsGroupInitResult()) { if (summary.containsVoInitResult()) { caseVoInitGroupInit(summary, title, messages); } else if (summary.containsVoExtResult()) { caseVoExtGroupInit(summary, title, messages); } else { caseGroupInit(summary, title, messages); } } else if (summary.containsGroupExtResult()) { if (summary.containsVoExtResult()) { caseVoExtGroupExt(summary, title, messages); } else { caseGroupExt(summary, title, messages); } } else { if (summary.containsVoInitResult()) { caseVoInit(summary, title, messages); } else if (summary.containsVoExtResult()) { caseVoExt(summary, title, messages); } else { // Steps should not be empty. } } } /** * Fill summary with result about VO initial application * * @param summary * @param title * @param messages */ private void caseVoInit(Summary summary, Heading title, ListGroup messages) { Result res = summary.getVoInitResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(res.getBean().getName())); } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfVo() || summary.alreadyAppliedToVo()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO extension application * * @param summary * @param title * @param messages */ private void caseVoExt(Summary summary, Heading title, ListGroup messages) { Result res = summary.getVoExtResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { title.add(new Text(" "+translation.extendTitleAutoApproval())); msg.setText(translation.extended(res.getBean().getName())); } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { // FIXME - solve this BLEEEH hack in better way. if (res.getException().getName().equals("DuplicateRegistrationAttemptException")) { res.getException().setName("DuplicateExtensionAttemptException"); } displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_EXTENDED); } else if (summary.alreadyAppliedForVoExtension() || summary.alreadyMemberOfVo()) { continueBtn = getContinueButton(TARGET_EXISTING); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about Group initial application * * @param summary * @param title * @param messages */ private void caseGroupInit(Summary summary, Heading title, ListGroup messages) { Result res = summary.getGroupInitResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { if (summary.alreadyAppliedToVo()) { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForVoAcceptation(((Group) res.getBean()).getShortName())); } else { title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(((Group) res.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedToGroup()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about Group extension application * * @param summary * @param title * @param messages */ private void caseGroupExt(Summary summary, Heading title, ListGroup messages) { Result res = summary.getGroupExtResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { if (summary.alreadyAppliedForVoExtension()) { title.add(new Text(" " + translation.extendTitle())); msg.setText(translation.waitForVoExtension(((Group) res.getBean()).getShortName())); } else { title.add(new Text(" " + translation.extendTitleAutoApproval())); msg.setText(translation.extended(((Group) res.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { // FIXME - solve this BLEEEH hack in better way. if (res.getException().getName().equals("DuplicateRegistrationAttemptException")) { res.getException().setName("DuplicateExtensionAttemptException"); } displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedForGroupExtension()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_EXTENDED); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO initial and Group initial application * * @param summary * @param title * @param messages */ private void caseVoInitGroupInit(Summary summary, Heading title, ListGroup messages) { Result resultVo = summary.getVoInitResult(); Result resultGroup = summary.getGroupInitResult(); // Show summary about initial application to VO if (resultVo.isOk()) { ListGroupItem msg = new ListGroupItem(); if (resultVo.hasAutoApproval()) { msg.setText(translation.registered(resultVo.getBean().getName())); } else { // Message from group application is sufficient in this case. } if (!msg.getText().isEmpty()) { messages.add(msg); } } else if (resultVo.getException() != null && "CantBeApprovedException".equals(resultVo.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. ListGroupItem msg = new ListGroupItem(); msg.setText(translation.waitForAcceptation()); messages.add(msg); } else { displayException(resultVo.getException(), resultVo.getBean()); } verifyMailMessage(summary, messages); // Show summary about application to group if (resultGroup.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (resultGroup.hasAutoApproval()) { if (resultVo.hasAutoApproval()) { title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(((Group) resultGroup.getBean()).getShortName())); } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForVoAcceptation(((Group) resultGroup.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); } else if (resultGroup.getException() != null && "CantBeApprovedException".equals(resultGroup.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO/Group manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); } else { displayException(resultGroup.getException(), resultGroup.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedToGroup()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if ((resultGroup.isOk() || resultGroup.getException().getName().equals("RegistrarException")) && (resultVo.isOk() || resultVo.getException().getName().equals("RegistrarException"))) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO extension and Group initial application * * @param summary * @param title * @param messages */ private void caseVoExtGroupInit(Summary summary, Heading title, ListGroup messages) { Result resultVo = summary.getVoExtResult(); Result resultGroup = summary.getGroupInitResult(); // Show summary about extension application to VO if (resultVo.isOk()) { ListGroupItem msg = new ListGroupItem(); if (resultVo.hasAutoApproval()) { msg.setText(translation.extended(resultVo.getBean().getName())); } else { // Message from group application is sufficient in this case. } if (!msg.getText().isEmpty()) { messages.add(msg); } } else if (resultVo.getException() != null && "CantBeApprovedException".equals(resultVo.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. ListGroupItem msg = new ListGroupItem(); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); } else { // FIXME - solve this BLEEEH hack in better way. if (resultVo.getException().getName().equals("DuplicateRegistrationAttemptException")) { resultVo.getException().setName("DuplicateExtensionAttemptException"); } displayException(resultVo.getException(), resultVo.getBean()); } // Show summary about application to group if (resultGroup.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (resultGroup.hasAutoApproval()) { if (resultVo.hasAutoApproval()) { // FIXME - tohle by se mělo vyhodnotit z předchozího stavu (není auto nebo byla chyba) title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(((Group) resultGroup.getBean()).getShortName())); } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForVoExtension(((Group) resultGroup.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); } else if (resultGroup.getException() != null && "CantBeApprovedException".equals(resultGroup.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO/Group manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); } else { displayException(resultGroup.getException(), resultGroup.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedToGroup()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (resultGroup.isOk() || resultGroup.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO extension and Group extension application * * @param summary * @param title * @param messages */ private void caseVoExtGroupExt(Summary summary, Heading title, ListGroup messages) { Result resultVo = summary.getVoExtResult(); Result resultGroup = summary.getGroupExtResult(); // Show summary about extension application to VO if (resultVo.isOk()) { ListGroupItem msg = new ListGroupItem(); if (resultVo.hasAutoApproval()) { msg.setText(translation.extended(resultVo.getBean().getName())); } else { // Message from group application is sufficient in this case. } if (!msg.getText().isEmpty()) { messages.add(msg); } } else if (resultVo.getException() != null && "CantBeApprovedException".equals(resultVo.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. ListGroupItem msg = new ListGroupItem(); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); } else { // FIXME - solve this BLEEEH hack in better way. if (resultVo.getException().getName().equals("DuplicateRegistrationAttemptException")) { resultVo.getException().setName("DuplicateExtensionAttemptException"); } displayException(resultVo.getException(), resultVo.getBean()); } // Show summary about application to group if (resultGroup.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (resultGroup.hasAutoApproval()) { if (resultVo.hasAutoApproval()) { title.add(new Text(" "+translation.extendTitleAutoApproval())); msg.setText(translation.extended(((Group) resultGroup.getBean()).getShortName())); } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForVoExtension(((Group) resultGroup.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); } messages.add(msg); } else if (resultGroup.getException() != null && "CantBeApprovedException".equals(resultGroup.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO/Group manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); } else { // FIXME - solve this BLEEEH hack in better way. if (resultVo.getException().getName().equals("DuplicateRegistrationAttemptException")) { resultVo.getException().setName("DuplicateExtensionAttemptException"); } displayException(resultGroup.getException(), resultGroup.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedForGroupExtension()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (resultGroup.isOk() || resultGroup.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_EXTENDED); } displaySummary(title, messages, continueBtn); } private Icon successIcon() { Icon success = new Icon(IconType.CHECK_CIRCLE); success.setColor("#5cb85c"); return success; } private void verifyMailMessage(Summary summary, ListGroup messages) { if (summary.mustRevalidateEmail() != null) { ListGroupItem verifyMail = new ListGroupItem(); verifyMail.add(new Icon(IconType.WARNING)); verifyMail.add(new Text(" " + translation.verifyMail(summary.mustRevalidateEmail()))); verifyMail.setType(ListGroupItemType.WARNING); messages.add(verifyMail); } } private void displaySummary(Heading title, ListGroup messages, PerunButton continueButton) { if (title != null || title.getWidgetCount() != 0 || !title.getText().isEmpty()) { formView.getForm().add(title); } if (messages != null || messages.getWidgetCount() != 0) { formView.getForm().add(messages); } if (continueButton != null) { formView.getForm().add(continueButton); } } private PerunButton getContinueButton(final String urlParameter) { if (Window.Location.getParameter(urlParameter) != null) { PerunButton continueButton = PerunButton.getButton(PerunButtonType.CONTINUE); continueButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { formView.getForm().clear(); Heading head = new Heading(HeadingSize.H4, translation.redirectingBackToService()); Icon spin = new Icon(IconType.SPINNER); spin.setSpin(true); spin.setSize(IconSize.LARGE); spin.setPull(Pull.LEFT); spin.setMarginTop(10); Column column = new Column(ColumnSize.MD_8, ColumnSize.LG_6, ColumnSize.SM_10, ColumnSize.XS_12); column.setOffset(ColumnOffset.MD_2,ColumnOffset.LG_3,ColumnOffset.SM_1,ColumnOffset.XS_0); column.add(spin); column.add(head); column.setMarginTop(30); formView.getForm().add(column); // WAIT 4 SEC BEFORE REDIRECT Timer timer = new Timer() { @Override public void run() { Window.Location.assign(Window.Location.getParameter(urlParameter)); } }; timer.schedule(7000); } }); return continueButton; } return null; } private void displayException(PerunException ex, GeneralObject bean) { formView.displayException(ex, bean); } @Override public Result getResult() { // Nobody should be after Summary step so nobody can call it. return null; } }
perun-wui-registrar/src/main/java/cz/metacentrum/perun/wui/registrar/pages/steps/SummaryStep.java
package cz.metacentrum.perun.wui.registrar.pages.steps; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import cz.metacentrum.perun.wui.json.Events; import cz.metacentrum.perun.wui.model.GeneralObject; import cz.metacentrum.perun.wui.model.PerunException; import cz.metacentrum.perun.wui.model.beans.Group; import cz.metacentrum.perun.wui.model.common.PerunPrincipal; import cz.metacentrum.perun.wui.registrar.client.resources.PerunRegistrarTranslation; import cz.metacentrum.perun.wui.registrar.pages.FormView; import cz.metacentrum.perun.wui.widgets.PerunButton; import cz.metacentrum.perun.wui.widgets.resources.PerunButtonType; import org.gwtbootstrap3.client.ui.Column; import org.gwtbootstrap3.client.ui.Heading; import org.gwtbootstrap3.client.ui.Icon; import org.gwtbootstrap3.client.ui.ListGroup; import org.gwtbootstrap3.client.ui.ListGroupItem; import org.gwtbootstrap3.client.ui.constants.ColumnOffset; import org.gwtbootstrap3.client.ui.constants.ColumnSize; import org.gwtbootstrap3.client.ui.constants.HeadingSize; import org.gwtbootstrap3.client.ui.constants.IconSize; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.constants.ListGroupItemType; import org.gwtbootstrap3.client.ui.constants.Pull; import org.gwtbootstrap3.client.ui.html.Text; /** * Represents a final step in registration process. Show info. * Contains methods caseXxx(...) e.g. caseVoInitGroupInit is called in usecase [ VO initial application -> Group application ] etc. * * @author Ondrej Velisek <[email protected]> */ public class SummaryStep implements Step { private FormView formView; private PerunRegistrarTranslation translation; private final String TARGET_EXISTING = "targetexisting"; private final String TARGET_NEW = "targetnew"; private final String TARGET_EXTENDED = "targetextended"; public SummaryStep(FormView formView) { this.formView = formView; this.translation = formView.getTranslation(); } @Override public void call(final PerunPrincipal pp, Summary summary, Events<Result> events) { Heading title = new Heading(HeadingSize.H2); ListGroup messages = new ListGroup(); if (summary.containsGroupInitResult()) { if (summary.containsVoInitResult()) { caseVoInitGroupInit(summary, title, messages); } else if (summary.containsVoExtResult()) { caseVoExtGroupInit(summary, title, messages); } else { caseGroupInit(summary, title, messages); } } else if (summary.containsGroupExtResult()) { if (summary.containsVoExtResult()) { caseVoExtGroupExt(summary, title, messages); } else { caseGroupExt(summary, title, messages); } } else { if (summary.containsVoInitResult()) { caseVoInit(summary, title, messages); } else if (summary.containsVoExtResult()) { caseVoExt(summary, title, messages); } else { // Steps should not be empty. } } } /** * Fill summary with result about VO initial application * * @param summary * @param title * @param messages */ private void caseVoInit(Summary summary, Heading title, ListGroup messages) { Result res = summary.getVoInitResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(res.getBean().getName())); } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfVo() || summary.alreadyAppliedToVo()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO extension application * * @param summary * @param title * @param messages */ private void caseVoExt(Summary summary, Heading title, ListGroup messages) { Result res = summary.getVoExtResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { title.add(new Text(" "+translation.extendTitleAutoApproval())); msg.setText(translation.extended(res.getBean().getName())); } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { // FIXME - solve this BLEEEH hack in better way. if (res.getException().getName().equals("DuplicateRegistrationAttemptException")) { res.getException().setName("DuplicateExtensionAttemptException"); } displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_EXTENDED); } else if (summary.alreadyAppliedForVoExtension() || summary.alreadyMemberOfVo()) { continueBtn = getContinueButton(TARGET_EXISTING); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about Group initial application * * @param summary * @param title * @param messages */ private void caseGroupInit(Summary summary, Heading title, ListGroup messages) { Result res = summary.getGroupInitResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { if (summary.alreadyAppliedToVo()) { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForVoAcceptation(((Group) res.getBean()).getShortName())); } else { title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(((Group) res.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedToGroup()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about Group extension application * * @param summary * @param title * @param messages */ private void caseGroupExt(Summary summary, Heading title, ListGroup messages) { Result res = summary.getGroupExtResult(); if (res.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (res.hasAutoApproval()) { if (summary.alreadyAppliedForVoExtension()) { title.add(new Text(" " + translation.extendTitle())); msg.setText(translation.waitForVoExtension(((Group) res.getBean()).getShortName())); } else { title.add(new Text(" " + translation.extendTitleAutoApproval())); msg.setText(translation.extended(((Group) res.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); } messages.add(msg); verifyMailMessage(summary, messages); } else if (res.getException() != null && "CantBeApprovedException".equals(res.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); verifyMailMessage(summary, messages); } else { // FIXME - solve this BLEEEH hack in better way. if (res.getException().getName().equals("DuplicateRegistrationAttemptException")) { res.getException().setName("DuplicateExtensionAttemptException"); } displayException(res.getException(), res.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedForGroupExtension()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (res.isOk() || res.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_EXTENDED); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO initial and Group initial application * * @param summary * @param title * @param messages */ private void caseVoInitGroupInit(Summary summary, Heading title, ListGroup messages) { Result resultVo = summary.getVoInitResult(); Result resultGroup = summary.getGroupInitResult(); // Show summary about initial application to VO if (resultVo.isOk()) { ListGroupItem msg = new ListGroupItem(); if (resultVo.hasAutoApproval()) { msg.setText(translation.registered(resultVo.getBean().getName())); } else { // Message from group application is sufficient in this case. } if (!msg.getText().isEmpty()) { messages.add(msg); } } else if (resultVo.getException() != null && "CantBeApprovedException".equals(resultVo.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. ListGroupItem msg = new ListGroupItem(); msg.setText(translation.waitForAcceptation()); messages.add(msg); } else { displayException(resultVo.getException(), resultVo.getBean()); } verifyMailMessage(summary, messages); // Show summary about application to group if (resultGroup.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (resultGroup.hasAutoApproval()) { if (resultVo.hasAutoApproval()) { title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(((Group) resultGroup.getBean()).getShortName())); } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForVoAcceptation(((Group) resultGroup.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); } else if (resultGroup.getException() != null && "CantBeApprovedException".equals(resultGroup.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO/Group manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); } else { displayException(resultGroup.getException(), resultGroup.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedToGroup()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if ((resultGroup.isOk() || resultGroup.getException().getName().equals("RegistrarException")) && (resultVo.isOk() || resultVo.getException().getName().equals("RegistrarException"))) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO extension and Group initial application * * @param summary * @param title * @param messages */ private void caseVoExtGroupInit(Summary summary, Heading title, ListGroup messages) { Result resultVo = summary.getVoExtResult(); Result resultGroup = summary.getGroupInitResult(); // Show summary about extension application to VO if (resultVo.isOk()) { ListGroupItem msg = new ListGroupItem(); if (resultVo.hasAutoApproval()) { msg.setText(translation.extended(resultVo.getBean().getName())); } else { // Message from group application is sufficient in this case. } if (!msg.getText().isEmpty()) { messages.add(msg); } } else if (resultVo.getException() != null && "CantBeApprovedException".equals(resultVo.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. ListGroupItem msg = new ListGroupItem(); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); } else { // FIXME - solve this BLEEEH hack in better way. if (resultVo.getException().getName().equals("DuplicateRegistrationAttemptException")) { resultVo.getException().setName("DuplicateExtensionAttemptException"); } displayException(resultVo.getException(), resultVo.getBean()); } // Show summary about application to group if (resultGroup.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (resultGroup.hasAutoApproval()) { if (resultVo.hasAutoApproval()) { // FIXME - tohle by se mělo vyhodnotit z předchozího stavu (není auto nebo byla chyba) title.add(new Text(" "+translation.initTitleAutoApproval())); msg.setText(translation.registered(((Group) resultGroup.getBean()).getShortName())); } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForVoExtension(((Group) resultGroup.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); } messages.add(msg); } else if (resultGroup.getException() != null && "CantBeApprovedException".equals(resultGroup.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO/Group manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.initTitle())); msg.setText(translation.waitForAcceptation()); messages.add(msg); } else { displayException(resultGroup.getException(), resultGroup.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedToGroup()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (resultGroup.isOk() || resultGroup.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_NEW); } displaySummary(title, messages, continueBtn); } /** * Fill summary with result about VO extension and Group extension application * * @param summary * @param title * @param messages */ private void caseVoExtGroupExt(Summary summary, Heading title, ListGroup messages) { Result resultVo = summary.getVoExtResult(); Result resultGroup = summary.getGroupInitResult(); // Show summary about extension application to VO if (resultVo.isOk()) { ListGroupItem msg = new ListGroupItem(); if (resultVo.hasAutoApproval()) { msg.setText(translation.extended(resultVo.getBean().getName())); } else { // Message from group application is sufficient in this case. } if (!msg.getText().isEmpty()) { messages.add(msg); } } else if (resultVo.getException() != null && "CantBeApprovedException".equals(resultVo.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO manager can manually handle it. ListGroupItem msg = new ListGroupItem(); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); } else { // FIXME - solve this BLEEEH hack in better way. if (resultVo.getException().getName().equals("DuplicateRegistrationAttemptException")) { resultVo.getException().setName("DuplicateExtensionAttemptException"); } displayException(resultVo.getException(), resultVo.getBean()); } // Show summary about application to group if (resultGroup.isOk()) { title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); if (resultGroup.hasAutoApproval()) { if (resultVo.hasAutoApproval()) { title.add(new Text(" "+translation.extendTitleAutoApproval())); msg.setText(translation.extended(((Group) resultGroup.getBean()).getShortName())); } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForVoExtension(((Group) resultGroup.getBean()).getShortName())); } } else { title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); } messages.add(msg); } else if (resultGroup.getException() != null && "CantBeApprovedException".equals(resultGroup.getException().getName())) { // FIXME - hack to ignore CantBeApprovedException since VO/Group manager can manually handle it. title.add(successIcon()); ListGroupItem msg = new ListGroupItem(); title.add(new Text(" "+translation.extendTitle())); msg.setText(translation.waitForExtAcceptation()); messages.add(msg); } else { // FIXME - solve this BLEEEH hack in better way. if (resultVo.getException().getName().equals("DuplicateRegistrationAttemptException")) { resultVo.getException().setName("DuplicateExtensionAttemptException"); } displayException(resultGroup.getException(), resultGroup.getBean()); } // Show continue button PerunButton continueBtn = null; if (summary.alreadyMemberOfGroup() || summary.alreadyAppliedForGroupExtension()) { continueBtn = getContinueButton(TARGET_EXISTING); } else if (resultGroup.isOk() || resultGroup.getException().getName().equals("RegistrarException")) { continueBtn = getContinueButton(TARGET_EXTENDED); } displaySummary(title, messages, continueBtn); } private Icon successIcon() { Icon success = new Icon(IconType.CHECK_CIRCLE); success.setColor("#5cb85c"); return success; } private void verifyMailMessage(Summary summary, ListGroup messages) { if (summary.mustRevalidateEmail() != null) { ListGroupItem verifyMail = new ListGroupItem(); verifyMail.add(new Icon(IconType.WARNING)); verifyMail.add(new Text(" " + translation.verifyMail(summary.mustRevalidateEmail()))); verifyMail.setType(ListGroupItemType.WARNING); messages.add(verifyMail); } } private void displaySummary(Heading title, ListGroup messages, PerunButton continueButton) { if (title != null || title.getWidgetCount() != 0 || !title.getText().isEmpty()) { formView.getForm().add(title); } if (messages != null || messages.getWidgetCount() != 0) { formView.getForm().add(messages); } if (continueButton != null) { formView.getForm().add(continueButton); } } private PerunButton getContinueButton(final String urlParameter) { if (Window.Location.getParameter(urlParameter) != null) { PerunButton continueButton = PerunButton.getButton(PerunButtonType.CONTINUE); continueButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { formView.getForm().clear(); Heading head = new Heading(HeadingSize.H4, translation.redirectingBackToService()); Icon spin = new Icon(IconType.SPINNER); spin.setSpin(true); spin.setSize(IconSize.LARGE); spin.setPull(Pull.LEFT); spin.setMarginTop(10); Column column = new Column(ColumnSize.MD_8, ColumnSize.LG_6, ColumnSize.SM_10, ColumnSize.XS_12); column.setOffset(ColumnOffset.MD_2,ColumnOffset.LG_3,ColumnOffset.SM_1,ColumnOffset.XS_0); column.add(spin); column.add(head); column.setMarginTop(30); formView.getForm().add(column); // WAIT 4 SEC BEFORE REDIRECT Timer timer = new Timer() { @Override public void run() { Window.Location.assign(Window.Location.getParameter(urlParameter)); } }; timer.schedule(7000); } }); return continueButton; } return null; } private void displayException(PerunException ex, GeneralObject bean) { formView.displayException(ex, bean); } @Override public Result getResult() { // Nobody should be after Summary step so nobody can call it. return null; } }
WUI: Fixed loading group ext data in SummaryStep
perun-wui-registrar/src/main/java/cz/metacentrum/perun/wui/registrar/pages/steps/SummaryStep.java
WUI: Fixed loading group ext data in SummaryStep
<ide><path>erun-wui-registrar/src/main/java/cz/metacentrum/perun/wui/registrar/pages/steps/SummaryStep.java <ide> private void caseVoExtGroupExt(Summary summary, Heading title, ListGroup messages) { <ide> <ide> Result resultVo = summary.getVoExtResult(); <del> Result resultGroup = summary.getGroupInitResult(); <add> Result resultGroup = summary.getGroupExtResult(); <ide> <ide> // Show summary about extension application to VO <ide> if (resultVo.isOk()) {
Java
apache-2.0
cc29fb3a92c3ac1fe8baff2806026e7ab9054ce7
0
archiecobbs/jsimpledb,archiecobbs/jsimpledb,permazen/permazen,permazen/permazen,permazen/permazen,archiecobbs/jsimpledb
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb.kv.array; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ForwardingFuture; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.dellroad.stuff.io.AtomicUpdateFileOutputStream; import org.jsimpledb.kv.AbstractKVStore; import org.jsimpledb.kv.CloseableKVStore; import org.jsimpledb.kv.KVPair; import org.jsimpledb.kv.KVStore; import org.jsimpledb.kv.KeyRange; import org.jsimpledb.kv.KeyRanges; import org.jsimpledb.kv.mvcc.AtomicKVStore; import org.jsimpledb.kv.mvcc.MutableView; import org.jsimpledb.kv.mvcc.Mutations; import org.jsimpledb.kv.mvcc.Writes; import org.jsimpledb.kv.util.CloseableForwardingKVStore; import org.jsimpledb.util.ByteUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link AtomicKVStore} based on {@link ArrayKVStore} with background compaction. * * <p> * This implementation is designed to maximize the speed of reads and minimize the amount of memory overhead per key/value pair. * It is optimized for relatively infrequent writes. * * <p> * Instances periodically compact outstanding changes into new arrays in a background thread. A compaction is scheduled whenever: * <ul> * <li>The size of uncompacted changes exceeds the {@linkplain #setCompactLowWater compaction space low-water mark}</li> * <li>The oldest uncompacted modification is older than the {@linkplain #setCompactMaxDelay compaction maximum delay}</li> * <li>{@link #scheduleCompaction} is invoked</li> * </ul> * * <p> * There is also a {@linkplain #setCompactHighWater high water mark for the size of uncompacted changes}: when this value * is exceeded, new write attempts will block until the current compaction cycle completes. This prevents the unbounded growth * of uncompacted changes when there is extremely high write volume. * * <p> * "Hot" backups created in parallel with normal operation are supported via {@link #hotCopy hotCopy()}. * Hard links are used (when available) to make this operation fast. * * <p> * The {@linkplain #setDirectory database directory} is a required configuration property. * * <p> * Key and value data must not exceed 2GB (each separately). * * <p> * Instances may be stopped and (re)started multiple times. */ public class AtomicArrayKVStore extends AbstractKVStore implements AtomicKVStore { /** * Default compaction maximum delay in seconds ({@value #DEFAULT_COMPACTION_MAX_DELAY} seconds). */ public static final int DEFAULT_COMPACTION_MAX_DELAY = 90; /** * Default compaction space low-water mark in bytes ({@value #DEFAULT_COMPACTION_LOW_WATER} bytes). */ public static final int DEFAULT_COMPACTION_LOW_WATER = 64 * 1024; /** * Default compaction space high-water mark in bytes ({@value #DEFAULT_COMPACTION_HIGH_WATER} bytes). */ public static final int DEFAULT_COMPACTION_HIGH_WATER = 1024 * 1024 * 1024; private static final int MIN_MMAP_LENGTH = 1024 * 1024; private static final String GENERATION_FILE_NAME = "gen"; private static final String LOCK_FILE_NAME = "lockfile"; private static final String INDX_FILE_NAME_BASE = "indx."; private static final String KEYS_FILE_NAME_BASE = "keys."; private static final String VALS_FILE_NAME_BASE = "vals."; private static final String MODS_FILE_NAME_BASE = "mods."; private final Logger log = LoggerFactory.getLogger(this.getClass()); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); private final ReentrantReadWriteLock.ReadLock readLock = this.lock.readLock(); private final ReentrantReadWriteLock.WriteLock writeLock = this.lock.writeLock(); private final Condition hotCopyFinishedCondition = this.writeLock.newCondition(); // Configuration state private File directory; private ScheduledExecutorService scheduledExecutorService; private int compactMaxDelay = DEFAULT_COMPACTION_MAX_DELAY; private int compactLowWater = DEFAULT_COMPACTION_LOW_WATER; private int compactHighWater = DEFAULT_COMPACTION_HIGH_WATER; // Runtime state private long generation; private boolean createdExecutorService; private File generationFile; private File lockFile; private FileChannel lockFileChannel; private File indxFile; private File keysFile; private File valsFile; private File modsFile; private FileOutputStream modsFileOutput; private FileChannel directoryChannel; private long modsFileLength; private long modsFileSyncPoint; private ByteBuffer indx; private ByteBuffer keys; private ByteBuffer vals; private ArrayKVStore kvstore; private MutableView mods; private Compaction compaction; private long firstModTimestamp; private int hotCopiesInProgress; // Accessors /** * Get the filesystem directory containing the database. If not set, this class functions as an im-memory store. * * @return database directory, or null for none */ public synchronized File getDirectory() { return this.directory; } /** * Configure the filesystem directory containing the database. If not set, this class functions as an im-memory store. * * @param directory database directory, or null for none * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setDirectory(File directory) { this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.directory = directory; } finally { this.writeLock.unlock(); } } /** * Configure the {@link ScheduledExecutorService} used to schedule background compaction. * * <p> * If not explicitly configured, a {@link ScheduledExecutorService} will be created automatically during {@link #start} * using {@link Executors#newSingleThreadScheduledExecutor} and shutdown by {@link #stop} (if explicitly configured here, * the configured {@link ScheduledExecutorService} will not be shutdown by {@link #stop}). * * @param scheduledExecutorService schduled executor service, or null to have one created automatically * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.scheduledExecutorService = scheduledExecutorService; } finally { this.writeLock.unlock(); } } /** * Configure the compaction time maximum delay. Compaction will be automatically triggered whenever there is any * uncompacted modification older than this. * * @param compactMaxDelay compaction time maximum delay in seconds * @throws IllegalArgumentException if {@code compactMaxDelay} is negative * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setCompactMaxDelay(int compactMaxDelay) { Preconditions.checkState(compactMaxDelay >= 0, "negative value"); this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.compactMaxDelay = compactMaxDelay; } finally { this.writeLock.unlock(); } } /** * Configure the compaction space low-water mark in bytes. * * @param compactLowWater compaction space low-water mark in bytes * @throws IllegalArgumentException if {@code compactLowWater} is negative * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setCompactLowWater(int compactLowWater) { Preconditions.checkState(compactLowWater >= 0, "negative value"); this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.compactLowWater = compactLowWater; } finally { this.writeLock.unlock(); } } /** * Configure the compaction space high-water mark in bytes. * * <p> * If the compaction space high water mark is set smaller than the the compaction space low water mark, * then it's treated as if it were the same as the compaction space low water mark. * * @param compactHighWater compaction space high-water mark in bytes * @throws IllegalArgumentException if {@code compactHighWater} is negative * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setCompactHighWater(int compactHighWater) { Preconditions.checkState(compactHighWater >= 0, "negative value"); this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.compactHighWater = compactHighWater; } finally { this.writeLock.unlock(); } } // Lifecycle @Override @PostConstruct public void start() { boolean success = false; this.writeLock.lock(); try { // Already started? if (this.kvstore != null) { success = true; return; } this.log.info("starting " + this); // Sanity check assert this.compaction == null; assert this.scheduledExecutorService == null; assert !this.createdExecutorService; assert this.generation == 0; assert this.generationFile == null; assert this.lockFile == null; assert this.lockFileChannel == null; assert this.indxFile == null; assert this.keysFile == null; assert this.valsFile == null; assert this.modsFile == null; assert this.modsFileOutput == null; assert this.directoryChannel == null; assert this.modsFileLength == 0; assert this.modsFileSyncPoint == 0; assert this.indx == null; assert this.keys == null; assert this.vals == null; assert this.kvstore == null; assert this.mods == null; assert this.firstModTimestamp == 0; // Check configuration Preconditions.checkState(this.directory != null, "no directory configured"); // Create executor if needed this.createdExecutorService = this.scheduledExecutorService == null; if (this.createdExecutorService) { this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable action) { final Thread thread = new Thread(action); thread.setName("Compactor for " + AtomicArrayKVStore.this); return thread; } }); } // Create directory if needed boolean initializeFiles = false; if (!this.directory.exists()) { if (!this.directory.mkdirs()) throw new ArrayKVException("failed to create directory `" + this.directory + "'"); } if (!this.directory.isDirectory()) throw new ArrayKVException("file `" + this.directory + "' is not a directory"); // Get directory channel we can fsync() this.directoryChannel = FileChannel.open(this.directory.toPath()); // Open and lock the lock file this.lockFile = new File(this.directory, LOCK_FILE_NAME); if (!this.lockFile.exists()) { this.lockFileChannel = FileChannel.open(this.lockFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); } else { this.lockFileChannel = FileChannel.open(this.lockFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } FileLock fileLock = null; try { fileLock = this.lockFileChannel.tryLock(); } catch (OverlappingFileLockException e) { // too bad } if (fileLock == null) throw new ArrayKVException("database is already locked by another process or thread"); // If no generation file exists, initialize generation zero this.generationFile = new File(this.directory, GENERATION_FILE_NAME); if (!this.generationFile.exists()) { // Verify no index, keys, or values file exists for (File file : this.directory.listFiles()) { final String name = file.getName(); if (name.startsWith(INDX_FILE_NAME_BASE) || name.startsWith(KEYS_FILE_NAME_BASE) || name.startsWith(VALS_FILE_NAME_BASE)) { throw new ArrayKVException("database file inconsistency: found " + name + " but not " + GENERATION_FILE_NAME + " in " + this.directory); } } // Create empty index, keys, and values files try ( final FileOutputStream indxOutput = new FileOutputStream(new File(this.directory, INDX_FILE_NAME_BASE + 0)); final FileOutputStream keysOutput = new FileOutputStream(new File(this.directory, KEYS_FILE_NAME_BASE + 0)); final FileOutputStream valsOutput = new FileOutputStream(new File(this.directory, VALS_FILE_NAME_BASE + 0)); final ArrayKVWriter arrayWriter = new ArrayKVWriter(indxOutput, keysOutput, valsOutput)) { arrayWriter.flush(); // avoid compiler warning valsOutput.getChannel().force(false); keysOutput.getChannel().force(false); indxOutput.getChannel().force(false); } this.directoryChannel.force(false); // Create generation file try (FileOutputStream output = new FileOutputStream(this.generationFile)) { new PrintStream(output, true).println(0); output.getChannel().force(false); } this.directoryChannel.force(false); } // Read current generation number try { this.generation = Long.parseLong( new String(Files.readAllBytes(this.generationFile.toPath()), StandardCharsets.UTF_8).trim(), 10); if (this.generation < 0) throw new ArrayKVException("read negative generation number from " + this.generationFile); } catch (Exception e) { throw new ArrayKVException("error reading generation file", e); } // Set corresponding filenames this.indxFile = new File(this.directory, INDX_FILE_NAME_BASE + this.generation); this.keysFile = new File(this.directory, KEYS_FILE_NAME_BASE + this.generation); this.valsFile = new File(this.directory, VALS_FILE_NAME_BASE + this.generation); this.modsFile = new File(this.directory, MODS_FILE_NAME_BASE + this.generation); // Scan directory for unexpected files final List<File> expectedFiles = Arrays.asList(this.lockFile, this.generationFile, this.indxFile, this.keysFile, this.valsFile, this.modsFile); for (File file : this.directory.listFiles()) { if (!expectedFiles.contains(file)) this.log.warn("ignoring unexpected file " + file.getName() + " in my database directory"); } // Create buffers that wrap the index, keys, and values files try (FileInputStream input = new FileInputStream(this.indxFile)) { this.indx = AtomicArrayKVStore.getBuffer(this.indxFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(this.keysFile)) { this.keys = AtomicArrayKVStore.getBuffer(this.keysFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(this.valsFile)) { this.vals = AtomicArrayKVStore.getBuffer(this.valsFile, input.getChannel()); } // Set up underlying k/v store and uncompacted modifications this.kvstore = new ArrayKVStore(this.indx, this.keys, this.vals); this.mods = new MutableView(this.kvstore, null, new Writes()); // Setup modifications file this.modsFileOutput = new FileOutputStream(this.modsFile, true); this.modsFileLength = this.modsFileOutput.getChannel().size(); this.modsFileSyncPoint = this.modsFileLength; // Read and apply pre-existing uncompacted modifications from modifications file if (this.modsFileLength > 0) { this.log.info("reading " + this.modsFileLength + " bytes of uncompacted modifications from " + this.modsFile); try (FileInputStream input = new FileInputStream(this.modsFile)) { while (input.available() > 0) { final Writes writes; try { writes = Writes.deserialize(input); } catch (Exception e) { break; // probably a partial write } writes.applyTo(this.mods); } } this.firstModTimestamp = System.nanoTime() | 1; // avoid zero value which is special } // Schedule compaction if necessary this.scheduleCompactionIfNecessary(); // Done success = true; } catch (IOException e) { throw new ArrayKVException("startup failed", e); } finally { try { if (!success) this.cleanup(); } finally { this.writeLock.unlock(); } } } @Override @PreDestroy public void stop() { this.writeLock.lock(); try { // Check state if (this.kvstore == null) return; this.log.info("stopping " + this); // Cleanup this.cleanup(); } finally { this.writeLock.unlock(); } } private void cleanup() { // Should hold write lock now assert this.lock.isWriteLockedByCurrentThread(); // Cancel compaction if possible, otherwise wait for it to complete if (this.compaction != null && !this.compaction.cancel()) { // Wait for compaction to complete this.log.debug("waiting for in-progress compaction to complete before shutdown"); this.compaction.waitForCompletion(); this.log.debug("compaction completed, proceeding with shutdown"); // Check whether another thread invoked stop() while we were asleep if (this.kvstore == null) return; } // Wait for any in-progress hot copies to complete if (this.hotCopiesInProgress > 0) { this.log.debug("waiting for " + this.hotCopiesInProgress + " hot copies to complete before shutdown"); boolean interrupted = false; do { // Wait for hot copies to complete try { this.hotCopyFinishedCondition.await(); } catch (InterruptedException e) { this.log.warn("thread interrupted while waiting for " + this.hotCopiesInProgress + " hot copies to complete (ignoring)", e); interrupted = true; } // Check whether another thread invoked stop() while we were asleep if (this.kvstore == null) return; } while (this.hotCopiesInProgress > 0); if (interrupted) Thread.currentThread().interrupt(); this.log.debug("hot copies completed, proceeding with shutdown"); } // Shut down executor - only if we created it if (this.createdExecutorService) { this.scheduledExecutorService.shutdownNow(); this.scheduledExecutorService = null; this.createdExecutorService = false; } // Close files for (Closeable closeable : new Closeable[] { this.modsFileOutput, this.directoryChannel, this.lockFileChannel }) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // ignore } } } // Reset state this.generation = 0; this.generationFile = null; this.lockFile = null; this.lockFileChannel = null; this.indxFile = null; this.keysFile = null; this.valsFile = null; this.modsFile = null; this.modsFileOutput = null; this.directoryChannel = null; this.modsFileLength = 0; this.modsFileSyncPoint = 0; this.indx = null; this.keys = null; this.vals = null; this.kvstore = null; this.mods = null; this.firstModTimestamp = 0; } // KVStore @Override public byte[] get(byte[] key) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.get(key); } finally { this.readLock.unlock(); } } @Override public KVPair getAtLeast(byte[] minKey) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.getAtLeast(minKey); } finally { this.readLock.unlock(); } } @Override public KVPair getAtMost(byte[] maxKey) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.getAtMost(maxKey); } finally { this.readLock.unlock(); } } @Override public Iterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.getRange(minKey, maxKey, reverse); } finally { this.readLock.unlock(); } } @Override public void put(byte[] key, byte[] value) { final Writes writes = new Writes(); writes.getPuts().put(key, value); this.mutate(writes, false); } @Override public void remove(byte[] key) { final Writes writes = new Writes(); writes.setRemoves(new KeyRanges(key)); this.mutate(writes, false); } @Override public void removeRange(byte[] minKey, byte[] maxKey) { final Writes writes = new Writes(); writes.setRemoves(new KeyRanges(minKey != null ? minKey : ByteUtil.EMPTY, maxKey)); this.mutate(writes, false); } @Override public void adjustCounter(byte[] key, long amount) { final Writes writes = new Writes(); writes.getAdjusts().put(key, amount); this.mutate(writes, false); } @Override public byte[] encodeCounter(long value) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.encodeCounter(value); } finally { this.readLock.unlock(); } } @Override public long decodeCounter(byte[] bytes) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.decodeCounter(bytes); } finally { this.readLock.unlock(); } } // AtomicKVStore @Override public CloseableKVStore snapshot() { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); // Get outstanding modifications; if we are compacting, there are two sets of modifications final Writes writes1; if (this.mods.getKVStore() instanceof MutableView) { final MutableView oldMods = (MutableView)this.mods.getKVStore(); assert oldMods.getKVStore() == this.kvstore; writes1 = oldMods.getWrites(); } else writes1 = null; final Writes writes2 = this.mods.getWrites(); // Clone (non-empty) writes to construct snapshot KVStore snapshot = this.kvstore; if (writes1 != null && !writes1.isEmpty()) snapshot = new MutableView(snapshot, null, writes1.clone()); if (writes2 != null && !writes2.isEmpty()) snapshot = new MutableView(snapshot, null, writes2.clone()); // Done return new CloseableForwardingKVStore(snapshot); } finally { this.readLock.unlock(); } } @Override public void mutate(Mutations mutations, final boolean sync) { Preconditions.checkArgument(mutations != null, "null mutations"); this.writeLock.lock(); try { // Verify we are started Preconditions.checkState(this.kvstore != null, "not started"); // Block until compaction completes if size of outstanding modifications exceeds high water mark while (this.compaction != null && this.modsFileLength > this.compactHighWater) { // If scheduled compaction is in the future, reschedule to be immediate if (this.compaction.getDelay() > 0) this.scheduleCompaction(0); // Wait for it to complete this.log.debug("reached compaction high-water mark; waiting for in-progress compaction to complete" + " before applying mutation(s)"); this.compaction.waitForCompletion(); this.log.debug("compaction completed, proceeding with application of mutation(s)"); // Verify we are still open after giving up lock if (this.kvstore == null) throw new ArrayKVException("k/v store was closed while waiting for compaction to complete"); } // Get mutations as a Writes object final Writes writes; if (mutations instanceof Writes) writes = (Writes)mutations; else { writes = new Writes(); writes.setRemoves(new KeyRanges(mutations.getRemoveRanges())); for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) writes.getPuts().put(entry.getKey(), entry.getValue()); for (Map.Entry<byte[], Long> entry : mutations.getAdjustPairs()) writes.getAdjusts().put(entry.getKey(), entry.getValue()); } // Check for the trivial case where there are zero modifications if (writes.isEmpty()) return; // Append mutations to uncompacted mods file try { writes.serialize(this.modsFileOutput); this.modsFileOutput.flush(); } catch (IOException e) { try { this.modsFileOutput.getChannel().truncate(this.modsFileLength); // undo append } catch (IOException e2) { this.log.error("error truncating log file (ignoring)", e2); } throw new ArrayKVException("error appending to " + this.modsFile, e); } final long newModsFileLength; try { newModsFileLength = this.modsFileOutput.getChannel().size(); } catch (IOException e) { throw new ArrayKVException("error getting length of " + this.modsFile, e); } if (this.log.isDebugEnabled()) { this.log.debug("appended " + (newModsFileLength - this.modsFileLength) + " bytes to " + this.modsFile + " (new length " + newModsFileLength + ")"); } this.modsFileLength = newModsFileLength; // Apply removes for (KeyRange range : mutations.getRemoveRanges()) { final byte[] min = range.getMin(); final byte[] max = range.getMax(); this.mods.removeRange(min, max); } // Apply puts for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) { final byte[] key = entry.getKey(); final byte[] val = entry.getValue(); this.mods.put(key, val); } // Apply counter adjustments for (Map.Entry<byte[], Long> entry : mutations.getAdjustPairs()) { final byte[] key = entry.getKey(); final long adjust = entry.getValue(); this.mods.adjustCounter(key, adjust); } // Set first uncompacted modification timestamp, if not already set if (this.firstModTimestamp == 0) this.firstModTimestamp = System.nanoTime() | 1; // avoid zero value which is special // Schedule compaction if necessary this.scheduleCompactionIfNecessary(); // If we're not syncing, we're done if (!sync) return; // Update sync point, so compaction knows to also sync these mods when it copies them this.modsFileSyncPoint = this.modsFileLength; // Downgrade lock this.readLock.lock(); } finally { this.writeLock.unlock(); } // Sync the mods file while holding only the read lock try { this.modsFileOutput.getChannel().force(false); } catch (IOException e) { this.log.error("error syncing log file (ignoring)", e); } finally { this.readLock.unlock(); } } // Hot Copy /** * Create a filesystem atomic snapshot, or "hot" copy", of this instance in the specified destination directory. * The copy will be up-to-date as of the time this method is invoked. * * <p> * The {@code target} directory will be created if it does not exist; otherwise, it must be empty. * All files except the uncompacted modifications file are copied into {@code target} * in constant time using {@linkplain Files#createLink hard links} if possible. * * <p> * The hot copy operation can proceed in parallel with normal database activity, with the exception * that the compaction operation cannot start while there are concurrent hot copies in progress. * * <p> * Therefore, for best performance, consider {@linkplain #scheduleCompaction performing a compaction} * immediately prior to this operation. * * <p> * Note: when this method returns, all copied files, and the {@code target} directory, have been {@code fsync()}'d * and therefore may be considered durable in case of a system crash. * * @param target destination directory * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code target} exists and is not a directory or is non-empty * @throws IllegalArgumentException if {@code target} is null */ public void hotCopy(File target) throws IOException { // Sanity check Preconditions.checkArgument(target != null, "null target"); final Path dir = target.toPath(); // Create/verify directory if (!Files.exists(dir)) Files.createDirectories(dir); if (!Files.isDirectory(dir)) throw new IllegalArgumentException("target `" + dir + "' is not a directory"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path path : stream) throw new IllegalArgumentException("target `" + dir + "' is not empty"); } // Increment hot copy counter - this prevents compaction from removing files while we're copying them this.writeLock.lock(); try { // Sanity check Preconditions.checkState(this.kvstore != null, "not started"); // Bump counter this.hotCopiesInProgress++; } finally { this.writeLock.unlock(); } try { // Logit this.log.debug("started hot copy into " + target); // Copy index, keys, and values files using hard links (if possible) as these files are read-only final ArrayList<File> regularCopyFiles = new ArrayList<>(5); for (File file : new File[] { this.indxFile, this.keysFile, this.valsFile }) { try { Files.createLink(dir.resolve(file.getName()), file.toPath()); } catch (IOException | UnsupportedOperationException e) { regularCopyFiles.add(file); // fall back to normal copy } } // Copy remaining files without using hard links regularCopyFiles.add(this.modsFile); // it's ok if we copy a partial write regularCopyFiles.add(this.generationFile); // copy this one last for (File file : regularCopyFiles) { try (final FileOutputStream fileCopy = new FileOutputStream(new File(target, file.getName()))) { Files.copy(file.toPath(), fileCopy); fileCopy.getChannel().force(false); } } // Sync directory try (FileChannel dirChannel = FileChannel.open(dir)) { dirChannel.force(false); } } finally { this.writeLock.lock(); try { // Sanity check assert this.hotCopiesInProgress > 0; assert this.kvstore != null; // Logit this.log.debug("completed hot copy into " + target); // Decrement counter this.hotCopiesInProgress--; // Wakeup waiters this.hotCopyFinishedCondition.signalAll(); } finally { this.writeLock.unlock(); } } } // Compaction /** * Schedule a new compaction cycle, unless there is one already scheduled or running, or there are no * outstanding uncompacted modifications. * * @return a future for the completion of the next compaction cycle, or null if there are no uncompacted modifications * @throws IllegalStateException if this instance is not started */ public Future<?> scheduleCompaction() { this.writeLock.lock(); try { // Sanity check Preconditions.checkState(this.kvstore != null, "not started"); // Is there anything to compact? if (this.modsFileLength == 0) return null; // Schedule an immediate compaction return this.scheduleCompaction(0); } finally { this.writeLock.unlock(); } } private Future<?> scheduleCompaction(long millis) { // Should hold write lock now assert this.lock.isWriteLockedByCurrentThread(); assert this.modsFileLength > 0; // (Re)schedule compaction if necessary if (this.compaction == null || (this.compaction.getDelay() > millis && this.compaction.cancel())) { assert this.compaction == null; this.compaction = new Compaction(millis); } // Done return new ForwardingFuture.SimpleForwardingFuture<Void>(this.compaction.getFuture()) { @Override public boolean cancel(boolean mayInterrupt) { // disallow this operation return false; } }; } private void scheduleCompactionIfNecessary() { // Should hold write lock now assert this.lock.isWriteLockedByCurrentThread(); // Is there anything to do? if (this.modsFileLength == 0) return; // Check space low-water mark if (this.modsFileLength > this.compactLowWater) { this.scheduleCompaction(0); return; } // Check maximum compaction delay if (this.firstModTimestamp != 0) { final long firstModAgeMillis = (System.nanoTime() - this.firstModTimestamp) / 1000000L; // convert ns -> ms this.scheduleCompaction(firstModAgeMillis); return; } } @SuppressWarnings("fallthrough") private void compact(final Compaction compaction) throws IOException { // Sanity check assert compaction != null; // Handle cancel() race condition this.writeLock.lock(); try { // Were we canceled? if (compaction != this.compaction) return; // Set now running - this prevents future cancel()'s assert !compaction.isStarted(); assert !compaction.isCompleted(); compaction.setStarted(); } finally { this.writeLock.unlock(); } // Start compaction final long compactionStartTime; try { // Snapshot (and wrap) pending modifications, and mark log file position final Writes writesToCompact; final long previousModsFileLength; final long previousModsFileSyncPoint; this.writeLock.lock(); try { // Sanity checks assert this.kvstore != null; assert this.modsFileLength > 0; // Mark start time and get uncompacted modifications compactionStartTime = System.nanoTime(); writesToCompact = this.mods.getWrites(); // It's possible the uncompacted modifications are a no-op; if so, no compaction is necessary if (writesToCompact.isEmpty()) { // Wait for any in-progress hot copies to complete while (this.hotCopiesInProgress > 0) { this.log.debug("waiting for " + this.hotCopiesInProgress + " hot copies to complete before completing (trivial) compaction"); try { this.hotCopyFinishedCondition.await(); } catch (InterruptedException e) { throw new ArrayKVException("thread was interrupted while waiting for " + this.hotCopiesInProgress + " hot copies to complete", e); } this.log.debug("hot copies completed, proceeding with completion of (trivial) compaction"); } assert this.kvstore != null; assert this.modsFileLength > 0; // Discard outstanding mods this.modsFileOutput.getChannel().truncate(0); this.modsFileLength = 0; this.modsFileSyncPoint = 0; this.modsFileOutput.getChannel().force(false); return; } // Allow new modifications to be added by other threads while we are compacting the old modifications this.mods = new MutableView(this.mods, null, new Writes()); previousModsFileLength = this.modsFileLength; previousModsFileSyncPoint = this.modsFileSyncPoint; } finally { this.writeLock.unlock(); } if (this.log.isDebugEnabled()) { this.log.debug("starting compaction for generation " + this.generation + " -> " + (this.generation + 1) + " with mods file length " + previousModsFileLength); } // Create the next generation final long newGeneration = this.generation + 1; final File newIndxFile = new File(this.directory, INDX_FILE_NAME_BASE + newGeneration); final File newKeysFile = new File(this.directory, KEYS_FILE_NAME_BASE + newGeneration); final File newValsFile = new File(this.directory, VALS_FILE_NAME_BASE + newGeneration); final File newModsFile = new File(this.directory, MODS_FILE_NAME_BASE + newGeneration); ByteBuffer newIndx = null; ByteBuffer newKeys = null; ByteBuffer newVals = null; FileOutputStream newModsFileOutput = null; boolean success = false; try { // Merge existing compacted key/value data with uncompacted modifications try ( final FileOutputStream indxOutput = new FileOutputStream(newIndxFile); final FileOutputStream keysOutput = new FileOutputStream(newKeysFile); final FileOutputStream valsOutput = new FileOutputStream(newValsFile); final ArrayKVWriter arrayWriter = new ArrayKVWriter(indxOutput, keysOutput, valsOutput)) { // Write out merged key/value pairs arrayWriter.writeMerged(this.kvstore, this.kvstore.getRange(null, null, false), writesToCompact); // Sync file data arrayWriter.flush(); valsOutput.getChannel().force(false); keysOutput.getChannel().force(false); indxOutput.getChannel().force(false); } assert newIndxFile.exists(); assert newKeysFile.exists(); assert newValsFile.exists(); // Create byte buffers from new files try (FileInputStream input = new FileInputStream(newIndxFile)) { newIndx = AtomicArrayKVStore.getBuffer(newIndxFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(newKeysFile)) { newKeys = AtomicArrayKVStore.getBuffer(newKeysFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(newValsFile)) { newVals = AtomicArrayKVStore.getBuffer(newValsFile, input.getChannel()); } // Create new, empty mods file newModsFile.delete(); // shouldn't exist, but just in case... newModsFileOutput = new FileOutputStream(newModsFile, true); assert newModsFile.exists(); // Sync directory this.directoryChannel.force(false); // We're done creating files success = true; } finally { // Finish up this.writeLock.lock(); try { if (success) { // Initialize for wrap-up success = false; // Size up additional mods final long additionalModsLength = this.modsFileLength - previousModsFileLength; // Logit if (this.log.isDebugEnabled()) { final float duration = (System.nanoTime() - compactionStartTime) / 1000000000f; this.log.debug("compaction for generation " + this.generation + " -> " + (this.generation + 1) + " finishing up with " + additionalModsLength + " bytes of new modifications after " + String.format("%.4f", duration) + " seconds"); } // Wait for any in-progress hot copies to complete while (this.hotCopiesInProgress > 0) { this.log.debug("waiting for " + this.hotCopiesInProgress + " hot copies to complete before completing compaction"); try { this.hotCopyFinishedCondition.await(); } catch (InterruptedException e) { throw new ArrayKVException("thread was interrupted while waiting for " + this.hotCopiesInProgress + " hot copies to complete", e); } assert this.compaction == compaction; assert this.kvstore != null; this.log.debug("hot copies completed, proceeding with completion of compaction"); } // Apply any changes that were made while we were unlocked and writing files long newModsFileLength = 0; long newModsFileSyncPoint = 0; if (additionalModsLength > 0) { try ( final FileChannel modsFileChannel = FileChannel.open(this.modsFile.toPath()); final FileChannel newModsFileChannel = FileChannel.open(newModsFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.APPEND)) { // Append new data in old mods file to new mods file while (newModsFileLength < additionalModsLength) { final long transferred = modsFileChannel.transferTo( previousModsFileLength + newModsFileLength, additionalModsLength - newModsFileLength, newModsFileChannel); assert transferred > 0; newModsFileLength += transferred; } // If any of that new data was fsync()'d, we must fsync() the copy of it in the new mods file if (this.modsFileSyncPoint > previousModsFileSyncPoint) { newModsFileChannel.force(false); newModsFileSyncPoint = newModsFileLength; } } } // Atomically update new generation file contents final AtomicUpdateFileOutputStream genOutput = new AtomicUpdateFileOutputStream(this.generationFile); boolean genSuccess = false; try { new PrintStream(genOutput, true).println(newGeneration); genOutput.getChannel().force(false); genSuccess = true; } finally { if (genSuccess) genOutput.close(); else genOutput.cancel(); } // Declare success success = true; // Remember old info so we can clean it up final File oldIndxFile = this.indxFile; final File oldKeysFile = this.keysFile; final File oldValsFile = this.valsFile; final File oldModsFile = this.modsFile; final FileOutputStream oldModsFileOutput = this.modsFileOutput; // Change to the new generation this.generation = newGeneration; this.indx = newIndx; this.keys = newKeys; this.vals = newVals; this.indxFile = newIndxFile; this.keysFile = newKeysFile; this.valsFile = newValsFile; this.modsFile = newModsFile; this.modsFileOutput = newModsFileOutput; this.modsFileLength = newModsFileLength; this.modsFileSyncPoint = newModsFileSyncPoint; this.kvstore = new ArrayKVStore(this.indx, this.keys, this.vals); this.mods = new MutableView(this.kvstore, null, this.mods.getWrites()); // Sync directory prior to deleting files try { this.directoryChannel.force(false); } catch (IOException e) { this.log.error("error syncing directory " + this.directory + " (ignoring)", e); } // Delete old files oldIndxFile.delete(); oldKeysFile.delete(); oldValsFile.delete(); oldModsFile.delete(); // Close old mods file output stream try { oldModsFileOutput.close(); } catch (IOException e) { // ignore } } } finally { try { // Logit if (this.log.isDebugEnabled()) { final float duration = (System.nanoTime() - compactionStartTime) / 1000000000f; this.log.debug("compaction for generation " + (newGeneration - 1) + " -> " + newGeneration + (success ? " succeeded" : " failed") + " in " + String.format("%.4f", duration) + " seconds"); } // Cleanup/undo on failure if (!success) { // Put back the old uncompacted modifications, and merge any new mods into them final Writes writesDuringCompaction = this.mods.getWrites(); this.mods = new MutableView(this.kvstore, null, writesToCompact); writesDuringCompaction.applyTo(this.mods); // Delete the files we were creating newIndxFile.delete(); newKeysFile.delete(); newValsFile.delete(); if (newModsFileOutput != null) { newModsFile.delete(); try { newModsFileOutput.close(); } catch (Exception e) { // ignore } } } } finally { this.writeLock.unlock(); } } } } finally { // Update state this.writeLock.lock(); try { assert this.kvstore != null; assert this.compaction == compaction; compaction.setCompleted(); this.compaction = null; } finally { this.writeLock.unlock(); } } } // Compaction private class Compaction implements Runnable { private final Condition completedCondition = AtomicArrayKVStore.this.writeLock.newCondition(); private final ScheduledFuture<Void> future; private boolean started; private boolean completed; @SuppressWarnings("unchecked") Compaction(long millis) { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); Preconditions.checkState(AtomicArrayKVStore.this.compaction == null, "compaction already exists"); // Schedule this.future = (ScheduledFuture<Void>)AtomicArrayKVStore.this.scheduledExecutorService.schedule(this, millis, TimeUnit.MILLISECONDS); } /** * Cancel this compaction. * * @return true if canceled, false if already started */ public boolean cancel() { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); Preconditions.checkState(this.future != null, "not scheduled"); // Already canceled? if (AtomicArrayKVStore.this.compaction != this) return false; // Already started? if (this.started) return false; // Attempt to cancel scheduled task assert this.future != null; this.future.cancel(false); // Make this task do nothing even if it runs anyway AtomicArrayKVStore.this.compaction = null; return true; } /** * Get delay until start. * * @return delay in milliseconds */ public long getDelay() { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); Preconditions.checkState(this.future != null, "not scheduled"); // Get delay return Math.max(0, this.future.getDelay(TimeUnit.MILLISECONDS)); } /** * Wait for this compaction to complete. */ public void waitForCompletion() { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); // Wait for completion boolean interrupted = false; while (!this.completed) { try { this.completedCondition.await(); } catch (InterruptedException e) { AtomicArrayKVStore.this.log.warn( "thread was interrupted while waiting for compaction to complete (ignoring)", e); interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); } public Future<Void> getFuture() { return this.future; } public boolean isStarted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); return this.started; } public void setStarted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); this.started = true; } public boolean isCompleted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); return this.completed; } public void setCompleted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); this.completed = true; this.completedCondition.signalAll(); } @Override public void run() { assert !AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); try { AtomicArrayKVStore.this.compact(this); } catch (Throwable t) { AtomicArrayKVStore.this.log.error("error during compaction", t); } } } // Object /** * Finalize this instance. Invokes {@link #stop} to close any unclosed iterators. */ @Override protected void finalize() throws Throwable { try { if (this.kvstore != null) this.log.warn(this + " leaked without invoking stop()"); this.stop(); } finally { super.finalize(); } } @Override public String toString() { return this.getClass().getSimpleName() + "[" + this.directory + "]"; } private static ByteBuffer getBuffer(File file, FileChannel fileChannel) throws IOException { final long length = fileChannel.size(); return length >= MIN_MMAP_LENGTH ? fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, length) : ByteBuffer.wrap(Files.readAllBytes(file.toPath())).asReadOnlyBuffer(); } }
src/java/org/jsimpledb/kv/array/AtomicArrayKVStore.java
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb.kv.array; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ForwardingFuture; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.dellroad.stuff.io.AtomicUpdateFileOutputStream; import org.jsimpledb.kv.AbstractKVStore; import org.jsimpledb.kv.CloseableKVStore; import org.jsimpledb.kv.KVPair; import org.jsimpledb.kv.KVStore; import org.jsimpledb.kv.KeyRange; import org.jsimpledb.kv.KeyRanges; import org.jsimpledb.kv.mvcc.AtomicKVStore; import org.jsimpledb.kv.mvcc.MutableView; import org.jsimpledb.kv.mvcc.Mutations; import org.jsimpledb.kv.mvcc.Writes; import org.jsimpledb.kv.util.CloseableForwardingKVStore; import org.jsimpledb.util.ByteUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link AtomicKVStore} based on {@link ArrayKVStore} with background compaction. * * <p> * This implementation is designed to maximize the speed of reads and minimize the amount of memory overhead per key/value pair. * It is optimized for relatively infrequent writes. * * <p> * Instances periodically compact outstanding changes into new arrays in a background thread. A compaction is scheduled whenever: * <ul> * <li>The size of uncompacted changes exceeds the {@linkplain #setCompactLowWater compaction space low-water mark}</li> * <li>The oldest uncompacted modification is older than the {@linkplain #setCompactMaxDelay compaction maximum delay}</li> * <li>{@link #scheduleCompaction} is invoked</li> * </ul> * * <p> * There is also a {@linkplain #setCompactHighWater high water mark for the size of uncompacted changes}: when this value * is exceeded, new write attempts will block until the current compaction cycle completes. This prevents the unbounded growth * of uncompacted changes when there is extremely high write volume. * * <p> * "Hot" backups created in parallel with normal operation are supported via {@link #hotCopy hotCopy()}. * Hard links are used (when available) to make this operation fast. * * <p> * The {@linkplain #setDirectory database directory} is a required configuration property. * * <p> * Key and value data must not exceed 2GB (each separately). * * <p> * Instances may be stopped and (re)started multiple times. */ public class AtomicArrayKVStore extends AbstractKVStore implements AtomicKVStore { /** * Default compaction maximum delay in seconds ({@value #DEFAULT_COMPACTION_MAX_DELAY} seconds). */ public static final int DEFAULT_COMPACTION_MAX_DELAY = 90; /** * Default compaction space low-water mark in bytes ({@value #DEFAULT_COMPACTION_LOW_WATER} bytes). */ public static final int DEFAULT_COMPACTION_LOW_WATER = 64 * 1024; /** * Default compaction space high-water mark in bytes ({@value #DEFAULT_COMPACTION_HIGH_WATER} bytes). */ public static final int DEFAULT_COMPACTION_HIGH_WATER = 1024 * 1024 * 1024; private static final int MIN_MMAP_LENGTH = 1024 * 1024; private static final String GENERATION_FILE_NAME = "gen"; private static final String LOCK_FILE_NAME = "lockfile"; private static final String INDX_FILE_NAME_BASE = "indx."; private static final String KEYS_FILE_NAME_BASE = "keys."; private static final String VALS_FILE_NAME_BASE = "vals."; private static final String MODS_FILE_NAME_BASE = "mods."; private final Logger log = LoggerFactory.getLogger(this.getClass()); private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); private final ReentrantReadWriteLock.ReadLock readLock = this.lock.readLock(); private final ReentrantReadWriteLock.WriteLock writeLock = this.lock.writeLock(); private final Condition hotCopyFinishedCondition = this.writeLock.newCondition(); // Configuration state private File directory; private ScheduledExecutorService scheduledExecutorService; private int compactMaxDelay = DEFAULT_COMPACTION_MAX_DELAY; private int compactLowWater = DEFAULT_COMPACTION_LOW_WATER; private int compactHighWater = DEFAULT_COMPACTION_HIGH_WATER; // Runtime state private long generation; private boolean createdExecutorService; private File generationFile; private File lockFile; private FileChannel lockFileChannel; private File indxFile; private File keysFile; private File valsFile; private File modsFile; private FileOutputStream modsFileOutput; private FileChannel directoryChannel; private long modsFileLength; private long modsFileSyncPoint; private ByteBuffer indx; private ByteBuffer keys; private ByteBuffer vals; private ArrayKVStore kvstore; private MutableView mods; private Compaction compaction; private long firstModTimestamp; private int hotCopiesInProgress; // Accessors /** * Get the filesystem directory containing the database. If not set, this class functions as an im-memory store. * * @return database directory, or null for none */ public synchronized File getDirectory() { return this.directory; } /** * Configure the filesystem directory containing the database. If not set, this class functions as an im-memory store. * * @param directory database directory, or null for none * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setDirectory(File directory) { this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.directory = directory; } finally { this.writeLock.unlock(); } } /** * Configure the {@link ScheduledExecutorService} used to schedule background compaction. * * <p> * If not explicitly configured, a {@link ScheduledExecutorService} will be created automatically during {@link #start} * using {@link Executors#newSingleThreadScheduledExecutor} and shutdown by {@link #stop} (if explicitly configured here, * the configured {@link ScheduledExecutorService} will not be shutdown by {@link #stop}). * * @param scheduledExecutorService schduled executor service, or null to have one created automatically * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.scheduledExecutorService = scheduledExecutorService; } finally { this.writeLock.unlock(); } } /** * Configure the compaction time maximum delay. Compaction will be automatically triggered whenever there is any * uncompacted modification older than this. * * @param compactMaxDelay compaction time maximum delay in seconds * @throws IllegalArgumentException if {@code compactMaxDelay} is negative * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setCompactMaxDelay(int compactMaxDelay) { Preconditions.checkState(compactMaxDelay >= 0, "negative value"); this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.compactMaxDelay = compactMaxDelay; } finally { this.writeLock.unlock(); } } /** * Configure the compaction space low-water mark in bytes. * * @param compactLowWater compaction space low-water mark in bytes * @throws IllegalArgumentException if {@code compactLowWater} is negative * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setCompactLowWater(int compactLowWater) { Preconditions.checkState(compactLowWater >= 0, "negative value"); this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.compactLowWater = compactLowWater; } finally { this.writeLock.unlock(); } } /** * Configure the compaction space high-water mark in bytes. * * <p> * If the compaction space high water mark is set smaller than the the compaction space low water mark, * then it's treated as if it were the same as the compaction space low water mark. * * @param compactHighWater compaction space high-water mark in bytes * @throws IllegalArgumentException if {@code compactHighWater} is negative * @throws IllegalStateException if this instance is already {@link #start}ed */ public void setCompactHighWater(int compactHighWater) { Preconditions.checkState(compactHighWater >= 0, "negative value"); this.writeLock.lock(); try { Preconditions.checkState(this.kvstore == null, "already started"); this.compactHighWater = compactHighWater; } finally { this.writeLock.unlock(); } } // Lifecycle @Override @PostConstruct public void start() { boolean success = false; this.writeLock.lock(); try { // Already started? if (this.kvstore != null) { success = true; return; } this.log.info("starting " + this); // Sanity check assert this.compaction == null; assert this.scheduledExecutorService == null; assert !this.createdExecutorService; assert this.generation == 0; assert this.generationFile == null; assert this.lockFile == null; assert this.lockFileChannel == null; assert this.indxFile == null; assert this.keysFile == null; assert this.valsFile == null; assert this.modsFile == null; assert this.modsFileOutput == null; assert this.directoryChannel == null; assert this.modsFileLength == 0; assert this.modsFileSyncPoint == 0; assert this.indx == null; assert this.keys == null; assert this.vals == null; assert this.kvstore == null; assert this.mods == null; assert this.firstModTimestamp == 0; // Check configuration Preconditions.checkState(this.directory != null, "no directory configured"); // Create executor if needed this.createdExecutorService = this.scheduledExecutorService == null; if (this.createdExecutorService) { this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable action) { final Thread thread = new Thread(action); thread.setName("Compactor for " + AtomicArrayKVStore.this); return thread; } }); } // Create directory if needed boolean initializeFiles = false; if (!this.directory.exists()) { if (!this.directory.mkdirs()) throw new ArrayKVException("failed to create directory `" + this.directory + "'"); } if (!this.directory.isDirectory()) throw new ArrayKVException("file `" + this.directory + "' is not a directory"); // Get directory channel we can fsync() this.directoryChannel = FileChannel.open(this.directory.toPath()); // Open and lock the lock file this.lockFile = new File(this.directory, LOCK_FILE_NAME); if (!this.lockFile.exists()) { this.lockFileChannel = FileChannel.open(this.lockFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); } else { this.lockFileChannel = FileChannel.open(this.lockFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } FileLock fileLock = null; try { fileLock = this.lockFileChannel.tryLock(); } catch (OverlappingFileLockException e) { // too bad } if (fileLock == null) throw new ArrayKVException("database is already locked by another process or thread"); // If no generation file exists, initialize generation zero this.generationFile = new File(this.directory, GENERATION_FILE_NAME); if (!this.generationFile.exists()) { // Verify no index, keys, or values file exists for (File file : this.directory.listFiles()) { final String name = file.getName(); if (name.startsWith(INDX_FILE_NAME_BASE) || name.startsWith(KEYS_FILE_NAME_BASE) || name.startsWith(VALS_FILE_NAME_BASE)) { throw new ArrayKVException("database file inconsistency: found " + name + " but not " + GENERATION_FILE_NAME + " in " + this.directory); } } // Create empty index, keys, and values files try ( final FileOutputStream indxOutput = new FileOutputStream(new File(this.directory, INDX_FILE_NAME_BASE + 0)); final FileOutputStream keysOutput = new FileOutputStream(new File(this.directory, KEYS_FILE_NAME_BASE + 0)); final FileOutputStream valsOutput = new FileOutputStream(new File(this.directory, VALS_FILE_NAME_BASE + 0)); final ArrayKVWriter arrayWriter = new ArrayKVWriter(indxOutput, keysOutput, valsOutput)) { arrayWriter.flush(); // avoid compiler warning valsOutput.getChannel().force(false); keysOutput.getChannel().force(false); indxOutput.getChannel().force(false); } this.directoryChannel.force(false); // Create generation file try (FileOutputStream output = new FileOutputStream(this.generationFile)) { new PrintStream(output, true).println(0); output.getChannel().force(false); } this.directoryChannel.force(false); } // Read current generation number try { this.generation = Long.parseLong( new String(Files.readAllBytes(this.generationFile.toPath()), StandardCharsets.UTF_8).trim(), 10); if (this.generation < 0) throw new ArrayKVException("read negative generation number from " + this.generationFile); } catch (Exception e) { throw new ArrayKVException("error reading generation file", e); } // Set corresponding filenames this.indxFile = new File(this.directory, INDX_FILE_NAME_BASE + this.generation); this.keysFile = new File(this.directory, KEYS_FILE_NAME_BASE + this.generation); this.valsFile = new File(this.directory, VALS_FILE_NAME_BASE + this.generation); this.modsFile = new File(this.directory, MODS_FILE_NAME_BASE + this.generation); // Scan directory for unexpected files final List<File> expectedFiles = Arrays.asList(this.lockFile, this.generationFile, this.indxFile, this.keysFile, this.valsFile, this.modsFile); for (File file : this.directory.listFiles()) { if (!expectedFiles.contains(file)) this.log.warn("ignoring unexpected file " + file.getName() + " in my database directory"); } // Create buffers that wrap the index, keys, and values files try (FileInputStream input = new FileInputStream(this.indxFile)) { this.indx = AtomicArrayKVStore.getBuffer(this.indxFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(this.keysFile)) { this.keys = AtomicArrayKVStore.getBuffer(this.keysFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(this.valsFile)) { this.vals = AtomicArrayKVStore.getBuffer(this.valsFile, input.getChannel()); } // Set up underlying k/v store and uncompacted modifications this.kvstore = new ArrayKVStore(this.indx, this.keys, this.vals); this.mods = new MutableView(this.kvstore, null, new Writes()); // Setup modifications file this.modsFileOutput = new FileOutputStream(this.modsFile, true); this.modsFileLength = this.modsFileOutput.getChannel().size(); this.modsFileSyncPoint = this.modsFileLength; // Read and apply pre-existing uncompacted modifications from modifications file if (this.modsFileLength > 0) { this.log.info("reading " + this.modsFileLength + " bytes of uncompacted modifications from " + this.modsFile); try (FileInputStream input = new FileInputStream(this.modsFile)) { while (input.available() > 0) { final Writes writes; try { writes = Writes.deserialize(input); } catch (Exception e) { break; // probably a partial write } writes.applyTo(this.mods); } } this.firstModTimestamp = System.nanoTime() | 1; // avoid zero value which is special } // Schedule compaction if necessary this.scheduleCompactionIfNecessary(); // Done success = true; } catch (IOException e) { throw new ArrayKVException("startup failed", e); } finally { try { if (!success) this.cleanup(); } finally { this.writeLock.unlock(); } } } @Override @PreDestroy public void stop() { this.writeLock.lock(); try { // Check state if (this.kvstore == null) return; this.log.info("stopping " + this); // Cleanup this.cleanup(); } finally { this.writeLock.unlock(); } } private void cleanup() { // Should hold write lock now assert this.lock.isWriteLockedByCurrentThread(); // Cancel compaction if possible, otherwise wait for it to complete if (this.compaction != null && !this.compaction.cancel()) { // Wait for compaction to complete this.log.debug("waiting for in-progress compaction to complete before shutdown"); this.compaction.waitForCompletion(); this.log.debug("compaction completed, proceeding with shutdown"); // Check whether another thread invoked stop() while we were asleep if (this.kvstore == null) return; } // Wait for any in-progress hot copies to complete if (this.hotCopiesInProgress > 0) { this.log.debug("waiting for " + this.hotCopiesInProgress + " hot copies to complete before shutdown"); boolean interrupted = false; do { // Wait for hot copies to complete try { this.hotCopyFinishedCondition.await(); } catch (InterruptedException e) { this.log.warn("thread interrupted while waiting for " + this.hotCopiesInProgress + " hot copies to complete (ignoring)", e); interrupted = true; } // Check whether another thread invoked stop() while we were asleep if (this.kvstore == null) return; } while (this.hotCopiesInProgress > 0); if (interrupted) Thread.currentThread().interrupt(); this.log.debug("hot copies completed, proceeding with shutdown"); } // Shut down executor - only if we created it if (this.createdExecutorService) { this.scheduledExecutorService.shutdownNow(); this.scheduledExecutorService = null; this.createdExecutorService = false; } // Close files for (Closeable closeable : new Closeable[] { this.modsFileOutput, this.directoryChannel, this.lockFileChannel }) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // ignore } } } // Reset state this.generation = 0; this.generationFile = null; this.lockFile = null; this.lockFileChannel = null; this.indxFile = null; this.keysFile = null; this.valsFile = null; this.modsFile = null; this.modsFileOutput = null; this.directoryChannel = null; this.modsFileLength = 0; this.modsFileSyncPoint = 0; this.indx = null; this.keys = null; this.vals = null; this.kvstore = null; this.mods = null; this.firstModTimestamp = 0; } // KVStore @Override public byte[] get(byte[] key) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.get(key); } finally { this.readLock.unlock(); } } @Override public KVPair getAtLeast(byte[] minKey) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.getAtLeast(minKey); } finally { this.readLock.unlock(); } } @Override public KVPair getAtMost(byte[] maxKey) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.getAtMost(maxKey); } finally { this.readLock.unlock(); } } @Override public Iterator<KVPair> getRange(byte[] minKey, byte[] maxKey, boolean reverse) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.getRange(minKey, maxKey, reverse); } finally { this.readLock.unlock(); } } @Override public void put(byte[] key, byte[] value) { final Writes writes = new Writes(); writes.getPuts().put(key, value); this.mutate(writes, false); } @Override public void remove(byte[] key) { final Writes writes = new Writes(); writes.setRemoves(new KeyRanges(key)); this.mutate(writes, false); } @Override public void removeRange(byte[] minKey, byte[] maxKey) { final Writes writes = new Writes(); writes.setRemoves(new KeyRanges(minKey != null ? minKey : ByteUtil.EMPTY, maxKey)); this.mutate(writes, false); } @Override public void adjustCounter(byte[] key, long amount) { final Writes writes = new Writes(); writes.getAdjusts().put(key, amount); this.mutate(writes, false); } @Override public byte[] encodeCounter(long value) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.encodeCounter(value); } finally { this.readLock.unlock(); } } @Override public long decodeCounter(byte[] bytes) { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); return this.mods.decodeCounter(bytes); } finally { this.readLock.unlock(); } } // AtomicKVStore @Override public CloseableKVStore snapshot() { this.readLock.lock(); try { Preconditions.checkState(this.kvstore != null, "closed"); // Get outstanding modifications; if we are compacting, there are two sets of modifications final Writes writes1; if (this.mods.getKVStore() instanceof MutableView) { final MutableView oldMods = (MutableView)this.mods.getKVStore(); assert oldMods.getKVStore() == this.kvstore; writes1 = oldMods.getWrites(); } else writes1 = null; final Writes writes2 = this.mods.getWrites(); // Clone (non-empty) writes to construct snapshot KVStore snapshot = this.kvstore; if (writes1 != null && !writes1.isEmpty()) snapshot = new MutableView(snapshot, null, writes1.clone()); if (writes2 != null && !writes2.isEmpty()) snapshot = new MutableView(snapshot, null, writes2.clone()); // Done return new CloseableForwardingKVStore(snapshot); } finally { this.readLock.unlock(); } } @Override public void mutate(Mutations mutations, final boolean sync) { Preconditions.checkArgument(mutations != null, "null mutations"); this.writeLock.lock(); try { // Verify we are started Preconditions.checkState(this.kvstore != null, "not started"); // Block until compaction completes if size of outstanding modifications exceeds high water mark while (this.compaction != null && this.modsFileLength > this.compactHighWater) { // If scheduled compaction is in the future, reschedule to be immediate if (this.compaction.getDelay() > 0) this.scheduleCompaction(0); // Wait for it to complete this.log.debug("reached compaction high-water mark; waiting for in-progress compaction to complete" + " before applying mutation(s)"); this.compaction.waitForCompletion(); this.log.debug("compaction completed, proceeding with application of mutation(s)"); // Verify we are still open after giving up lock if (this.kvstore == null) throw new ArrayKVException("k/v store was closed while waiting for compaction to complete"); } // Get mutations as a Writes object final Writes writes; if (mutations instanceof Writes) writes = (Writes)mutations; else { writes = new Writes(); writes.setRemoves(new KeyRanges(mutations.getRemoveRanges())); for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) writes.getPuts().put(entry.getKey(), entry.getValue()); for (Map.Entry<byte[], Long> entry : mutations.getAdjustPairs()) writes.getAdjusts().put(entry.getKey(), entry.getValue()); } // Check for the trivial case where there are zero modifications if (writes.isEmpty()) return; // Append mutations to uncompacted mods file try { writes.serialize(this.modsFileOutput); this.modsFileOutput.flush(); } catch (IOException e) { try { this.modsFileOutput.getChannel().truncate(this.modsFileLength); // undo append } catch (IOException e2) { this.log.error("error truncating log file (ignoring)", e2); } throw new ArrayKVException("error appending to " + this.modsFile, e); } final long newModsFileLength; try { newModsFileLength = this.modsFileOutput.getChannel().size(); } catch (IOException e) { throw new ArrayKVException("error getting length of " + this.modsFile, e); } if (this.log.isDebugEnabled()) { this.log.debug("appended " + (newModsFileLength - this.modsFileLength) + " bytes to " + this.modsFile + " (new length " + newModsFileLength + ")"); } this.modsFileLength = newModsFileLength; // Apply removes for (KeyRange range : mutations.getRemoveRanges()) { final byte[] min = range.getMin(); final byte[] max = range.getMax(); this.mods.removeRange(min, max); } // Apply puts for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) { final byte[] key = entry.getKey(); final byte[] val = entry.getValue(); this.mods.put(key, val); } // Apply counter adjustments for (Map.Entry<byte[], Long> entry : mutations.getAdjustPairs()) { final byte[] key = entry.getKey(); final long adjust = entry.getValue(); this.mods.adjustCounter(key, adjust); } // Set first uncompacted modification timestamp, if not already set if (this.firstModTimestamp == 0) this.firstModTimestamp = System.nanoTime() | 1; // avoid zero value which is special // Schedule compaction if necessary this.scheduleCompactionIfNecessary(); // If we're not syncing, we're done if (!sync) return; // Update sync point, so compaction knows to also sync these mods when it copies them this.modsFileSyncPoint = this.modsFileLength; // Downgrade lock this.readLock.lock(); } finally { this.writeLock.unlock(); } // Sync the mods file while holding only the read lock try { this.modsFileOutput.getChannel().force(false); } catch (IOException e) { this.log.error("error syncing log file (ignoring)", e); } finally { this.readLock.unlock(); } } // Hot Copy /** * Create a filesystem atomic snapshot, or "hot" copy", of this instance in the specified destination directory. * * <p> * The {@code target} directory will be created if it does not exist; otherwise, it must be empty. * All files except the uncompacted modifications file are copied into {@code target} * in constant time using {@linkplain Files#createLink hard links} if possible. * * <p> * The hot copy operation proceeds in parallel with normal database activity, with the exception * that the compaction operation must wait until there are no concurrent hot copies to complete. * * <p> * Therefore, for best performance, consider {@linkplain #scheduleCompaction performing a compaction} * immediately prior to this operation. * * <p> * The {@code target} directory is not fsync()'d by this method; the caller * must perform that action to ensure durability if required. * * @param target destination directory * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code target} exists and is not a directory or is non-empty * @throws IllegalArgumentException if {@code target} is null */ public void hotCopy(File target) throws IOException { // Sanity check Preconditions.checkArgument(target != null, "null target"); final Path dir = target.toPath(); // Create/verify directory if (!Files.exists(dir)) Files.createDirectories(dir); if (!Files.isDirectory(dir)) throw new IllegalArgumentException("target `" + dir + "' is not a directory"); try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path path : stream) throw new IllegalArgumentException("target `" + dir + "' is not empty"); } // Increment hot copy counter - this prevents compaction from removing files while we're copying them this.writeLock.lock(); try { // Sanity check Preconditions.checkState(this.kvstore != null, "not started"); // Bump counter this.hotCopiesInProgress++; } finally { this.writeLock.unlock(); } try { // Logit this.log.debug("started hot copy into " + target); // Copy index, keys, and values files using hard links (if possible) as these files are read-only final ArrayList<File> regularCopyFiles = new ArrayList<>(5); for (File file : new File[] { this.indxFile, this.keysFile, this.valsFile }) { try { Files.createLink(dir.resolve(file.getName()), file.toPath()); } catch (IOException | UnsupportedOperationException e) { regularCopyFiles.add(file); // fall back to normal copy } } // Copy remaining files without using hard links regularCopyFiles.add(this.modsFile); // it's ok if we copy a partial write regularCopyFiles.add(this.generationFile); // copy this one last for (File file : regularCopyFiles) Files.copy(file.toPath(), dir.resolve(file.getName())); } finally { this.writeLock.lock(); try { // Sanity check assert this.hotCopiesInProgress > 0; assert this.kvstore != null; // Logit this.log.debug("completed hot copy into " + target); // Decrement counter this.hotCopiesInProgress--; // Wakeup waiters this.hotCopyFinishedCondition.signalAll(); } finally { this.writeLock.unlock(); } } } // Compaction /** * Schedule a new compaction cycle, unless there is one already scheduled or running, or there are no * outstanding uncompacted modifications. * * @return a future for the completion of the next compaction cycle, or null if there are no uncompacted modifications * @throws IllegalStateException if this instance is not started */ public Future<?> scheduleCompaction() { this.writeLock.lock(); try { // Sanity check Preconditions.checkState(this.kvstore != null, "not started"); // Is there anything to compact? if (this.modsFileLength == 0) return null; // Schedule an immediate compaction return this.scheduleCompaction(0); } finally { this.writeLock.unlock(); } } private Future<?> scheduleCompaction(long millis) { // Should hold write lock now assert this.lock.isWriteLockedByCurrentThread(); assert this.modsFileLength > 0; // (Re)schedule compaction if necessary if (this.compaction == null || (this.compaction.getDelay() > millis && this.compaction.cancel())) { assert this.compaction == null; this.compaction = new Compaction(millis); } // Done return new ForwardingFuture.SimpleForwardingFuture<Void>(this.compaction.getFuture()) { @Override public boolean cancel(boolean mayInterrupt) { // disallow this operation return false; } }; } private void scheduleCompactionIfNecessary() { // Should hold write lock now assert this.lock.isWriteLockedByCurrentThread(); // Is there anything to do? if (this.modsFileLength == 0) return; // Check space low-water mark if (this.modsFileLength > this.compactLowWater) { this.scheduleCompaction(0); return; } // Check maximum compaction delay if (this.firstModTimestamp != 0) { final long firstModAgeMillis = (System.nanoTime() - this.firstModTimestamp) / 1000000L; // convert ns -> ms this.scheduleCompaction(firstModAgeMillis); return; } } @SuppressWarnings("fallthrough") private void compact(final Compaction compaction) throws IOException { // Sanity check assert compaction != null; // Handle cancel() race condition this.writeLock.lock(); try { // Were we canceled? if (compaction != this.compaction) return; // Set now running - this prevents future cancel()'s assert !compaction.isStarted(); assert !compaction.isCompleted(); compaction.setStarted(); } finally { this.writeLock.unlock(); } // Start compaction final long compactionStartTime; try { // Snapshot (and wrap) pending modifications, and mark log file position final Writes writesToCompact; final long previousModsFileLength; final long previousModsFileSyncPoint; this.writeLock.lock(); try { // Sanity checks assert this.kvstore != null; assert this.modsFileLength > 0; // Mark start time and get uncompacted modifications compactionStartTime = System.nanoTime(); writesToCompact = this.mods.getWrites(); // It's possible the uncompacted modifications are a no-op; if so, no compaction is necessary if (writesToCompact.isEmpty()) { // Wait for any in-progress hot copies to complete while (this.hotCopiesInProgress > 0) { this.log.debug("waiting for " + this.hotCopiesInProgress + " hot copies to complete before completing (trivial) compaction"); try { this.hotCopyFinishedCondition.await(); } catch (InterruptedException e) { throw new ArrayKVException("thread was interrupted while waiting for " + this.hotCopiesInProgress + " hot copies to complete", e); } this.log.debug("hot copies completed, proceeding with completion of (trivial) compaction"); } assert this.kvstore != null; assert this.modsFileLength > 0; // Discard outstanding mods this.modsFileOutput.getChannel().truncate(0); this.modsFileLength = 0; this.modsFileSyncPoint = 0; this.modsFileOutput.getChannel().force(false); return; } // Allow new modifications to be added by other threads while we are compacting the old modifications this.mods = new MutableView(this.mods, null, new Writes()); previousModsFileLength = this.modsFileLength; previousModsFileSyncPoint = this.modsFileSyncPoint; } finally { this.writeLock.unlock(); } if (this.log.isDebugEnabled()) { this.log.debug("starting compaction for generation " + this.generation + " -> " + (this.generation + 1) + " with mods file length " + previousModsFileLength); } // Create the next generation final long newGeneration = this.generation + 1; final File newIndxFile = new File(this.directory, INDX_FILE_NAME_BASE + newGeneration); final File newKeysFile = new File(this.directory, KEYS_FILE_NAME_BASE + newGeneration); final File newValsFile = new File(this.directory, VALS_FILE_NAME_BASE + newGeneration); final File newModsFile = new File(this.directory, MODS_FILE_NAME_BASE + newGeneration); ByteBuffer newIndx = null; ByteBuffer newKeys = null; ByteBuffer newVals = null; FileOutputStream newModsFileOutput = null; boolean success = false; try { // Merge existing compacted key/value data with uncompacted modifications try ( final FileOutputStream indxOutput = new FileOutputStream(newIndxFile); final FileOutputStream keysOutput = new FileOutputStream(newKeysFile); final FileOutputStream valsOutput = new FileOutputStream(newValsFile); final ArrayKVWriter arrayWriter = new ArrayKVWriter(indxOutput, keysOutput, valsOutput)) { // Write out merged key/value pairs arrayWriter.writeMerged(this.kvstore, this.kvstore.getRange(null, null, false), writesToCompact); // Sync file data arrayWriter.flush(); valsOutput.getChannel().force(false); keysOutput.getChannel().force(false); indxOutput.getChannel().force(false); } assert newIndxFile.exists(); assert newKeysFile.exists(); assert newValsFile.exists(); // Create byte buffers from new files try (FileInputStream input = new FileInputStream(newIndxFile)) { newIndx = AtomicArrayKVStore.getBuffer(newIndxFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(newKeysFile)) { newKeys = AtomicArrayKVStore.getBuffer(newKeysFile, input.getChannel()); } try (FileInputStream input = new FileInputStream(newValsFile)) { newVals = AtomicArrayKVStore.getBuffer(newValsFile, input.getChannel()); } // Create new, empty mods file newModsFile.delete(); // shouldn't exist, but just in case... newModsFileOutput = new FileOutputStream(newModsFile, true); assert newModsFile.exists(); // Sync directory this.directoryChannel.force(false); // We're done creating files success = true; } finally { // Finish up this.writeLock.lock(); try { if (success) { // Initialize for wrap-up success = false; // Size up additional mods final long additionalModsLength = this.modsFileLength - previousModsFileLength; // Logit if (this.log.isDebugEnabled()) { final float duration = (System.nanoTime() - compactionStartTime) / 1000000000f; this.log.debug("compaction for generation " + this.generation + " -> " + (this.generation + 1) + " finishing up with " + additionalModsLength + " bytes of new modifications after " + String.format("%.4f", duration) + " seconds"); } // Wait for any in-progress hot copies to complete while (this.hotCopiesInProgress > 0) { this.log.debug("waiting for " + this.hotCopiesInProgress + " hot copies to complete before completing compaction"); try { this.hotCopyFinishedCondition.await(); } catch (InterruptedException e) { throw new ArrayKVException("thread was interrupted while waiting for " + this.hotCopiesInProgress + " hot copies to complete", e); } assert this.compaction == compaction; assert this.kvstore != null; this.log.debug("hot copies completed, proceeding with completion of compaction"); } // Apply any changes that were made while we were unlocked and writing files long newModsFileLength = 0; long newModsFileSyncPoint = 0; if (additionalModsLength > 0) { try ( final FileChannel modsFileChannel = FileChannel.open(this.modsFile.toPath()); final FileChannel newModsFileChannel = FileChannel.open(newModsFile.toPath(), StandardOpenOption.WRITE, StandardOpenOption.APPEND)) { // Append new data in old mods file to new mods file while (newModsFileLength < additionalModsLength) { final long transferred = modsFileChannel.transferTo( previousModsFileLength + newModsFileLength, additionalModsLength - newModsFileLength, newModsFileChannel); assert transferred > 0; newModsFileLength += transferred; } // If any of that new data was fsync()'d, we must fsync() the copy of it in the new mods file if (this.modsFileSyncPoint > previousModsFileSyncPoint) { newModsFileChannel.force(false); newModsFileSyncPoint = newModsFileLength; } } } // Atomically update new generation file contents final AtomicUpdateFileOutputStream genOutput = new AtomicUpdateFileOutputStream(this.generationFile); boolean genSuccess = false; try { new PrintStream(genOutput, true).println(newGeneration); genOutput.getChannel().force(false); genSuccess = true; } finally { if (genSuccess) genOutput.close(); else genOutput.cancel(); } // Declare success success = true; // Remember old info so we can clean it up final File oldIndxFile = this.indxFile; final File oldKeysFile = this.keysFile; final File oldValsFile = this.valsFile; final File oldModsFile = this.modsFile; final FileOutputStream oldModsFileOutput = this.modsFileOutput; // Change to the new generation this.generation = newGeneration; this.indx = newIndx; this.keys = newKeys; this.vals = newVals; this.indxFile = newIndxFile; this.keysFile = newKeysFile; this.valsFile = newValsFile; this.modsFile = newModsFile; this.modsFileOutput = newModsFileOutput; this.modsFileLength = newModsFileLength; this.modsFileSyncPoint = newModsFileSyncPoint; this.kvstore = new ArrayKVStore(this.indx, this.keys, this.vals); this.mods = new MutableView(this.kvstore, null, this.mods.getWrites()); // Sync directory prior to deleting files try { this.directoryChannel.force(false); } catch (IOException e) { this.log.error("error syncing directory " + this.directory + " (ignoring)", e); } // Delete old files oldIndxFile.delete(); oldKeysFile.delete(); oldValsFile.delete(); oldModsFile.delete(); // Close old mods file output stream try { oldModsFileOutput.close(); } catch (IOException e) { // ignore } } } finally { try { // Logit if (this.log.isDebugEnabled()) { final float duration = (System.nanoTime() - compactionStartTime) / 1000000000f; this.log.debug("compaction for generation " + (newGeneration - 1) + " -> " + newGeneration + (success ? " succeeded" : " failed") + " in " + String.format("%.4f", duration) + " seconds"); } // Cleanup/undo on failure if (!success) { // Put back the old uncompacted modifications, and merge any new mods into them final Writes writesDuringCompaction = this.mods.getWrites(); this.mods = new MutableView(this.kvstore, null, writesToCompact); writesDuringCompaction.applyTo(this.mods); // Delete the files we were creating newIndxFile.delete(); newKeysFile.delete(); newValsFile.delete(); if (newModsFileOutput != null) { newModsFile.delete(); try { newModsFileOutput.close(); } catch (Exception e) { // ignore } } } } finally { this.writeLock.unlock(); } } } } finally { // Update state this.writeLock.lock(); try { assert this.kvstore != null; assert this.compaction == compaction; compaction.setCompleted(); this.compaction = null; } finally { this.writeLock.unlock(); } } } // Compaction private class Compaction implements Runnable { private final Condition completedCondition = AtomicArrayKVStore.this.writeLock.newCondition(); private final ScheduledFuture<Void> future; private boolean started; private boolean completed; @SuppressWarnings("unchecked") Compaction(long millis) { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); Preconditions.checkState(AtomicArrayKVStore.this.compaction == null, "compaction already exists"); // Schedule this.future = (ScheduledFuture<Void>)AtomicArrayKVStore.this.scheduledExecutorService.schedule(this, millis, TimeUnit.MILLISECONDS); } /** * Cancel this compaction. * * @return true if canceled, false if already started */ public boolean cancel() { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); Preconditions.checkState(this.future != null, "not scheduled"); // Already canceled? if (AtomicArrayKVStore.this.compaction != this) return false; // Already started? if (this.started) return false; // Attempt to cancel scheduled task assert this.future != null; this.future.cancel(false); // Make this task do nothing even if it runs anyway AtomicArrayKVStore.this.compaction = null; return true; } /** * Get delay until start. * * @return delay in milliseconds */ public long getDelay() { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); Preconditions.checkState(this.future != null, "not scheduled"); // Get delay return Math.max(0, this.future.getDelay(TimeUnit.MILLISECONDS)); } /** * Wait for this compaction to complete. */ public void waitForCompletion() { // Sanity check assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); // Wait for completion boolean interrupted = false; while (!this.completed) { try { this.completedCondition.await(); } catch (InterruptedException e) { AtomicArrayKVStore.this.log.warn( "thread was interrupted while waiting for compaction to complete (ignoring)", e); interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); } public Future<Void> getFuture() { return this.future; } public boolean isStarted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); return this.started; } public void setStarted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); this.started = true; } public boolean isCompleted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); return this.completed; } public void setCompleted() { assert AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); this.completed = true; this.completedCondition.signalAll(); } @Override public void run() { assert !AtomicArrayKVStore.this.lock.isWriteLockedByCurrentThread(); try { AtomicArrayKVStore.this.compact(this); } catch (Throwable t) { AtomicArrayKVStore.this.log.error("error during compaction", t); } } } // Object /** * Finalize this instance. Invokes {@link #stop} to close any unclosed iterators. */ @Override protected void finalize() throws Throwable { try { if (this.kvstore != null) this.log.warn(this + " leaked without invoking stop()"); this.stop(); } finally { super.finalize(); } } @Override public String toString() { return this.getClass().getSimpleName() + "[" + this.directory + "]"; } private static ByteBuffer getBuffer(File file, FileChannel fileChannel) throws IOException { final long length = fileChannel.size(); return length >= MIN_MMAP_LENGTH ? fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, length) : ByteBuffer.wrap(Files.readAllBytes(file.toPath())).asReadOnlyBuffer(); } }
Make array k/v hot copies safer by fsync()'ing before return.
src/java/org/jsimpledb/kv/array/AtomicArrayKVStore.java
Make array k/v hot copies safer by fsync()'ing before return.
<ide><path>rc/java/org/jsimpledb/kv/array/AtomicArrayKVStore.java <ide> <ide> /** <ide> * Create a filesystem atomic snapshot, or "hot" copy", of this instance in the specified destination directory. <add> * The copy will be up-to-date as of the time this method is invoked. <ide> * <ide> * <p> <ide> * The {@code target} directory will be created if it does not exist; otherwise, it must be empty. <ide> * in constant time using {@linkplain Files#createLink hard links} if possible. <ide> * <ide> * <p> <del> * The hot copy operation proceeds in parallel with normal database activity, with the exception <del> * that the compaction operation must wait until there are no concurrent hot copies to complete. <add> * The hot copy operation can proceed in parallel with normal database activity, with the exception <add> * that the compaction operation cannot start while there are concurrent hot copies in progress. <ide> * <ide> * <p> <ide> * Therefore, for best performance, consider {@linkplain #scheduleCompaction performing a compaction} <ide> * immediately prior to this operation. <ide> * <ide> * <p> <del> * The {@code target} directory is not fsync()'d by this method; the caller <del> * must perform that action to ensure durability if required. <add> * Note: when this method returns, all copied files, and the {@code target} directory, have been {@code fsync()}'d <add> * and therefore may be considered durable in case of a system crash. <ide> * <ide> * @param target destination directory <ide> * @throws IOException if an I/O error occurs <ide> // Copy remaining files without using hard links <ide> regularCopyFiles.add(this.modsFile); // it's ok if we copy a partial write <ide> regularCopyFiles.add(this.generationFile); // copy this one last <del> for (File file : regularCopyFiles) <del> Files.copy(file.toPath(), dir.resolve(file.getName())); <add> for (File file : regularCopyFiles) { <add> try (final FileOutputStream fileCopy = new FileOutputStream(new File(target, file.getName()))) { <add> Files.copy(file.toPath(), fileCopy); <add> fileCopy.getChannel().force(false); <add> } <add> } <add> <add> // Sync directory <add> try (FileChannel dirChannel = FileChannel.open(dir)) { <add> dirChannel.force(false); <add> } <ide> } finally { <ide> this.writeLock.lock(); <ide> try {
Java
bsd-3-clause
d642a939c34b904dc78e1e7bb367105f6ab8de40
0
jason-simmons/flutter_engine,jason-simmons/sky_engine,jamesr/flutter_engine,jason-simmons/flutter_engine,devoncarew/sky_engine,devoncarew/engine,rmacnak-google/engine,flutter/engine,Hixie/sky_engine,devoncarew/sky_engine,flutter/engine,jason-simmons/flutter_engine,Hixie/sky_engine,devoncarew/engine,jamesr/sky_engine,aam/engine,aam/engine,chinmaygarde/sky_engine,flutter/engine,Hixie/sky_engine,rmacnak-google/engine,jamesr/flutter_engine,chinmaygarde/flutter_engine,chinmaygarde/sky_engine,devoncarew/engine,jamesr/sky_engine,Hixie/sky_engine,jason-simmons/flutter_engine,chinmaygarde/flutter_engine,rmacnak-google/engine,Hixie/sky_engine,flutter/engine,jason-simmons/flutter_engine,jamesr/flutter_engine,Hixie/sky_engine,rmacnak-google/engine,jason-simmons/flutter_engine,flutter/engine,devoncarew/engine,jamesr/flutter_engine,jason-simmons/flutter_engine,jamesr/sky_engine,devoncarew/sky_engine,chinmaygarde/flutter_engine,chinmaygarde/flutter_engine,jason-simmons/sky_engine,devoncarew/engine,rmacnak-google/engine,devoncarew/sky_engine,jamesr/flutter_engine,chinmaygarde/sky_engine,jamesr/flutter_engine,aam/engine,jamesr/flutter_engine,flutter/engine,jason-simmons/sky_engine,devoncarew/sky_engine,jamesr/flutter_engine,aam/engine,chinmaygarde/sky_engine,devoncarew/sky_engine,aam/engine,rmacnak-google/engine,chinmaygarde/sky_engine,flutter/engine,Hixie/sky_engine,rmacnak-google/engine,jason-simmons/sky_engine,jamesr/sky_engine,jamesr/sky_engine,jason-simmons/flutter_engine,jason-simmons/sky_engine,chinmaygarde/flutter_engine,jamesr/sky_engine,chinmaygarde/flutter_engine,devoncarew/engine,flutter/engine,jamesr/sky_engine,jason-simmons/sky_engine,jamesr/flutter_engine,chinmaygarde/sky_engine,Hixie/sky_engine,devoncarew/engine,aam/engine,aam/engine,jason-simmons/sky_engine,chinmaygarde/sky_engine,aam/engine,chinmaygarde/flutter_engine,devoncarew/sky_engine
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.common; import android.app.Activity; import android.content.Context; import android.content.Intent; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.platform.PlatformViewRegistry; import io.flutter.view.FlutterNativeView; import io.flutter.view.FlutterView; import io.flutter.view.TextureRegistry; /** * Container class for Android API listeners used by {@link ActivityPluginBinding}. * * <p>This class also contains deprecated v1 embedding APIs used for plugin registration. * * <p>In v1 Android applications, an auto-generated and auto-updated plugin registrant class * (GeneratedPluginRegistrant) makes use of a {@link PluginRegistry} to register contributions from * each plugin mentioned in the application's pubspec file. The generated registrant class is, again * by default, called from the application's main {@link Activity}, which defaults to an instance of * {@link io.flutter.app.FlutterActivity}, itself a {@link PluginRegistry}. */ public interface PluginRegistry { /** * Returns a {@link Registrar} for receiving the registrations pertaining to the specified plugin. * * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of * the plugin's main class. * @deprecated See https://flutter.dev/go/android-project-migration for migration details. */ @Deprecated Registrar registrarFor(String pluginKey); /** * Returns whether the specified plugin is known to this registry. * * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of * the plugin's main class. * @return true if this registry has handed out a registrar for the specified plugin. * @deprecated See https://flutter.dev/go/android-project-migration for migration details. */ @Deprecated boolean hasPlugin(String pluginKey); /** * Returns the value published by the specified plugin, if any. * * <p>Plugins may publish a single value, such as an instance of the plugin's main class, for * situations where external control or interaction is needed. Clients are expected to know the * value's type. * * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of * the plugin's main class. * @return the published value, possibly null. * @deprecated See https://flutter.dev/go/android-project-migration for migration details. */ @Deprecated <T> T valuePublishedByPlugin(String pluginKey); /** * Receiver of registrations from a single plugin. * * @deprecated This registrar is for Flutter's v1 embedding. For instructions on migrating a * plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ @Deprecated interface Registrar { /** * Returns the {@link Activity} that forms the plugin's operating context. * * <p>Plugin authors should not assume the type returned by this method is any specific subclass * of {@code Activity} (such as {@link io.flutter.app.FlutterActivity} or {@link * io.flutter.app.FlutterFragmentActivity}), as applications are free to use any activity * subclass. * * <p>When there is no foreground activity in the application, this will return null. If a * {@link Context} is needed, use context() to get the application's context. * * <p>This registrar is for Flutter's v1 embedding. To access an {@code Activity} from a plugin * using the v2 embedding, see {@link ActivityPluginBinding#getActivity()}. To obtain an * instance of an {@link ActivityPluginBinding} in a Flutter plugin, implement the {@link * ActivityAware} interface. A binding is provided in {@link * ActivityAware#onAttachedToActivity(ActivityPluginBinding)} and {@link * ActivityAware#onReattachedToActivityForConfigChanges(ActivityPluginBinding)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ Activity activity(); /** * Returns the {@link android.app.Application}'s {@link Context}. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code Context} from a plugin * using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getApplicationContext()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ Context context(); /** * Returns the active {@link Context}. * * <p>This registrar is for Flutter's v1 embedding. In the v2 embedding, there is no concept of * an "active context". Either use the application {@code Context} or an attached {@code * Activity}. See {@link #context()} and {@link #activity()} for more details. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @return the current {@link #activity() Activity}, if not null, otherwise the {@link * #context() Application}. */ Context activeContext(); /** * Returns a {@link BinaryMessenger} which the plugin can use for creating channels for * communicating with the Dart side. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code BinaryMessenger} from a * plugin using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getBinaryMessenger()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ BinaryMessenger messenger(); /** * Returns a {@link TextureRegistry} which the plugin can use for managing backend textures. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code TextureRegistry} from a * plugin using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getTextureRegistry()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ TextureRegistry textures(); /** * Returns the application's {@link PlatformViewRegistry}. * * <p>Plugins can use the platform registry to register their view factories. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code PlatformViewRegistry} * from a plugin using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getPlatformViewRegistry()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ PlatformViewRegistry platformViewRegistry(); /** * Returns the {@link FlutterView} that's instantiated by this plugin's {@link #activity() * activity}. * * <p>This registrar is for Flutter's v1 embedding. The {@link FlutterView} referenced by this * method does not exist in the v2 embedding. Additionally, no {@code View} is exposed to any * plugins in the v2 embedding. Platform views can access their containing {@code View} using * the platform views APIs. If you have a use-case that absolutely requires a plugin to access * an Android {@code View}, please file a ticket on GitHub. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ FlutterView view(); /** * Returns the file name for the given asset. The returned file name can be used to access the * asset in the APK through the {@link android.content.res.AssetManager} API. * * <p>TODO(mattcarroll): point this method towards new lookup method. * * @param asset the name of the asset. The name can be hierarchical * @return the filename to be used with {@link android.content.res.AssetManager} */ String lookupKeyForAsset(String asset); /** * Returns the file name for the given asset which originates from the specified packageName. * The returned file name can be used to access the asset in the APK through the {@link * android.content.res.AssetManager} API. * * <p>TODO(mattcarroll): point this method towards new lookup method. * * @param asset the name of the asset. The name can be hierarchical * @param packageName the name of the package from which the asset originates * @return the file name to be used with {@link android.content.res.AssetManager} */ String lookupKeyForAsset(String asset, String packageName); /** * Publishes a value associated with the plugin being registered. * * <p>The published value is available to interested clients via {@link * PluginRegistry#valuePublishedByPlugin(String)}. * * <p>Publication should be done only when client code needs to interact with the plugin in a * way that cannot be accomplished by the plugin registering callbacks with client APIs. * * <p>Overwrites any previously published value. * * <p>This registrar is for Flutter's v1 embedding. The concept of publishing values from * plugins is not supported in the v2 embedding. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param value the value, possibly null. * @return this {@link Registrar}. */ Registrar publish(Object value); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@code * Activity#onRequestPermissionsResult(int, String[], int[])} or {@code * androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, * String[], int[])}. * * <p>This registrar is for Flutter's v1 embedding. To listen for permission results in the v2 * embedding, use {@link * ActivityPluginBinding#addRequestPermissionsResultListener(RequestPermissionsResultListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link RequestPermissionsResultListener} callback. * @return this {@link Registrar}. */ Registrar addRequestPermissionsResultListener(RequestPermissionsResultListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onActivityResult(int, int, Intent)}. * * <p>This registrar is for Flutter's v1 embedding. To listen for {@code Activity} results in * the v2 embedding, use {@link * ActivityPluginBinding#addActivityResultListener(ActivityResultListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener an {@link ActivityResultListener} callback. * @return this {@link Registrar}. */ Registrar addActivityResultListener(ActivityResultListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onNewIntent(Intent)}. * * <p>This registrar is for Flutter's v1 embedding. To listen for new {@code Intent}s in the v2 * embedding, use {@link ActivityPluginBinding#addOnNewIntentListener(NewIntentListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link NewIntentListener} callback. * @return this {@link Registrar}. */ Registrar addNewIntentListener(NewIntentListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onUserLeaveHint()}. * * <p>This registrar is for Flutter's v1 embedding. To listen for leave hints in the v2 * embedding, use {@link * ActivityPluginBinding#addOnUserLeaveHintListener(UserLeaveHintListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link UserLeaveHintListener} callback. * @return this {@link Registrar}. */ Registrar addUserLeaveHintListener(UserLeaveHintListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onDestroy()}. * * <p>This registrar is for Flutter's v1 embedding. The concept of {@code View} destruction does * not exist in the v2 embedding. However, plugins in the v2 embedding can respond to {@link * ActivityAware#onDetachedFromActivityForConfigChanges()} and {@link * ActivityAware#onDetachedFromActivity()}, which indicate the loss of a visual context for the * running Flutter experience. Developers should implement {@link ActivityAware} for their * {@link FlutterPlugin} if such callbacks are needed. Also, plugins can respond to {@link * FlutterPlugin#onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding)}, which indicates that * the given plugin has been completely disconnected from the associated Flutter experience and * should clean up any resources. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link ViewDestroyListener} callback. * @return this {@link Registrar}. */ // TODO(amirh): Add a line in the javadoc above that points to a Platform Views website guide // when one is available (but not a website API doc) Registrar addViewDestroyListener(ViewDestroyListener listener); } /** * Delegate interface for handling result of permissions requests on behalf of the main {@link * Activity}. */ interface RequestPermissionsResultListener { /** @return true if the result has been handled. */ boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); } /** Delegate interface for handling activity results on behalf of the main {@link Activity}. */ interface ActivityResultListener { /** @return true if the result has been handled. */ boolean onActivityResult(int requestCode, int resultCode, Intent data); } /** Delegate interface for handling new intents on behalf of the main {@link Activity}. */ interface NewIntentListener { /** @return true if the new intent has been handled. */ boolean onNewIntent(Intent intent); } /** Delegate interface for handling user leave hints on behalf of the main {@link Activity}. */ interface UserLeaveHintListener { void onUserLeaveHint(); } /** * Delegate interface for handling an {@link Activity}'s onDestroy method being called. A plugin * that implements this interface can adopt the FlutterNativeView by retaining a reference and * returning true. * * @deprecated See https://flutter.dev/go/android-project-migration for migration details. */ @Deprecated interface ViewDestroyListener { boolean onViewDestroy(FlutterNativeView view); } /** * Callback interface for registering plugins with a plugin registry. * * <p>For example, an Application may use this callback interface to provide a background service * with a callback for calling its GeneratedPluginRegistrant.registerWith method. * * @deprecated See https://flutter.dev/go/android-project-migration for migration details. */ @Deprecated interface PluginRegistrantCallback { void registerWith(PluginRegistry registry); } }
shell/platform/android/io/flutter/plugin/common/PluginRegistry.java
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugin.common; import android.app.Activity; import android.content.Context; import android.content.Intent; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.platform.PlatformViewRegistry; import io.flutter.view.FlutterNativeView; import io.flutter.view.FlutterView; import io.flutter.view.TextureRegistry; /** * Registry used by plugins to set up interaction with Android APIs. * * <p>Flutter applications by default include an auto-generated and auto-updated plugin registrant * class (GeneratedPluginRegistrant) that makes use of a {@link PluginRegistry} to register * contributions from each plugin mentioned in the application's pubspec file. The generated * registrant class is, again by default, called from the application's main {@link Activity}, which * defaults to an instance of {@link io.flutter.app.FlutterActivity}, itself a {@link * PluginRegistry}. * * @deprecated See https://flutter.dev/go/android-project-migration for migration details. */ @Deprecated public interface PluginRegistry { /** * Returns a {@link Registrar} for receiving the registrations pertaining to the specified plugin. * * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of * the plugin's main class. */ Registrar registrarFor(String pluginKey); /** * Returns whether the specified plugin is known to this registry. * * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of * the plugin's main class. * @return true if this registry has handed out a registrar for the specified plugin. */ boolean hasPlugin(String pluginKey); /** * Returns the value published by the specified plugin, if any. * * <p>Plugins may publish a single value, such as an instance of the plugin's main class, for * situations where external control or interaction is needed. Clients are expected to know the * value's type. * * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of * the plugin's main class. * @return the published value, possibly null. */ <T> T valuePublishedByPlugin(String pluginKey); /** * Receiver of registrations from a single plugin. * * <p>This registrar is for Flutter's v1 embedding. For instructions on migrating a plugin from * Flutter's v1 Android embedding to v2, visit http://flutter.dev/go/android-plugin-migration */ interface Registrar { /** * Returns the {@link Activity} that forms the plugin's operating context. * * <p>Plugin authors should not assume the type returned by this method is any specific subclass * of {@code Activity} (such as {@link io.flutter.app.FlutterActivity} or {@link * io.flutter.app.FlutterFragmentActivity}), as applications are free to use any activity * subclass. * * <p>When there is no foreground activity in the application, this will return null. If a * {@link Context} is needed, use context() to get the application's context. * * <p>This registrar is for Flutter's v1 embedding. To access an {@code Activity} from a plugin * using the v2 embedding, see {@link ActivityPluginBinding#getActivity()}. To obtain an * instance of an {@link ActivityPluginBinding} in a Flutter plugin, implement the {@link * ActivityAware} interface. A binding is provided in {@link * ActivityAware#onAttachedToActivity(ActivityPluginBinding)} and {@link * ActivityAware#onReattachedToActivityForConfigChanges(ActivityPluginBinding)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ Activity activity(); /** * Returns the {@link android.app.Application}'s {@link Context}. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code Context} from a plugin * using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getApplicationContext()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ Context context(); /** * Returns the active {@link Context}. * * <p>This registrar is for Flutter's v1 embedding. In the v2 embedding, there is no concept of * an "active context". Either use the application {@code Context} or an attached {@code * Activity}. See {@link #context()} and {@link #activity()} for more details. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @return the current {@link #activity() Activity}, if not null, otherwise the {@link * #context() Application}. */ Context activeContext(); /** * Returns a {@link BinaryMessenger} which the plugin can use for creating channels for * communicating with the Dart side. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code BinaryMessenger} from a * plugin using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getBinaryMessenger()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ BinaryMessenger messenger(); /** * Returns a {@link TextureRegistry} which the plugin can use for managing backend textures. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code TextureRegistry} from a * plugin using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getTextureRegistry()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ TextureRegistry textures(); /** * Returns the application's {@link PlatformViewRegistry}. * * <p>Plugins can use the platform registry to register their view factories. * * <p>This registrar is for Flutter's v1 embedding. To access a {@code PlatformViewRegistry} * from a plugin using the v2 embedding, see {@link * FlutterPlugin.FlutterPluginBinding#getPlatformViewRegistry()} * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ PlatformViewRegistry platformViewRegistry(); /** * Returns the {@link FlutterView} that's instantiated by this plugin's {@link #activity() * activity}. * * <p>This registrar is for Flutter's v1 embedding. The {@link FlutterView} referenced by this * method does not exist in the v2 embedding. Additionally, no {@code View} is exposed to any * plugins in the v2 embedding. Platform views can access their containing {@code View} using * the platform views APIs. If you have a use-case that absolutely requires a plugin to access * an Android {@code View}, please file a ticket on GitHub. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration */ FlutterView view(); /** * Returns the file name for the given asset. The returned file name can be used to access the * asset in the APK through the {@link android.content.res.AssetManager} API. * * <p>TODO(mattcarroll): point this method towards new lookup method. * * @param asset the name of the asset. The name can be hierarchical * @return the filename to be used with {@link android.content.res.AssetManager} */ String lookupKeyForAsset(String asset); /** * Returns the file name for the given asset which originates from the specified packageName. * The returned file name can be used to access the asset in the APK through the {@link * android.content.res.AssetManager} API. * * <p>TODO(mattcarroll): point this method towards new lookup method. * * @param asset the name of the asset. The name can be hierarchical * @param packageName the name of the package from which the asset originates * @return the file name to be used with {@link android.content.res.AssetManager} */ String lookupKeyForAsset(String asset, String packageName); /** * Publishes a value associated with the plugin being registered. * * <p>The published value is available to interested clients via {@link * PluginRegistry#valuePublishedByPlugin(String)}. * * <p>Publication should be done only when client code needs to interact with the plugin in a * way that cannot be accomplished by the plugin registering callbacks with client APIs. * * <p>Overwrites any previously published value. * * <p>This registrar is for Flutter's v1 embedding. The concept of publishing values from * plugins is not supported in the v2 embedding. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param value the value, possibly null. * @return this {@link Registrar}. */ Registrar publish(Object value); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@code * Activity#onRequestPermissionsResult(int, String[], int[])} or {@code * androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, * String[], int[])}. * * <p>This registrar is for Flutter's v1 embedding. To listen for permission results in the v2 * embedding, use {@link * ActivityPluginBinding#addRequestPermissionsResultListener(RequestPermissionsResultListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link RequestPermissionsResultListener} callback. * @return this {@link Registrar}. */ Registrar addRequestPermissionsResultListener(RequestPermissionsResultListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onActivityResult(int, int, Intent)}. * * <p>This registrar is for Flutter's v1 embedding. To listen for {@code Activity} results in * the v2 embedding, use {@link * ActivityPluginBinding#addActivityResultListener(ActivityResultListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener an {@link ActivityResultListener} callback. * @return this {@link Registrar}. */ Registrar addActivityResultListener(ActivityResultListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onNewIntent(Intent)}. * * <p>This registrar is for Flutter's v1 embedding. To listen for new {@code Intent}s in the v2 * embedding, use {@link ActivityPluginBinding#addOnNewIntentListener(NewIntentListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link NewIntentListener} callback. * @return this {@link Registrar}. */ Registrar addNewIntentListener(NewIntentListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onUserLeaveHint()}. * * <p>This registrar is for Flutter's v1 embedding. To listen for leave hints in the v2 * embedding, use {@link * ActivityPluginBinding#addOnUserLeaveHintListener(UserLeaveHintListener)}. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link UserLeaveHintListener} callback. * @return this {@link Registrar}. */ Registrar addUserLeaveHintListener(UserLeaveHintListener listener); /** * Adds a callback allowing the plugin to take part in handling incoming calls to {@link * Activity#onDestroy()}. * * <p>This registrar is for Flutter's v1 embedding. The concept of {@code View} destruction does * not exist in the v2 embedding. However, plugins in the v2 embedding can respond to {@link * ActivityAware#onDetachedFromActivityForConfigChanges()} and {@link * ActivityAware#onDetachedFromActivity()}, which indicate the loss of a visual context for the * running Flutter experience. Developers should implement {@link ActivityAware} for their * {@link FlutterPlugin} if such callbacks are needed. Also, plugins can respond to {@link * FlutterPlugin#onDetachedFromEngine(FlutterPlugin.FlutterPluginBinding)}, which indicates that * the given plugin has been completely disconnected from the associated Flutter experience and * should clean up any resources. * * <p>For instructions on migrating a plugin from Flutter's v1 Android embedding to v2, visit * http://flutter.dev/go/android-plugin-migration * * @param listener a {@link ViewDestroyListener} callback. * @return this {@link Registrar}. */ // TODO(amirh): Add a line in the javadoc above that points to a Platform Views website guide // when one is available (but not a website API doc) Registrar addViewDestroyListener(ViewDestroyListener listener); } /** * Delegate interface for handling result of permissions requests on behalf of the main {@link * Activity}. */ interface RequestPermissionsResultListener { /** @return true if the result has been handled. */ boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); } /** Delegate interface for handling activity results on behalf of the main {@link Activity}. */ interface ActivityResultListener { /** @return true if the result has been handled. */ boolean onActivityResult(int requestCode, int resultCode, Intent data); } /** Delegate interface for handling new intents on behalf of the main {@link Activity}. */ interface NewIntentListener { /** @return true if the new intent has been handled. */ boolean onNewIntent(Intent intent); } /** Delegate interface for handling user leave hints on behalf of the main {@link Activity}. */ interface UserLeaveHintListener { void onUserLeaveHint(); } /** * Delegate interface for handling an {@link Activity}'s onDestroy method being called. A plugin * that implements this interface can adopt the FlutterNativeView by retaining a reference and * returning true. */ interface ViewDestroyListener { boolean onViewDestroy(FlutterNativeView view); } /** * Callback interface for registering plugins with a plugin registry. * * <p>For example, an Application may use this callback interface to provide a background service * with a callback for calling its GeneratedPluginRegistrant.registerWith method. */ interface PluginRegistrantCallback { void registerWith(PluginRegistry registry); } }
move deprecation from the PluginRegistry outer interface to inner, v1-specific fields (#22345)
shell/platform/android/io/flutter/plugin/common/PluginRegistry.java
move deprecation from the PluginRegistry outer interface to inner, v1-specific fields (#22345)
<ide><path>hell/platform/android/io/flutter/plugin/common/PluginRegistry.java <ide> import io.flutter.view.TextureRegistry; <ide> <ide> /** <del> * Registry used by plugins to set up interaction with Android APIs. <add> * Container class for Android API listeners used by {@link ActivityPluginBinding}. <ide> * <del> * <p>Flutter applications by default include an auto-generated and auto-updated plugin registrant <del> * class (GeneratedPluginRegistrant) that makes use of a {@link PluginRegistry} to register <del> * contributions from each plugin mentioned in the application's pubspec file. The generated <del> * registrant class is, again by default, called from the application's main {@link Activity}, which <del> * defaults to an instance of {@link io.flutter.app.FlutterActivity}, itself a {@link <del> * PluginRegistry}. <add> * <p>This class also contains deprecated v1 embedding APIs used for plugin registration. <ide> * <del> * @deprecated See https://flutter.dev/go/android-project-migration for migration details. <add> * <p>In v1 Android applications, an auto-generated and auto-updated plugin registrant class <add> * (GeneratedPluginRegistrant) makes use of a {@link PluginRegistry} to register contributions from <add> * each plugin mentioned in the application's pubspec file. The generated registrant class is, again <add> * by default, called from the application's main {@link Activity}, which defaults to an instance of <add> * {@link io.flutter.app.FlutterActivity}, itself a {@link PluginRegistry}. <ide> */ <del>@Deprecated <ide> public interface PluginRegistry { <ide> /** <ide> * Returns a {@link Registrar} for receiving the registrations pertaining to the specified plugin. <ide> * <ide> * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of <ide> * the plugin's main class. <del> */ <add> * @deprecated See https://flutter.dev/go/android-project-migration for migration details. <add> */ <add> @Deprecated <ide> Registrar registrarFor(String pluginKey); <ide> <ide> /** <ide> * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of <ide> * the plugin's main class. <ide> * @return true if this registry has handed out a registrar for the specified plugin. <del> */ <add> * @deprecated See https://flutter.dev/go/android-project-migration for migration details. <add> */ <add> @Deprecated <ide> boolean hasPlugin(String pluginKey); <ide> <ide> /** <ide> * @param pluginKey a unique String identifying the plugin; typically the fully qualified name of <ide> * the plugin's main class. <ide> * @return the published value, possibly null. <del> */ <add> * @deprecated See https://flutter.dev/go/android-project-migration for migration details. <add> */ <add> @Deprecated <ide> <T> T valuePublishedByPlugin(String pluginKey); <ide> <ide> /** <ide> * Receiver of registrations from a single plugin. <ide> * <del> * <p>This registrar is for Flutter's v1 embedding. For instructions on migrating a plugin from <del> * Flutter's v1 Android embedding to v2, visit http://flutter.dev/go/android-plugin-migration <del> */ <add> * @deprecated This registrar is for Flutter's v1 embedding. For instructions on migrating a <add> * plugin from Flutter's v1 Android embedding to v2, visit <add> * http://flutter.dev/go/android-plugin-migration <add> */ <add> @Deprecated <ide> interface Registrar { <ide> /** <ide> * Returns the {@link Activity} that forms the plugin's operating context. <ide> * Delegate interface for handling an {@link Activity}'s onDestroy method being called. A plugin <ide> * that implements this interface can adopt the FlutterNativeView by retaining a reference and <ide> * returning true. <del> */ <add> * <add> * @deprecated See https://flutter.dev/go/android-project-migration for migration details. <add> */ <add> @Deprecated <ide> interface ViewDestroyListener { <ide> boolean onViewDestroy(FlutterNativeView view); <ide> } <ide> * <ide> * <p>For example, an Application may use this callback interface to provide a background service <ide> * with a callback for calling its GeneratedPluginRegistrant.registerWith method. <del> */ <add> * <add> * @deprecated See https://flutter.dev/go/android-project-migration for migration details. <add> */ <add> @Deprecated <ide> interface PluginRegistrantCallback { <ide> void registerWith(PluginRegistry registry); <ide> }
Java
bsd-3-clause
error: pathspec 'src/main/java/com/pengyifan/commons/math/PrecisionRecallStats.java' did not match any file(s) known to git
6c3760fb39945ff4f01b76ad94368c26c0fa0a29
1
yfpeng/pengyifan-commons,yfpeng/pengyifan-commons
package com.pengyifan.commons.math; import com.google.common.collect.Lists; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import java.text.NumberFormat; import java.util.List; public class PrecisionRecallStats<E> { private List<E> tps; private List<E> fps; private List<E> fns; public PrecisionRecallStats(List<E> tps, List<E> fps, List<E> fns) { this.tps = Lists.newArrayList(tps); this.fps = Lists.newArrayList(fps); this.fns = Lists.newArrayList(fns); } public PrecisionRecallStats() { tps = Lists.newArrayList(); fps = Lists.newArrayList(); fns = Lists.newArrayList(); } public List<E> getTPs() { return tps; } public List<E> getFPs() { return fps; } public List<E> getFNs() { return fns; } public int getTP() { return tps.size(); } public int getFP() { return fps.size(); } public int getFN() { return fns.size(); } public void incrementTP(E e) { tps.add(e); } public void incrementFP(E e) { fps.add(e); } public void incrementFN(E e) { fns.add(e); } /** * Returns the current precision: <tt>tp/(tp+fp)</tt>. * Returns 1.0 if tp and fp are both 0. */ public double getPrecision() { if (getTP() == 0 && getFP() == 0) { return Double.NaN; } return ((double) getTP()) / (getTP() + getFP()); } /** * Returns the current precision: <tt>tp/(tp+fp)</tt>. * Returns 1.0 if tp and fp are both 0. */ public String getPrecision(int numDigits) { double d = getPrecision(); return Double.isNaN(d) ? "NaN" : getNumberFormat(numDigits).format(d); } /** * Returns the current recall: <tt>tp/(tp+fn)</tt>. * Returns NaN if tp and fn are both 0. */ public double getRecall() { if (getTP() == 0 && getFN() == 0) { return Double.NaN; } return ((double) getTP()) / (getTP() + getFN()); } /** * Returns the current recall: <tt>tp/(tp+fn)</tt>. * Returns NaN if tp and fn are both 0. */ public String getRecall(int numDigits) { double d = getRecall(); return Double.isNaN(d) ? "NaN" : getNumberFormat(numDigits).format(d); } /** * Returns the current F1 measure (<tt>alpha=0.5</tt>). */ public double getFMeasure() { return getFMeasure(0.5); } /** * Returns the current F1 measure (<tt>alpha=0.5</tt>). */ public String getFMeasure(int numDigits) { return getNumberFormat(numDigits).format(getFMeasure()); } /** * Returns the F-Measure with the given mixing parameter (must be between 0 and 1). * If either precision or recall are 0, return 0.0. * <tt>F(alpha) = 1/(alpha/precision + (1-alpha)/recall)</tt> */ public double getFMeasure(double alpha) { double pr = getPrecision(); double re = getRecall(); if (pr == 0 || re == 0) { return 0.0; } return 1.0 / ((alpha / pr) + (1.0 - alpha) / re); } /** * Returns the F-Measure with the given mixing parameter (must be between 0 and 1). * If either precision or recall are 0, return 0.0. * <tt>F(alpha) = 1/(alpha/precision + (1-alpha)/recall)</tt> */ public String getFMeasure(double alpha, int numDigits) { return getNumberFormat(numDigits).format(getFMeasure(alpha)); } /** * Returns a String representation of this PrecisionRecallStats, indicating the number of tp, fp, * fn counts. */ @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("tp", getTP()) .append("fp", getFP()) .append("fn", getFN()) .toString(); } private NumberFormat getNumberFormat(int numDigits) { NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(numDigits); return nf; } }
src/main/java/com/pengyifan/commons/math/PrecisionRecallStats.java
add precision recall stats
src/main/java/com/pengyifan/commons/math/PrecisionRecallStats.java
add precision recall stats
<ide><path>rc/main/java/com/pengyifan/commons/math/PrecisionRecallStats.java <add>package com.pengyifan.commons.math; <add> <add>import com.google.common.collect.Lists; <add>import org.apache.commons.lang3.builder.ToStringBuilder; <add>import org.apache.commons.lang3.builder.ToStringStyle; <add> <add>import java.text.NumberFormat; <add>import java.util.List; <add> <add>public class PrecisionRecallStats<E> { <add> private List<E> tps; <add> private List<E> fps; <add> private List<E> fns; <add> <add> public PrecisionRecallStats(List<E> tps, List<E> fps, List<E> fns) { <add> this.tps = Lists.newArrayList(tps); <add> this.fps = Lists.newArrayList(fps); <add> this.fns = Lists.newArrayList(fns); <add> } <add> <add> public PrecisionRecallStats() { <add> tps = Lists.newArrayList(); <add> fps = Lists.newArrayList(); <add> fns = Lists.newArrayList(); <add> } <add> <add> public List<E> getTPs() { <add> return tps; <add> } <add> <add> public List<E> getFPs() { <add> return fps; <add> } <add> <add> public List<E> getFNs() { <add> return fns; <add> } <add> <add> public int getTP() { <add> return tps.size(); <add> } <add> <add> public int getFP() { <add> return fps.size(); <add> } <add> <add> public int getFN() { <add> return fns.size(); <add> } <add> <add> public void incrementTP(E e) { <add> tps.add(e); <add> } <add> <add> public void incrementFP(E e) { <add> fps.add(e); <add> } <add> <add> public void incrementFN(E e) { <add> fns.add(e); <add> } <add> <add> /** <add> * Returns the current precision: <tt>tp/(tp+fp)</tt>. <add> * Returns 1.0 if tp and fp are both 0. <add> */ <add> public double getPrecision() { <add> if (getTP() == 0 && getFP() == 0) { <add> return Double.NaN; <add> } <add> return ((double) getTP()) / (getTP() + getFP()); <add> } <add> <add> /** <add> * Returns the current precision: <tt>tp/(tp+fp)</tt>. <add> * Returns 1.0 if tp and fp are both 0. <add> */ <add> public String getPrecision(int numDigits) { <add> double d = getPrecision(); <add> return Double.isNaN(d) ? "NaN" : getNumberFormat(numDigits).format(d); <add> } <add> <add> /** <add> * Returns the current recall: <tt>tp/(tp+fn)</tt>. <add> * Returns NaN if tp and fn are both 0. <add> */ <add> public double getRecall() { <add> if (getTP() == 0 && getFN() == 0) { <add> return Double.NaN; <add> } <add> return ((double) getTP()) / (getTP() + getFN()); <add> } <add> <add> /** <add> * Returns the current recall: <tt>tp/(tp+fn)</tt>. <add> * Returns NaN if tp and fn are both 0. <add> */ <add> public String getRecall(int numDigits) { <add> double d = getRecall(); <add> return Double.isNaN(d) ? "NaN" : getNumberFormat(numDigits).format(d); <add> } <add> <add> /** <add> * Returns the current F1 measure (<tt>alpha=0.5</tt>). <add> */ <add> public double getFMeasure() { <add> return getFMeasure(0.5); <add> } <add> <add> /** <add> * Returns the current F1 measure (<tt>alpha=0.5</tt>). <add> */ <add> public String getFMeasure(int numDigits) { <add> return getNumberFormat(numDigits).format(getFMeasure()); <add> } <add> <add> /** <add> * Returns the F-Measure with the given mixing parameter (must be between 0 and 1). <add> * If either precision or recall are 0, return 0.0. <add> * <tt>F(alpha) = 1/(alpha/precision + (1-alpha)/recall)</tt> <add> */ <add> public double getFMeasure(double alpha) { <add> double pr = getPrecision(); <add> double re = getRecall(); <add> if (pr == 0 || re == 0) { <add> return 0.0; <add> } <add> return 1.0 / ((alpha / pr) + (1.0 - alpha) / re); <add> } <add> <add> /** <add> * Returns the F-Measure with the given mixing parameter (must be between 0 and 1). <add> * If either precision or recall are 0, return 0.0. <add> * <tt>F(alpha) = 1/(alpha/precision + (1-alpha)/recall)</tt> <add> */ <add> public String getFMeasure(double alpha, int numDigits) { <add> return getNumberFormat(numDigits).format(getFMeasure(alpha)); <add> } <add> <add> /** <add> * Returns a String representation of this PrecisionRecallStats, indicating the number of tp, fp, <add> * fn counts. <add> */ <add> @Override <add> public String toString() { <add> return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) <add> .append("tp", getTP()) <add> .append("fp", getFP()) <add> .append("fn", getFN()) <add> .toString(); <add> } <add> <add> private NumberFormat getNumberFormat(int numDigits) { <add> NumberFormat nf = NumberFormat.getNumberInstance(); <add> nf.setMaximumFractionDigits(numDigits); <add> return nf; <add> } <add>}
Java
apache-2.0
0d90ec97ad96ec87ba6edb8b3d3ef26ea418e473
0
timgifford/tiles,timgifford/tiles
/* * $Id$ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tiles.web.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tiles.Attribute; import org.apache.tiles.AttributeContext; import org.apache.tiles.TilesContainer; import org.apache.tiles.TilesException; import org.apache.tiles.access.TilesAccess; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Map; import java.util.Enumeration; import java.util.HashMap; /** * Decoration Filter. Intercepts all requests and decorates them * with the configured definition. * <p/> * For example, given the following config: * <xmp> * <filter> * <filter-name>Tiles Decoration Filter</filter-name> * <filter-class>org.apache.tiles.web.TilesDecorationFilter</filter-class> * <init-param> * <param-name>definition</param-name> * <param-value>test.definition</param-value> * </init-param> * <init-param> * <param-name>attribute-name</param-name> * <param-value>body</param-value> * </init-param> * <init-param> * <param-name>prevent-token</param-name> * <param-value>layout</param-value> * </init-param> * </filter> * <p/> * <filter-mapping> * <filter-name>Tiles Decoration Filter</filter-name> * <url-pattern>/testdecorationfilter.jsp</url-pattern> * <dispatcher>REQUEST</dispatcher> * </filter-mapping> * </xmp> * The filter will intercept all requests to the indicated url pattern * store the initial request path as the "body" attribute and then render the * "test.definition" definition. The filter will only redecorate those requests * which do not contain the request attribute associated with the prevent token * "layout". */ public class TilesDecorationFilter implements Filter { /** * The logging object. */ private static final Log LOG = LogFactory.getLog(TilesDecorationFilter.class); /** * Filter configuration. */ private FilterConfig filterConfig; /** * The name of the definition attribute used to * pass on the request. */ private String definitionAttributeName = "content"; /** * The definition name to use. */ private String definitionName = "layout"; /** * Token used to prevent re-decoration of requests. * This token is used to prevent infinate loops on * filters configured to match wildcards. */ private String preventDecorationToken; /** * Stores a map of the type "mask -> definition": when a definition name * mask is identified, it is substituted with the configured definition. */ private Map<String, String> alternateDefinitions; /** * The object that will mutate the attribute context so that it uses * different attributes. */ private AttributeContextMutator mutator = null; /** * Returns the filter configuration object. * * @return The filter configuration. */ public FilterConfig getFilterConfig() { return filterConfig; } /** * Returns the servlet context. * * @return The servlet context. */ public ServletContext getServletContext() { return filterConfig.getServletContext(); } /** {@inheritDoc} */ public void init(FilterConfig config) throws ServletException { filterConfig = config; String temp = config.getInitParameter("attribute-name"); if (temp != null) { definitionAttributeName = temp; } temp = config.getInitParameter("definition"); if (temp != null) { definitionName = temp; } temp = config.getInitParameter("prevent-token"); preventDecorationToken = "org.apache.tiles.decoration.PREVENT:" + (temp == null ? definitionName : temp); alternateDefinitions = parseAlternateDefinitions(); temp = config.getInitParameter("mutator"); if (temp != null) { try { mutator = (AttributeContextMutator) Class.forName(temp) .newInstance(); } catch (Exception e) { throw new ServletException("Unable to instantiate specified context mutator.", e); } } else { mutator = new DefaultMutator(); } } /** * Creates the alternate definitions map, to map a mask of definition names * to a configured definition. * * @return The alternate definitions map. */ @SuppressWarnings("unchecked") protected Map<String, String> parseAlternateDefinitions() { Map<String, String> map = new HashMap<String, String>(); Enumeration<String> e = filterConfig.getInitParameterNames(); while (e.hasMoreElements()) { String parm = e.nextElement(); if (parm.startsWith("definition(") && parm.endsWith("*)")) { String value = filterConfig.getInitParameter(parm); String mask = parm.substring("definition(".length()); mask = mask.substring(0, mask.lastIndexOf("*)")); map.put(mask, value); LOG.info("Mapping all requests matching '" + mask + "*' to definition '" + value + "'"); } } return map; } /** {@inheritDoc} */ public void destroy() { filterConfig = null; } /** * {@inheritDoc} */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { // If the request contains the prevent token, we must not reapply the definition. // This is used to ensure that filters mapped to wild cards do not infinately // loop. if (isPreventTokenPresent(req)) { filterChain.doFilter(req, res); return; } TilesContainer container = TilesAccess.getContainer(getServletContext()); mutator.mutate(container.getAttributeContext(req, res), req); try { if (preventDecorationToken != null) { req.setAttribute(preventDecorationToken, Boolean.TRUE); } String definitionName = getDefinitionForRequest(req); container.render(definitionName, req, res); } catch (TilesException e) { throw new ServletException("Error wrapping jsp with tile definition. " + e.getMessage(), e); } } /** * Returns the final definition to render for the given request. * * @param request The request object. * @return The final definition name. */ private String getDefinitionForRequest(ServletRequest request) { if (alternateDefinitions.size() < 1) { return definitionName; } String base = getRequestBase(request); for (Map.Entry<String, String> pair : alternateDefinitions.entrySet()) { if (base.startsWith(pair.getKey())) { return pair.getValue(); } } return definitionName; } /** * Returns the request base, i.e. the the URL to calculate all the relative * paths. * * @param request The request object to use. * @return The request base. */ private String getRequestBase(ServletRequest request) { // Included Path String include = (String) request.getAttribute("javax.servlet.include.servlet_path"); if (include != null) { return include; } // As opposed to includes, if a forward occurs, it will update the servletPath property // and include the original as the request attribute. return ((HttpServletRequest) request).getServletPath(); } /** * The default attribute context mutator to use. */ class DefaultMutator implements AttributeContextMutator { /** {@inheritDoc} */ public void mutate(AttributeContext ctx, ServletRequest req) { Attribute attr = new Attribute(); attr.setRenderer("template"); attr.setValue(getRequestBase(req)); ctx.putAttribute(definitionAttributeName, attr); } } /** * Checks if the prevent evaluation token is present. * * @param request The HTTP request object. * @return <code>true</code> if the token is present. */ private boolean isPreventTokenPresent(ServletRequest request) { return preventDecorationToken != null && request.getAttribute(preventDecorationToken) != null; } }
tiles-core/src/main/java/org/apache/tiles/web/util/TilesDecorationFilter.java
/* * $Id$ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tiles.web.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tiles.Attribute; import org.apache.tiles.AttributeContext; import org.apache.tiles.TilesContainer; import org.apache.tiles.TilesException; import org.apache.tiles.Attribute.AttributeType; import org.apache.tiles.access.TilesAccess; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Map; import java.util.Enumeration; import java.util.HashMap; /** * Decoration Filter. Intercepts all requests and decorates them * with the configured definition. * <p/> * For example, given the following config: * <xmp> * <filter> * <filter-name>Tiles Decoration Filter</filter-name> * <filter-class>org.apache.tiles.web.TilesDecorationFilter</filter-class> * <init-param> * <param-name>definition</param-name> * <param-value>test.definition</param-value> * </init-param> * <init-param> * <param-name>attribute-name</param-name> * <param-value>body</param-value> * </init-param> * <init-param> * <param-name>prevent-token</param-name> * <param-value>layout</param-value> * </init-param> * </filter> * <p/> * <filter-mapping> * <filter-name>Tiles Decoration Filter</filter-name> * <url-pattern>/testdecorationfilter.jsp</url-pattern> * <dispatcher>REQUEST</dispatcher> * </filter-mapping> * </xmp> * The filter will intercept all requests to the indicated url pattern * store the initial request path as the "body" attribute and then render the * "test.definition" definition. The filter will only redecorate those requests * which do not contain the request attribute associated with the prevent token * "layout". */ public class TilesDecorationFilter implements Filter { /** * The logging object. */ private static final Log LOG = LogFactory.getLog(TilesDecorationFilter.class); /** * Filter configuration. */ private FilterConfig filterConfig; /** * The name of the definition attribute used to * pass on the request. */ private String definitionAttributeName = "content"; /** * The definition name to use. */ private String definitionName = "layout"; /** * Token used to prevent re-decoration of requests. * This token is used to prevent infinate loops on * filters configured to match wildcards. */ private String preventDecorationToken; /** * Stores a map of the type "mask -> definition": when a definition name * mask is identified, it is substituted with the configured definition. */ private Map<String, String> alternateDefinitions; /** * The object that will mutate the attribute context so that it uses * different attributes. */ private AttributeContextMutator mutator = null; /** * Returns the filter configuration object. * * @return The filter configuration. */ public FilterConfig getFilterConfig() { return filterConfig; } /** * Returns the servlet context. * * @return The servlet context. */ public ServletContext getServletContext() { return filterConfig.getServletContext(); } /** {@inheritDoc} */ public void init(FilterConfig config) throws ServletException { filterConfig = config; String temp = config.getInitParameter("attribute-name"); if (temp != null) { definitionAttributeName = temp; } temp = config.getInitParameter("definition"); if (temp != null) { definitionName = temp; } temp = config.getInitParameter("prevent-token"); preventDecorationToken = "org.apache.tiles.decoration.PREVENT:"+(temp == null ? definitionName : temp); alternateDefinitions = parseAlternateDefinitions(); temp = config.getInitParameter("mutator"); if (temp != null) { try { mutator = (AttributeContextMutator) Class.forName(temp) .newInstance(); } catch (Exception e) { throw new ServletException("Unable to instantiate specified context mutator.", e); } } else { mutator = new DefaultMutator(); } } /** * Creates the alternate definitions map, to map a mask of definition names * to a configured definition. * * @return The alternate definitions map. */ @SuppressWarnings("unchecked") protected Map<String, String> parseAlternateDefinitions() { Map<String, String> map = new HashMap<String, String>(); Enumeration<String> e = filterConfig.getInitParameterNames(); while (e.hasMoreElements()) { String parm = e.nextElement(); if (parm.startsWith("definition(") && parm.endsWith("*)")) { String value = filterConfig.getInitParameter(parm); String mask = parm.substring("definition(".length()); mask = mask.substring(0, mask.lastIndexOf("*)")); map.put(mask, value); LOG.info("Mapping all requests matching '" + mask + "*' to definition '" + value + "'"); } } return map; } /** {@inheritDoc} */ public void destroy() { filterConfig = null; } /** * {@inheritDoc} */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { // If the request contains the prevent token, we must not reapply the definition. // This is used to ensure that filters mapped to wild cards do not infinately // loop. if (isPreventTokenPresent(req)) { filterChain.doFilter(req, res); return; } TilesContainer container = TilesAccess.getContainer(getServletContext()); mutator.mutate(container.getAttributeContext(req, res), req); try { if(preventDecorationToken != null) { req.setAttribute(preventDecorationToken, Boolean.TRUE); } String definitionName = getDefinitionForRequest(req); container.render(definitionName, req, res); } catch (TilesException e) { throw new ServletException("Error wrapping jsp with tile definition. " + e.getMessage(), e); } } /** * Returns the final definition to render for the given request. * * @param request The request object. * @return The final definition name. */ private String getDefinitionForRequest(ServletRequest request) { if (alternateDefinitions.size() < 1) { return definitionName; } String base = getRequestBase(request); for (Map.Entry<String, String> pair : alternateDefinitions.entrySet()) { if (base.startsWith(pair.getKey())) { return pair.getValue(); } } return definitionName; } /** * Returns the request base, i.e. the the URL to calculate all the relative * paths. * * @param request The request object to use. * @return The request base. */ private String getRequestBase(ServletRequest request) { // Included Path String include = (String) request.getAttribute("javax.servlet.include.servlet_path"); if (include != null) { return include; } // As opposed to includes, if a forward occurs, it will update the servletPath property // and include the original as the request attribute. return ((HttpServletRequest) request).getServletPath(); } /** * The default attribute context mutator to use. */ class DefaultMutator implements AttributeContextMutator { /** {@inheritDoc} */ public void mutate(AttributeContext ctx, ServletRequest req) { Attribute attr = new Attribute(); attr.setType(AttributeType.TEMPLATE); attr.setValue(getRequestBase(req)); ctx.putAttribute(definitionAttributeName, attr); } } private boolean isPreventTokenPresent(ServletRequest request) { return preventDecorationToken != null && request.getAttribute(preventDecorationToken) != null; } }
Fixed Checkstyle problems. git-svn-id: 64d0ca227631da92532e2ab7c1519b56fd7cbde3@637217 13f79535-47bb-0310-9956-ffa450edef68
tiles-core/src/main/java/org/apache/tiles/web/util/TilesDecorationFilter.java
Fixed Checkstyle problems.
<ide><path>iles-core/src/main/java/org/apache/tiles/web/util/TilesDecorationFilter.java <ide> import org.apache.tiles.AttributeContext; <ide> import org.apache.tiles.TilesContainer; <ide> import org.apache.tiles.TilesException; <del>import org.apache.tiles.Attribute.AttributeType; <ide> import org.apache.tiles.access.TilesAccess; <ide> <ide> import javax.servlet.Filter; <ide> } <ide> <ide> temp = config.getInitParameter("prevent-token"); <del> preventDecorationToken = "org.apache.tiles.decoration.PREVENT:"+(temp == null ? definitionName : temp); <add> preventDecorationToken = "org.apache.tiles.decoration.PREVENT:" <add> + (temp == null ? definitionName : temp); <ide> <ide> alternateDefinitions = parseAlternateDefinitions(); <ide> <ide> filterChain.doFilter(req, res); <ide> return; <ide> } <del> <add> <ide> TilesContainer container = TilesAccess.getContainer(getServletContext()); <ide> mutator.mutate(container.getAttributeContext(req, res), req); <ide> try { <del> if(preventDecorationToken != null) { <add> if (preventDecorationToken != null) { <ide> req.setAttribute(preventDecorationToken, Boolean.TRUE); <ide> } <ide> String definitionName = getDefinitionForRequest(req); <ide> container.render(definitionName, req, res); <del> } <del> catch (TilesException e) { <add> } catch (TilesException e) { <ide> throw new ServletException("Error wrapping jsp with tile definition. " <ide> + e.getMessage(), e); <ide> } <ide> /** {@inheritDoc} */ <ide> public void mutate(AttributeContext ctx, ServletRequest req) { <ide> Attribute attr = new Attribute(); <del> attr.setType(AttributeType.TEMPLATE); <add> attr.setRenderer("template"); <ide> attr.setValue(getRequestBase(req)); <ide> ctx.putAttribute(definitionAttributeName, attr); <ide> } <ide> } <ide> <add> /** <add> * Checks if the prevent evaluation token is present. <add> * <add> * @param request The HTTP request object. <add> * @return <code>true</code> if the token is present. <add> */ <ide> private boolean isPreventTokenPresent(ServletRequest request) { <ide> return preventDecorationToken != null && request.getAttribute(preventDecorationToken) != null; <ide> }
Java
apache-2.0
75ffb9e42395ed4f846e31d1a6c8d7192697dafb
0
strongbox/strongbox,strongbox/strongbox,strongbox/strongbox,sbespalov/strongbox,sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox,sbespalov/strongbox
package org.carlspring.strongbox.io; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; import org.apache.commons.io.IOUtils; import org.apache.maven.artifact.Artifact; import org.carlspring.maven.commons.util.ArtifactUtils; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.artifact.coordinates.MavenArtifactCoordinates; import org.carlspring.strongbox.config.CommonConfig; import org.carlspring.strongbox.config.StorageApiConfig; import org.carlspring.strongbox.configuration.Configuration; import org.carlspring.strongbox.configuration.ConfigurationManager; import org.carlspring.strongbox.providers.storage.FileSystemStorageProvider; import org.carlspring.strongbox.storage.Storage; import org.carlspring.strongbox.storage.repository.Repository; import org.carlspring.strongbox.testing.TestCaseWithArtifactGeneration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author mtodorov */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class ArtifactOutputStreamTest extends TestCaseWithArtifactGeneration { @org.springframework.context.annotation.Configuration @Import({ StorageApiConfig.class, CommonConfig.class }) public static class SpringConfig { } @Autowired private ConfigurationManager configurationManager; @Test public void testCreateWithTemporaryLocation() throws IOException { final Storage storage = getConfiguration().getStorage("storage0"); final Repository repository = storage.getRepository("releases"); final Artifact artifact = ArtifactUtils.getArtifactFromGAVTC("org.carlspring.foo:temp-file-test:1.2.3:jar"); final ArtifactCoordinates coordinates = new MavenArtifactCoordinates(artifact); ArtifactPath artifactPath = new ArtifactPath(coordinates, FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), FileSystemStorageProvider.getRepositoryFileSystem(repository)); RepositoryFileSystemProvider provider = (RepositoryFileSystemProvider) artifactPath.getFileSystem().provider(); RepositoryPath artifactPathTemp = provider.getTempPath(artifactPath); final ArtifactOutputStream afos = new ArtifactOutputStream(Files.newOutputStream(artifactPathTemp), coordinates); ByteArrayInputStream bais = new ByteArrayInputStream("This is a test\n".getBytes()); IOUtils.copy(bais, afos); assertTrue("Failed to create temporary artifact file!", Files.exists(artifactPathTemp)); afos.close(); provider.restoreFromTemp(artifactPath); assertTrue("Failed to the move temporary artifact file to original location!", Files.exists(artifactPath)); } @Test public void testCreateWithTemporaryLocationNoMoveOnClose() throws IOException { final Storage storage = getConfiguration().getStorage("storage0"); final Repository repository = storage.getRepository("releases"); final Artifact artifact = ArtifactUtils.getArtifactFromGAVTC("org.carlspring.foo:temp-file-test:1.2.4:jar"); final ArtifactCoordinates coordinates = new MavenArtifactCoordinates(artifact); ArtifactPath artifactPath = new ArtifactPath(coordinates, FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), FileSystemStorageProvider.getRepositoryFileSystem(repository)); RepositoryFileSystemProvider provider = (RepositoryFileSystemProvider) artifactPath.getFileSystem().provider(); RepositoryPath artifactPathTemp = provider.getTempPath(artifactPath); final ArtifactOutputStream afos = new ArtifactOutputStream(Files.newOutputStream(artifactPathTemp), coordinates); ByteArrayInputStream bais = new ByteArrayInputStream("This is a test\n".getBytes()); IOUtils.copy(bais, afos); assertTrue("Failed to create temporary artifact file!", Files.exists(artifactPathTemp)); afos.close(); assertFalse("Should not have move temporary the artifact file to original location!", Files.exists(artifactPath)); assertTrue("Should not have move temporary the artifact file to original location!", Files.exists(artifactPathTemp)); } private Configuration getConfiguration() { return configurationManager.getConfiguration(); } }
strongbox-storage/strongbox-storage-api/src/test/java/org/carlspring/strongbox/io/ArtifactOutputStreamTest.java
package org.carlspring.strongbox.io; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; import org.apache.commons.io.IOUtils; import org.apache.maven.artifact.Artifact; import org.carlspring.maven.commons.util.ArtifactUtils; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.artifact.coordinates.MavenArtifactCoordinates; import org.carlspring.strongbox.config.CommonConfig; import org.carlspring.strongbox.config.StorageApiConfig; import org.carlspring.strongbox.configuration.Configuration; import org.carlspring.strongbox.configuration.ConfigurationManager; import org.carlspring.strongbox.providers.storage.FileSystemStorageProvider; import org.carlspring.strongbox.storage.Storage; import org.carlspring.strongbox.storage.repository.Repository; import org.carlspring.strongbox.testing.TestCaseWithArtifactGeneration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author mtodorov */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class ArtifactOutputStreamTest extends TestCaseWithArtifactGeneration { @org.springframework.context.annotation.Configuration @Import({ StorageApiConfig.class, CommonConfig.class }) public static class SpringConfig { } @Autowired private ConfigurationManager configurationManager; @Test public void testCreateWithTemporaryLocation() throws IOException { final Storage storage = getConfiguration().getStorage("storage0"); final Repository repository = storage.getRepository("releases"); final Artifact artifact = ArtifactUtils.getArtifactFromGAVTC("org.carlspring.foo:temp-file-test:1.2.3:jar"); final ArtifactCoordinates coordinates = new MavenArtifactCoordinates(artifact); ArtifactPath artifactPath = new ArtifactPath(coordinates, FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), FileSystemStorageProvider.getRepositoryFileSystem(repository)); RepositoryFileSystemProvider provider = (RepositoryFileSystemProvider) artifactPath.getFileSystem().provider(); RepositoryPath artifactPathTemp = provider.getTempPath(artifactPath); final ArtifactOutputStream afos = new ArtifactOutputStream(Files.newOutputStream(artifactPathTemp), coordinates); ByteArrayInputStream bais = new ByteArrayInputStream("This is a test\n".getBytes()); IOUtils.copy(bais, afos); assertTrue("Failed to create temporary artifact file!", Files.exists(artifactPathTemp)); afos.close(); provider.restoreFromTemp(artifactPath); assertTrue("Failed to the move temporary artifact file to original location!", Files.exists(artifactPath)); } @Test public void testCreateWithTemporaryLocationNoMoveOnClose() throws IOException { final Storage storage = getConfiguration().getStorage("storage0"); final Repository repository = storage.getRepository("releases"); final Artifact artifact = ArtifactUtils.getArtifactFromGAVTC("org.carlspring.foo:temp-file-test:1.2.4:jar"); final ArtifactCoordinates coordinates = new MavenArtifactCoordinates(artifact); ArtifactPath artifactPath = new ArtifactPath(coordinates, FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), FileSystemStorageProvider.getRepositoryFileSystem(repository)); RepositoryFileSystemProvider provider = (RepositoryFileSystemProvider) artifactPath.getFileSystem().provider(); RepositoryPath artifactPathTemp = provider.getTempPath(artifactPath); final ArtifactOutputStream afos = new ArtifactOutputStream(Files.newOutputStream(artifactPathTemp), coordinates); ByteArrayInputStream bais = new ByteArrayInputStream("This is a test\n".getBytes()); IOUtils.copy(bais, afos); assertTrue("Failed to create temporary artifact file!", Files.exists(artifactPathTemp)); afos.close(); assertFalse("Should not have move temporary the artifact file to original location!", Files.exists(artifactPath)); assertTrue("Should not have move temporary the artifact file to original location!", Files.exists(artifactPathTemp)); } private Configuration getConfiguration() { return configurationManager.getConfiguration(); } }
SB-713: `StorageProvider` refactored to use `java.nio.file.Path` abstraction Fixed the indentation.
strongbox-storage/strongbox-storage-api/src/test/java/org/carlspring/strongbox/io/ArtifactOutputStreamTest.java
SB-713: `StorageProvider` refactored to use `java.nio.file.Path` abstraction
<ide><path>trongbox-storage/strongbox-storage-api/src/test/java/org/carlspring/strongbox/io/ArtifactOutputStreamTest.java <ide> { <ide> <ide> @org.springframework.context.annotation.Configuration <del> @Import({ <del> StorageApiConfig.class, <del> CommonConfig.class <del> }) <add> @Import({ StorageApiConfig.class, <add> CommonConfig.class <add> }) <add> <ide> public static class SpringConfig { } <ide> <ide> @Autowired <ide> final Artifact artifact = ArtifactUtils.getArtifactFromGAVTC("org.carlspring.foo:temp-file-test:1.2.3:jar"); <ide> final ArtifactCoordinates coordinates = new MavenArtifactCoordinates(artifact); <ide> ArtifactPath artifactPath = new ArtifactPath(coordinates, <del> FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), <del> FileSystemStorageProvider.getRepositoryFileSystem(repository)); <add> FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), <add> FileSystemStorageProvider.getRepositoryFileSystem(repository)); <ide> RepositoryFileSystemProvider provider = (RepositoryFileSystemProvider) artifactPath.getFileSystem().provider(); <ide> RepositoryPath artifactPathTemp = provider.getTempPath(artifactPath); <ide> <ide> final ArtifactOutputStream afos = new ArtifactOutputStream(Files.newOutputStream(artifactPathTemp), coordinates); <ide> ByteArrayInputStream bais = new ByteArrayInputStream("This is a test\n".getBytes()); <ide> IOUtils.copy(bais, afos); <add> <ide> assertTrue("Failed to create temporary artifact file!", Files.exists(artifactPathTemp)); <add> <ide> afos.close(); <ide> provider.restoreFromTemp(artifactPath); <add> <ide> assertTrue("Failed to the move temporary artifact file to original location!", Files.exists(artifactPath)); <ide> } <ide> <ide> <ide> final Artifact artifact = ArtifactUtils.getArtifactFromGAVTC("org.carlspring.foo:temp-file-test:1.2.4:jar"); <ide> final ArtifactCoordinates coordinates = new MavenArtifactCoordinates(artifact); <add> <ide> ArtifactPath artifactPath = new ArtifactPath(coordinates, <del> FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), <del> FileSystemStorageProvider.getRepositoryFileSystem(repository)); <add> FileSystemStorageProvider.getArtifactPath(repository.getBasedir(), coordinates.toPath()), <add> FileSystemStorageProvider.getRepositoryFileSystem(repository)); <add> <ide> RepositoryFileSystemProvider provider = (RepositoryFileSystemProvider) artifactPath.getFileSystem().provider(); <ide> RepositoryPath artifactPathTemp = provider.getTempPath(artifactPath); <ide> <ide> final ArtifactOutputStream afos = new ArtifactOutputStream(Files.newOutputStream(artifactPathTemp), coordinates); <ide> ByteArrayInputStream bais = new ByteArrayInputStream("This is a test\n".getBytes()); <ide> IOUtils.copy(bais, afos); <add> <ide> assertTrue("Failed to create temporary artifact file!", Files.exists(artifactPathTemp)); <add> <ide> afos.close(); <del> assertFalse("Should not have move temporary the artifact file to original location!", <del> Files.exists(artifactPath)); <del> assertTrue("Should not have move temporary the artifact file to original location!", <del> Files.exists(artifactPathTemp)); <add> <add> assertFalse("Should not have move temporary the artifact file to original location!", Files.exists(artifactPath)); <add> assertTrue("Should not have move temporary the artifact file to original location!", Files.exists(artifactPathTemp)); <ide> } <ide> <ide> private Configuration getConfiguration()
Java
apache-2.0
a295eaca923f101081b16c432acc43fb74884fff
0
Cantara/Java-Auto-Update,Cantara/Java-Auto-Update
src/main/java/no/cantara/jau/eventextraction/EventPublisher.java
package no.cantara.jau.eventextraction; public class EventPublisher { }
Remove EventPublisher. Events will be included in CheckForUpdate
src/main/java/no/cantara/jau/eventextraction/EventPublisher.java
Remove EventPublisher. Events will be included in CheckForUpdate
<ide><path>rc/main/java/no/cantara/jau/eventextraction/EventPublisher.java <del>package no.cantara.jau.eventextraction; <del> <del>public class EventPublisher { <del>}