answer
stringlengths
17
10.2M
package org.jboss.loom.utils.el; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Ondrej Zizka, ozizka at redhat.com */ public class ELUtils { private static final Logger log = LoggerFactory.getLogger( ELUtils.class ); public static void evaluateObjectMembersEL( Object obj, JuelCustomResolverEvaluator eval ) { Class curClass = obj.getClass(); while( curClass != null && ! Object.class.equals( curClass ) ){ for( Field fld : curClass.getDeclaredFields() ){ //if( ! fld.getType().equals( String.class )) if( ! String.class.isAssignableFrom( fld.getType() ) ) continue; if( null == fld.getAnnotation( EL.class )) continue; try { String orig = (String) fld.get( obj ); String res = eval.evaluateEL( orig ); fld.set( obj, res ); } catch( IllegalArgumentException | IllegalAccessException ex ) { throw new IllegalStateException("Failed resolving EL in " + obj + ": " + ex.getMessage(), ex); } } curClass = curClass.getSuperclass(); } } }// class
package org.orange.familylink; import org.orange.familylink.data.Settings; import org.orange.familylink.data.Settings.Role; import org.orange.familylink.fragment.LogFragment; import org.orange.familylink.fragment.NavigateFragment; import org.orange.familylink.fragment.SeekHelpFragment; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBar.Tab; /** * @author Team Orange */ public class MainActivity extends BaseActivity { private ViewPager mViewPager; private int[] mPagersOrder; @Override protected void onCreate(Bundle savedInstanceState) { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mViewPager = (ViewPager) findViewById(R.id.pager); setup(); } protected void setup() { Role role = Settings.getRole(this); if(role == Role.CARER) mPagersOrder = new int[]{R.string.log, R.string.seek_help, R.string.navigate}; else if(role == Role.CAREE) mPagersOrder = new int[]{R.string.seek_help, R.string.log, R.string.navigate}; setupViewPager(mViewPager); setupActionBar(); } /** * {@link ActionBar}{@link #onCreate(Bundle)} */ protected void setupActionBar() { ActionBar actionBar = getSupportActionBar(); // Specify that the Home/Up button should not be enabled, since there is no hierarchical parent. actionBar.setHomeButtonEnabled(false); if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { //Let navigation tabs to collapse into the main action bar actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); } // Specify that tabs should be displayed in the action bar. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create a tab listener that is called when the user changes tabs. ActionBar.TabListener tabListener = new ActionBar.TabListener() { @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} }; // Add tabs, specifying the tab's text and TabListener for(int i = 0 ;i < mPagersOrder.length ; i++) actionBar.addTab(actionBar.newTab().setText(mPagersOrder[i]).setTabListener(tabListener)); } /** * {@link ViewPager}{@link #onCreate(Bundle)} */ protected void setupViewPager(ViewPager viewPager) { mViewPager.setAdapter(new AppSectionsPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(new OnPageChangeListener(){ @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); } @Override public void onPageScrollStateChanged(int state) {} }); } /** * {@link MainActivity}{@link ViewPager}{@link PagerAdapter} * {@link MainActivity}{@link Fragment} * @see FragmentPagerAdapter * @author Team Orange */ protected class AppSectionsPagerAdapter extends FragmentPagerAdapter { public AppSectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch(mPagersOrder[position]){ case R.string.seek_help: return new SeekHelpFragment(); case R.string.log: return new LogFragment(); case R.string.navigate: return new NavigateFragment(); } throw new IllegalArgumentException("illegal position: " + position); } @Override public int getCount() { return mPagersOrder.length; } } }
package org.lightmare.utils; /** * Utility class for {@link String} operations * * @author Levan * */ public class StringUtils { public static final String EMPTY_STRING = ""; public static final char SPACE = ' '; /** * Concatenates passed {@link Object}s in one {@link String} instance * * @param parts * @return {@link String} */ public static String concat(Object... parts) { String resultText; if (ObjectUtils.available(parts)) { StringBuilder resultBuider = new StringBuilder(); for (Object part : parts) { resultBuider.append(part); } resultText = resultBuider.toString(); } else { resultText = null; } return resultText; } }
package peergos.shared.corenode; import peergos.shared.cbor.*; import peergos.shared.crypto.*; import peergos.shared.crypto.asymmetric.*; import peergos.shared.crypto.hash.*; import peergos.shared.storage.*; import peergos.shared.util.*; import java.io.*; import java.time.*; import java.util.*; import java.util.concurrent.*; import java.util.stream.*; public class UserPublicKeyLink implements Cborable{ public static final int MAX_SIZE = 2*1024*1024; public static final int MAX_USERNAME_SIZE = 64; public final PublicKeyHash owner; public final UsernameClaim claim; private final Optional<byte[]> keyChangeProof; public UserPublicKeyLink(PublicKeyHash ownerHash, UsernameClaim claim, Optional<byte[]> keyChangeProof) { this.owner = ownerHash; this.claim = claim; this.keyChangeProof = keyChangeProof; } public UserPublicKeyLink(PublicKeyHash owner, UsernameClaim claim) { this(owner, claim, Optional.empty()); } public Optional<byte[]> getKeyChangeProof() { return keyChangeProof.map(x -> Arrays.copyOfRange(x, 0, x.length)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserPublicKeyLink that = (UserPublicKeyLink) o; if (owner != null ? !owner.equals(that.owner) : that.owner != null) return false; if (claim != null ? !claim.equals(that.claim) : that.claim != null) return false; return keyChangeProof.isPresent() ? that.keyChangeProof.isPresent() && Arrays.equals(keyChangeProof.get(), that.keyChangeProof.get()) : ! that.keyChangeProof.isPresent(); } @Override public int hashCode() { int result = owner != null ? owner.hashCode() : 0; result = 31 * result + (claim != null ? claim.hashCode() : 0); result = 31 * result + keyChangeProof.map(Arrays::hashCode).orElse(0); return result; } @Override public CborObject toCbor() { Map<String, CborObject> values = new TreeMap<>(); values.put("owner", owner.toCbor()); values.put("claim", claim.toCbor()); keyChangeProof.ifPresent(proof -> values.put("keychange", new CborObject.CborByteArray(proof))); return CborObject.CborMap.build(values); } public static UserPublicKeyLink fromCbor(CborObject cbor) { if (! (cbor instanceof CborObject.CborMap)) throw new IllegalStateException("Invalid cbor for UserPublicKeyLink: " + cbor); SortedMap<CborObject, CborObject> values = ((CborObject.CborMap) cbor).values; PublicKeyHash owner = PublicKeyHash.fromCbor(values.get(new CborObject.CborString("owner"))); UsernameClaim claim = UsernameClaim.fromCbor(values.get(new CborObject.CborString("claim"))); CborObject.CborString proofKey = new CborObject.CborString("keychange"); Optional<byte[]> keyChangeProof = values.containsKey(proofKey) ? Optional.of(((CborObject.CborByteArray)values.get(proofKey)).value) : Optional.empty(); return new UserPublicKeyLink(owner, claim, keyChangeProof); } public static List<UserPublicKeyLink> createChain(SigningPrivateKeyAndPublicHash oldUser, SigningPrivateKeyAndPublicHash newUser, String username, LocalDate expiry) { // sign new claim to username, with provided expiry UsernameClaim newClaim = UsernameClaim.create(username, newUser.secret, expiry); // sign new key with old byte[] link = oldUser.secret.signMessage(newUser.publicKeyHash.serialize()); // create link from old that never expires UserPublicKeyLink fromOld = new UserPublicKeyLink(oldUser.publicKeyHash, UsernameClaim.create(username, oldUser.secret, LocalDate.MAX), Optional.of(link)); return Arrays.asList(fromOld, new UserPublicKeyLink(newUser.publicKeyHash, newClaim)); } public static class UsernameClaim implements Cborable { public final String username; public final LocalDate expiry; private final byte[] signedContents; public UsernameClaim(String username, LocalDate expiry, byte[] signedContents) { this.username = username; this.expiry = expiry; this.signedContents = signedContents; } @Override public CborObject toCbor() { return new CborObject.CborList(Arrays.asList(new CborObject.CborString(username), new CborObject.CborString(expiry.toString()), new CborObject.CborByteArray(signedContents))); } public static UsernameClaim fromCbor(CborObject cbor) { if (! (cbor instanceof CborObject.CborList)) throw new IllegalStateException("Invalid cbor for Username claim: " + cbor); String username = ((CborObject.CborString)((CborObject.CborList) cbor).value.get(0)).value; LocalDate expiry = LocalDate.parse(((CborObject.CborString)((CborObject.CborList) cbor).value.get(1)).value); byte[] signedContents = ((CborObject.CborByteArray)((CborObject.CborList) cbor).value.get(2)).value; return new UsernameClaim(username, expiry, signedContents); } public static UsernameClaim create(String username, SecretSigningKey from, LocalDate expiryDate) { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); Serialize.serialize(username, dout); Serialize.serialize(expiryDate.toString(), dout); byte[] payload = bout.toByteArray(); byte[] signed = from.signMessage(payload); return new UsernameClaim(username, expiryDate, signed); } catch (IOException e) { throw new RuntimeException(e); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UsernameClaim that = (UsernameClaim) o; if (username != null ? !username.equals(that.username) : that.username != null) return false; if (expiry != null ? !expiry.equals(that.expiry) : that.expiry != null) return false; return Arrays.equals(signedContents, that.signedContents); } @Override public int hashCode() { int result = username != null ? username.hashCode() : 0; result = 31 * result + (expiry != null ? expiry.hashCode() : 0); result = 31 * result + Arrays.hashCode(signedContents); return result; } } public static List<UserPublicKeyLink> createInitial(SigningPrivateKeyAndPublicHash signer, String username, LocalDate expiry) { UsernameClaim newClaim = UsernameClaim.create(username, signer.secret, expiry); return Collections.singletonList(new UserPublicKeyLink(signer.publicKeyHash, newClaim)); } public static CompletableFuture<List<UserPublicKeyLink>> merge(List<UserPublicKeyLink> existing, List<UserPublicKeyLink> tail, ContentAddressedStorage ipfs) { if (existing.size() == 0) return CompletableFuture.completedFuture(tail); if (!tail.get(0).owner.equals(existing.get(existing.size()-1).owner)) throw new IllegalStateException("Different keys in merge chains intersection!"); List<UserPublicKeyLink> result = Stream.concat(existing.subList(0, existing.size() - 1).stream(), tail.stream()).collect(Collectors.toList()); return validChain(result, tail.get(0).claim.username, ipfs) .thenApply(valid -> { if (! valid) throw new IllegalStateException("Invalid key chain merge!"); return result; }); } public static CompletableFuture<Boolean> validChain(List<UserPublicKeyLink> chain, String username, ContentAddressedStorage ipfs) { List<CompletableFuture<Boolean>> validities = new ArrayList<>(); for (int i=0; i < chain.size()-1; i++) validities.add(validLink(chain.get(i), chain.get(i+1).owner, username, ipfs)); return Futures.reduceAll(validities, true, (b, valid) -> valid.thenApply(res -> res && b), (a, b) -> a && b) .thenApply(valid -> { if (! valid) return valid; UserPublicKeyLink last = chain.get(chain.size() - 1); if (!validClaim(last, username)) { return false; } return true; }); } static CompletableFuture<Boolean> validLink(UserPublicKeyLink from, PublicKeyHash target, String username, ContentAddressedStorage ipfs) { if (!validClaim(from, username)) return CompletableFuture.completedFuture(true); Optional<byte[]> keyChangeProof = from.getKeyChangeProof(); if (!keyChangeProof.isPresent()) return CompletableFuture.completedFuture(false); return ipfs.getSigningKey(from.owner).thenApply(ownerKeyOpt -> { if (! ownerKeyOpt.isPresent()) return false; PublicKeyHash targetKey = PublicKeyHash.fromCbor(CborObject.fromByteArray(ownerKeyOpt.get().unsignMessage(keyChangeProof.get()))); if (!Arrays.equals(targetKey.serialize(), target.serialize())) return false; return true; }); } static boolean validClaim(UserPublicKeyLink from, String username) { if (username.contains(" ") || username.contains("\t") || username.contains("\n")) return false; if (username.length() > MAX_USERNAME_SIZE) return false; if (!from.claim.username.equals(username)) return false; return true; } public static boolean isExpiredClaim(UserPublicKeyLink from) { return from.claim.expiry.isBefore(LocalDate.now()); } }
package org.orange.familylink.data; import org.orange.familylink.data.MessageLogRecord.Status; import org.orange.familylink.database.Contract; import org.orange.familylink.database.Contract.Messages; import org.orange.familylink.util.Objects; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.PhoneNumberUtils; import android.util.Log; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; /** * * <p><em>SettersMethod chaining</em></p> * @author Team Orange */ public abstract class Message implements Cloneable{ /** * * @author Team Orange */ public abstract static class Code { /** * * @see Extra.Inform */ public static final int INFORM = 0x000; /** * * @see Extra.Command */ public static final int COMMAND = 0x100; public abstract static class Extra { /** * {@link Code#INFORM} * @author Team Orange * @see Extra */ public abstract static class Inform { public static final int RESPONSE = 0x01; public static final int PULSE = 0x02; public static final int URGENT = 0x04; /** * code{@link #RESPONSE} * @param code code * @return code{@link Code#INFORM}{@link #RESPONSE}truefalse */ public static boolean hasSetRespond(int code) { if(!isInform(code)) return false; return (code & RESPONSE) == RESPONSE; } /** * code{@link #PULSE} * @param code code * @return code{@link Code#INFORM}{@link #PULSE}truefalse */ public static boolean hasSetPulse(int code) { if(!isInform(code)) return false; return (code & PULSE) == PULSE; } /** * code{@link #URGENT} * @param code code * @return code{@link Code#INFORM}{@link #URGENT}truefalse */ public static boolean hasSetUrgent(int code) { if(!isInform(code)) return false; return (code & URGENT) == URGENT; } } /** * {@link Code#COMMAND} * @author Team Orange * @see Extra */ public abstract static class Command { public static final int ECHO = 0x01; public static final int LOCATE_NOW = 0x02; /** * code{@link #ECHO} * @param code code * @return code{@link Code#COMMAND}{@link #ECHO}truefalse */ public static boolean hasSetEcho(int code) { if(!isCommand(code)) return false; return (code & ECHO) == ECHO; } /** * code{@link #LOCATE_NOW} * @param code code * @return code{@link Code#COMMAND}{@link #LOCATE_NOW}truefalse */ public static boolean hasSetLocateNow(int code) { if(!isCommand(code)) return false; return (code & LOCATE_NOW) == LOCATE_NOW; } } } /** {@link Extra} */ public static final int EXTRA_BITS = 0xff; /** {@link Code} */ public static final int MINIMUM = INFORM; /** {@link Code} */ public static final int MAXIMUM = COMMAND | EXTRA_BITS; /** * code * @param code * @return truefalse */ public static boolean isLegalCode (int code) { if(code >= MINIMUM && code <= MAXIMUM) return true; else return false; } /** * code{@link #INFORM} code * @param code code * @return {@link #INFORM}truefalse */ public static boolean isInform(int code) { if(!isLegalCode(code)) return false; return (code & (~EXTRA_BITS)) == INFORM; } /** * code{@link #COMMAND} code * @param code code * @return {@link #COMMAND}truefalse */ public static boolean isCommand(int code) { if(!isLegalCode(code)) return false; return (code & (~EXTRA_BITS)) == COMMAND; } } /** * * @see Code */ private Integer code = null; private String body = null; /** * * <p> * Tips * <pre><code>new Message().setBody("Hello") * .setCode(Message.Code.INFORM | Message.Code.Extra.Inform.PULSE);</code></pre> */ public Message() { super(); } /** * * @return * @see Code */ public Integer getCode() { return code; } /** * * @param code * @return this * @see Code */ public Message setCode(Integer code) { if((code != null) && (!Code.isLegalCode(code))) throw new IllegalArgumentException("Illegal Code :" + code); this.code = code; return this; } /** * * @return */ public String getBody() { return body; } /** * * @param body * @return this */ public Message setBody(String body) { this.body = body; return this; } /** * Json * @return Json * @see Gson#toJson(Object) */ public String toJson() { return new Gson().toJson(this); } /** * Json * @param json Json * @return this * @throws JsonSyntaxException Json */ public Message fromJson(String json) { Message m = new Gson().fromJson(json, getClass()); setCode(m.getCode()).setBody(m.getBody()); return this; } public Uri sendAndSave(Context context, Long contactId , String dest) { return sendAndSave(context, contactId, dest, Settings.getPassword(context)); } public Uri sendAndSave(Context context, Long contactId , String dest, String password) { if(dest == null || dest.isEmpty()) throw new IllegalArgumentException("dest address shouldn't be empty"); Uri newUri = saveMessage(context, contactId, dest, Status.SENDING); if (Code.isCommand(getCode())) beforeSendCommandMessage(context, newUri); send(context, newUri, dest, password); return newUri; } /** * Command MessagebodyID * @param messageUri {@link Message}{@link Uri} */ private void beforeSendCommandMessage(Context context, Uri messageUri) { if (getBody() != null) throw new IllegalStateException("have setBody"); final long id = ContentUris.parseId(messageUri); CommandMessageBody body = new CommandMessageBody(); body.setId(id); setBody(body.toJson()); // Content Provider ContentValues message = new ContentValues(); message.put(Messages.COLUMN_NAME_TIME, System.currentTimeMillis()); message.put(Messages.COLUMN_NAME_BODY, getBody()); final int rowsUpdated = context.getContentResolver().update( ContentUris.withAppendedId(Messages.MESSAGES_URI, id), message, null, null); assert rowsUpdated == 1; } /** * * @param context * @param messageUri {@link Uri} * @param dest * @param password */ public abstract void send(Context context, Uri messageUri, String dest, String password); /** * {@link Message} * <p> * <strong></strong><em></em> UI * @param context * @param receivedMessage * @param srcAddr * @return {@link Uri} * @throws JsonSyntaxException receivedMessage * @see #sendAndSave(Context, Long, String) */ public Uri receiveAndSave(Context context, String receivedMessage, String srcAddr) { // remove spaces and dashes from destination number // (e.g. "801 555 1212" -> "8015551212") // (e.g. "+8211-123-4567" -> "+82111234567") srcAddr = PhoneNumberUtils.stripSeparators(srcAddr); return receiveAndSave(context, receivedMessage, queryContactId(context, srcAddr), srcAddr, Settings.getPassword(context)); } /** * {@link Message} * <p> * <strong></strong><em></em> UI * @param context * @param receivedMessage * @param contactId ID * @param srcAddr * @param password * @return {@link Uri} * @throws JsonSyntaxException receivedMessage * @see #sendAndSave(Context, Long, String, String) * @see #receive(String, String) */ public Uri receiveAndSave(Context context, String receivedMessage, Long contactId, String srcAddr, String password) { receive(receivedMessage, password); return saveMessage(context, contactId, srcAddr, Status.UNREAD); } protected Long queryContactId(Context context, String contactAddress) { Long contactId = null; Uri baseUri = Contract.Contacts.CONTACTS_URI; String[] projection = {Contract.Contacts._ID}; String selection = Contract.Contacts.COLUMN_NAME_PHONE_NUMBER + " = ?"; contactAddress = removePrefix(contactAddress); String[] args = {contactAddress}; Log.w("cont", "" + contactAddress); Cursor c = context.getContentResolver() .query(baseUri, projection, selection, args, null); if(c.moveToFirst()) { int column = c.getColumnIndex(Contract.Contacts._ID); if(!c.isNull(column)) contactId = c.getLong(column); } return contactId; } private String removePrefix(String contactAddress){ String newContactAddress = null; int phoneDigits = 11; final int PLUS_SIGN_POSITION = 0; if(contactAddress.charAt(PLUS_SIGN_POSITION) == '+'){ int prefixDigits = contactAddress.length() - phoneDigits; newContactAddress = contactAddress.substring(prefixDigits); }else{ newContactAddress = contactAddress; } return newContactAddress; } /** * {@link Message} * @param receivedMessage * @param password * @throws JsonSyntaxException receivedMessage */ public abstract void receive(String receivedMessage, String password); /** * {@link Uri} * @param context * @param contactId ID * @param address * @param status * @return {@link Uri} */ protected Uri saveMessage(Context context, Long contactId , String address, Status status) { Log.w("smsfamily", "sms5"); // Content Provider ContentValues newMessage = new ContentValues(); newMessage.put(Messages.COLUMN_NAME_CONTACT_ID, contactId); newMessage.put(Messages.COLUMN_NAME_ADDRESS, address); newMessage.put(Messages.COLUMN_NAME_TIME, System.currentTimeMillis()); newMessage.put(Messages.COLUMN_NAME_STATUS, status.name()); newMessage.put(Messages.COLUMN_NAME_BODY, getBody()); newMessage.put(Messages.COLUMN_NAME_CODE, getCode()); return context.getContentResolver().insert(Messages.MESSAGES_URI, newMessage); } @Override public Message clone() { Message clone = null; try { clone = (Message) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("can't clone Message", e); } return clone; } /** * * <p><em>{@link #isSameClass(Object)} * {@link Objects#compare(Object, Object)}{@link String}</em></p> * @param o * @return truefalse */ @Override public boolean equals(Object o) { if(o == null) return false; else if(!isSameClass(o)) return false; else { Message other = (Message) o; return Objects.compare(code, other.code) && Objects.compare(body, other.body); } } /** * {@link #mDefaultValue} * @param o * @return {@link #mDefaultValue}truefalse */ protected boolean isSameClass(Object o) { return getClass() == o.getClass(); } }
package org.pentaho.ui.xul.gwt.tags; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.components.XulMenuitem; import org.pentaho.ui.xul.components.XulMenuseparator; import org.pentaho.ui.xul.containers.XulMenubar; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer; import org.pentaho.ui.xul.gwt.GwtXulHandler; import org.pentaho.ui.xul.gwt.GwtXulParser; import org.pentaho.ui.xul.stereotype.Bindable; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.MenuItem; public class GwtMenubar extends AbstractGwtXulContainer implements XulMenubar { private String menubarName; private MenuBar menubar; private boolean loaded; private boolean vertical = true; public static void register() { GwtXulParser.registerHandler("menubar", new GwtXulHandler() { public Element newInstance() { return new GwtMenubar(); } }); } public GwtMenubar() { super("menubar"); } public GwtMenubar(String tagName) { super(tagName); } @Override public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) { this.setHorizontal("vertical".equalsIgnoreCase(srcEle.getAttribute("layout"))); menubar = new MenuBar(vertical); this.setLabel(srcEle.getAttribute("label")); setManagedObject(menubar); // init AFTER we set the managed object and we get "id" set for us super.init(srcEle, container); } public void setLabel(String label) { menubar.setTitle(label); } public String getLabel() { return menubar.getTitle(); } public boolean isHorizontal() { return vertical; } public void setHorizontal(boolean horizontal) { this.vertical = horizontal; } public String getMenubarName() { return menubarName; } public void setMenubarName(String name) { this.menubarName = name; } @Bindable public void setVisible(boolean visible) { this.visible = visible; menubar.getElement().getStyle().setProperty("display", (this.visible) ? "" : "none"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (getParent() instanceof GwtMenubar) { ((MenuBar)getParent().getManagedObject()).clearItems(); ((GwtMenubar)getParent()).layout(); } } @Override public void layout() { for (XulComponent c : this.getChildNodes()) { add(c); } if (!loaded) { loaded = true; } } private void add(XulComponent c) { if (c instanceof XulMenuitem) { MenuItem item = (MenuItem) c.getManagedObject(); menubar.addItem(item); } else if (c instanceof XulMenuseparator) { menubar.addSeparator(); } else if (c instanceof XulMenubar) { if (c.isVisible()) { MenuBar bar = (MenuBar) c.getManagedObject(); MenuItem submenu = new MenuItem(bar.getTitle(), bar); menubar.addItem(submenu); } } } @Override public void addChild(Element element) { super.addChild(element); if (loaded == true) { menubar.clearItems(); this.layout(); } } @Override public void addChildAt(Element element, int idx) { super.addChildAt(element, idx); if (loaded == true) { menubar.clearItems(); this.layout(); } } @Override public void removeChild(Element element) { super.removeChild(element); XulComponent child = (XulComponent) element; if (child instanceof XulMenuitem) { menubar.removeItem((MenuItem) child.getManagedObject()); } } public void adoptAttributes(XulComponent component) { } }
package org.mastodon.trackmate; import java.util.Map; import org.mastodon.detection.DetectionUtil; import org.mastodon.detection.mamut.DoGDetectorMamut; import org.mastodon.detection.mamut.SpotDetectorOp; import org.mastodon.linking.LinkingUtils; import org.mastodon.linking.mamut.SimpleSparseLAPLinkerMamut; import org.mastodon.linking.mamut.SpotLinkerOp; import bdv.spimdata.SpimDataMinimal; public class Settings { public final Values values = new Values(); public Settings detector( final Class< ? extends SpotDetectorOp > detector ) { values.detector = detector; return this; } public Settings detectorSettings( final Map< String, Object > detectorSettings ) { values.detectorSettings = detectorSettings; return this; } public Settings linker( final Class< ? extends SpotLinkerOp > linker ) { values.linker = linker; return this; } public Settings linkerSettings( final Map< String, Object > linkerSettings ) { values.linkerSettings = linkerSettings; return this; } public Settings spimData( final SpimDataMinimal spimData ) { values.spimData = spimData; return this; } public static class Values { private SpimDataMinimal spimData = null; private Class< ? extends SpotDetectorOp > detector = DoGDetectorMamut.class; private Map< String, Object > detectorSettings = DetectionUtil.getDefaultDetectorSettingsMap(); private Class< ? extends SpotLinkerOp > linker = SimpleSparseLAPLinkerMamut.class; private Map< String, Object > linkerSettings = LinkingUtils.getDefaultLAPSettingsMap(); public Class< ? extends SpotDetectorOp > getDetector() { return detector; } public Map< String, Object > getDetectorSettings() { return detectorSettings; } public Class< ? extends SpotLinkerOp > getLinker() { return linker; } public Map< String, Object > getLinkerSettings() { return linkerSettings; } public SpimDataMinimal getSpimData() { return spimData; } } }
package cz.metacentrum.perun.rpc; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import cz.metacentrum.perun.cabinet.api.CabinetManager; import cz.metacentrum.perun.cabinet.model.Category; import cz.metacentrum.perun.cabinet.model.Publication; import cz.metacentrum.perun.cabinet.model.Thanks; import cz.metacentrum.perun.core.api.PerunClient; import cz.metacentrum.perun.oidc.OIDC; import cz.metacentrum.perun.registrar.model.Application; import cz.metacentrum.perun.voot.VOOT; import org.springframework.web.context.support.WebApplicationContextUtils; import cz.metacentrum.perun.controller.service.GeneralServiceManager; import cz.metacentrum.perun.controller.service.PropagationStatsReader; import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.AttributeDefinition; import cz.metacentrum.perun.core.api.AttributesManager; import cz.metacentrum.perun.core.api.AuditMessagesManager; import cz.metacentrum.perun.core.api.BanOnFacility; import cz.metacentrum.perun.core.api.BanOnResource; import cz.metacentrum.perun.core.api.DatabaseManager; import cz.metacentrum.perun.core.api.Destination; import cz.metacentrum.perun.core.api.ExtSource; import cz.metacentrum.perun.core.api.ExtSourcesManager; import cz.metacentrum.perun.core.api.FacilitiesManager; import cz.metacentrum.perun.core.api.Facility; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.GroupsManager; import cz.metacentrum.perun.core.api.Host; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.MembersManager; import cz.metacentrum.perun.core.api.Owner; import cz.metacentrum.perun.core.api.OwnersManager; import cz.metacentrum.perun.core.api.Perun; import cz.metacentrum.perun.core.api.PerunPrincipal; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.RTMessagesManager; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.ResourcesManager; import cz.metacentrum.perun.core.api.Searcher; import cz.metacentrum.perun.core.api.SecurityTeam; import cz.metacentrum.perun.core.api.SecurityTeamsManager; import cz.metacentrum.perun.core.api.Service; import cz.metacentrum.perun.core.api.ServicesManager; import cz.metacentrum.perun.core.api.ServicesPackage; import cz.metacentrum.perun.core.api.User; import cz.metacentrum.perun.core.api.UserExtSource; import cz.metacentrum.perun.core.api.UsersManager; import cz.metacentrum.perun.core.api.Vo; import cz.metacentrum.perun.core.api.VosManager; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.PerunException; import cz.metacentrum.perun.core.api.exceptions.RpcException; import cz.metacentrum.perun.notif.entities.PerunNotifObject; import cz.metacentrum.perun.notif.entities.PerunNotifReceiver; import cz.metacentrum.perun.notif.entities.PerunNotifRegex; import cz.metacentrum.perun.notif.entities.PerunNotifTemplate; import cz.metacentrum.perun.notif.entities.PerunNotifTemplateMessage; import cz.metacentrum.perun.notif.managers.PerunNotifNotificationManager; import cz.metacentrum.perun.registrar.RegistrarManager; import cz.metacentrum.perun.rpc.deserializer.Deserializer; import cz.metacentrum.perun.taskslib.model.ExecService; public class ApiCaller { private AuditMessagesManager auditMessagesManager = null; private VosManager vosManager = null; private MembersManager membersManager = null; private UsersManager usersManager = null; private GroupsManager groupsManager = null; private ExtSourcesManager extSourcesManager = null; private ServicesManager servicesManager = null; private FacilitiesManager facilitiesManager = null; private DatabaseManager databaseManager = null; private ResourcesManager resourcesManager = null; private AttributesManager attributesManager = null; private OwnersManager ownersManager = null; private GeneralServiceManager generalServiceManager; private RTMessagesManager rtMessagesManager = null; private SecurityTeamsManager securityTeamsManager = null; private PropagationStatsReader propagationStatsReader; private Searcher searcher = null; private CabinetManager cabinetManager; private RegistrarManager registrarManager; private PerunNotifNotificationManager notificationManager; private VOOT vootManager = null; private OIDC oidcManager = null; private final static String RPCPRINCIPAL = "perunRpc"; private final PerunSession session; private final PerunSession rpcSession; public AuditMessagesManager getAuditMessagesManager() { if (auditMessagesManager == null){ auditMessagesManager = rpcSession.getPerun().getAuditMessagesManager(); } return auditMessagesManager; } public RTMessagesManager getRTMessagesManager() { if (rtMessagesManager == null) { rtMessagesManager = rpcSession.getPerun().getRTMessagesManager(); } return rtMessagesManager; } public SecurityTeamsManager getSecurityTeamsManager() { if (securityTeamsManager == null) { securityTeamsManager = rpcSession.getPerun().getSecurityTeamsManager(); } return securityTeamsManager; } public Searcher getSearcher() { if (searcher == null) { searcher = rpcSession.getPerun().getSearcher(); } return searcher; } public VosManager getVosManager() { if (vosManager == null) { vosManager = rpcSession.getPerun().getVosManager(); } return vosManager; } public MembersManager getMembersManager() { if (membersManager == null) { membersManager = rpcSession.getPerun().getMembersManager(); } return membersManager; } public UsersManager getUsersManager() { if (usersManager == null) { usersManager = rpcSession.getPerun().getUsersManager(); } return usersManager; } public GroupsManager getGroupsManager() { if (groupsManager == null) { groupsManager = rpcSession.getPerun().getGroupsManager(); } return groupsManager; } public ExtSourcesManager getExtSourcesManager() { if (extSourcesManager == null) { extSourcesManager = rpcSession.getPerun().getExtSourcesManager(); } return extSourcesManager; } public ServicesManager getServicesManager() { if (servicesManager == null) { servicesManager = rpcSession.getPerun().getServicesManager(); } return servicesManager; } public FacilitiesManager getFacilitiesManager() { if (facilitiesManager == null) { facilitiesManager = rpcSession.getPerun().getFacilitiesManager(); } return facilitiesManager; } public DatabaseManager getDatabaseManager() { if (databaseManager == null) { databaseManager = rpcSession.getPerun().getDatabaseManager(); } return databaseManager; } public ResourcesManager getResourcesManager() { if (resourcesManager == null) { resourcesManager = rpcSession.getPerun().getResourcesManager(); } return resourcesManager; } public AttributesManager getAttributesManager() { if (attributesManager == null) { attributesManager = rpcSession.getPerun().getAttributesManager(); } return attributesManager; } public OwnersManager getOwnersManager() { if (ownersManager == null) { ownersManager = rpcSession.getPerun().getOwnersManager(); } return ownersManager; } public GeneralServiceManager getGeneralServiceManager() { return generalServiceManager; } public PropagationStatsReader getPropagationStatsReader() { return propagationStatsReader; } public CabinetManager getCabinetManager() { return cabinetManager; } public RegistrarManager getRegistrarManager() { return registrarManager; } public PerunNotifNotificationManager getNotificationManager() { return notificationManager; } public VOOT getVOOTManager(){ return vootManager; } public OIDC getOIDCManager(){ return oidcManager; } public Vo getVoById(int id) throws PerunException { return getVosManager().getVoById(rpcSession, id); } public Member getMemberById(int id) throws PerunException { return getMembersManager().getMemberById(rpcSession, id); } public User getUserById(int id) throws PerunException { return getUsersManager().getUserById(rpcSession, id); } public Group getGroupById(int id) throws PerunException { return getGroupsManager().getGroupById(rpcSession, id); } public ExtSource getExtSourceById(int id) throws PerunException { return getExtSourcesManager().getExtSourceById(rpcSession, id); } public Service getServiceById(int id) throws PerunException { return getServicesManager().getServiceById(rpcSession, id); } public ServicesPackage getServicesPackageById(int id) throws PerunException { return getServicesManager().getServicesPackageById(rpcSession, id); } public Facility getFacilityById(int id) throws PerunException { return getFacilitiesManager().getFacilityById(rpcSession, id); } public Facility getFacilityByName(String name) throws PerunException { return getFacilitiesManager().getFacilityByName(rpcSession, name); } public Resource getResourceById(int id) throws PerunException { return getResourcesManager().getResourceById(rpcSession, id); } public Host getHostById(int id) throws PerunException { return getFacilitiesManager().getHostById(rpcSession, id); } public Owner getOwnerById(int id) throws PerunException { return getOwnersManager().getOwnerById(rpcSession, id); } public Application getApplicationById(int id) throws PerunException { return getRegistrarManager().getApplicationById(rpcSession, id); } public SecurityTeam getSecurityTeamById(int id) throws PerunException { return getSecurityTeamsManager().getSecurityTeamById(rpcSession, id); } public BanOnFacility getBanOnFacility(int id) throws PerunException { return getFacilitiesManager().getBanById(rpcSession, id); } public BanOnResource getBanOnResource(int id) throws PerunException { return getResourcesManager().getBanById(rpcSession, id); } public AttributeDefinition getAttributeDefinitionById(int id) throws PerunException { return getAttributesManager().getAttributeDefinitionById(rpcSession, id); } public Attribute getAttributeById(Facility facility, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, facility, id); } public Attribute getAttributeById(Vo vo, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, vo, id); } public Attribute getAttributeById(Resource resource, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, resource, id); } public Attribute getAttributeById(Resource resource, Member member, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, resource, member, id); } public Attribute getAttributeById(Member member, Group group, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, member, group, id); } public Attribute getAttributeById(Host host, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, host, id); } public Attribute getAttributeById(Group group, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, group, id); } public Attribute getAttributeById(Resource resource, Group group, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, resource, group, id); } public Attribute getAttributeById(User user, int id) throws PerunException { return getAttributesManager().getAttributeById(rpcSession, user, id); } public Attribute getAttributeById(Member member, int id) throws PerunException { return getAttributesManager().getAttributeById(session, member, id); } public Attribute getAttributeById(Facility facility, User user, int id) throws PerunException { return getAttributesManager().getAttributeById(session, facility, user, id); } public Attribute getAttributeById(UserExtSource ues, int id) throws PerunException { return getAttributesManager().getAttributeById(session, ues, id); } public UserExtSource getUserExtSourceById(int id) throws PerunException { return getUsersManager().getUserExtSourceById(rpcSession, id); } public ExecService getExecServiceById(int id) throws PerunException { return getGeneralServiceManager().getExecService(rpcSession, id); } public PerunNotifObject getPerunNotifObjectById(int id) throws PerunException { return getNotificationManager().getPerunNotifObjectById(id); } public PerunNotifReceiver getPerunNotifReceiverById(int id) throws PerunException { return getNotificationManager().getPerunNotifReceiverById(rpcSession, id); } public PerunNotifRegex getPerunNotifRegexById(int id) throws PerunException { return getNotificationManager().getPerunNotifRegexById(rpcSession, id); } public PerunNotifTemplateMessage getPerunNotifTemplateMessageById(int id) throws PerunException { return getNotificationManager().getPerunNotifTemplateMessageById(rpcSession, id); } public PerunNotifTemplate getPerunNotifTemplateById(int id) throws PerunException { return getNotificationManager().getPerunNotifTemplateById(rpcSession, id); } public Destination getDestination(String destination, String type) throws PerunException { Destination d = new Destination(); d.setDestination(destination); d.setType(type); return d; } public Destination getDestination(String destination, String type, String propagationType) throws PerunException { Destination d = new Destination(); d.setDestination(destination); d.setType(type); d.setPropagationType(propagationType); return d; } public List<Object> convertGroupsWithHierarchy(Group group, Map<Group, Object> groups) { if (group != null) { List<Object> groupHierarchy = new ArrayList<Object>(); groupHierarchy.add(0, group); if (groups != null) { for (Group subGroup: groups.keySet()) { groupHierarchy.add(convertGroupsWithHierarchy(subGroup, (Map<Group, Object>) groups.get(subGroup))); } } return groupHierarchy; } return null; } public Category getCategoryById(int id) throws PerunException { return getCabinetManager().getCategoryById(id); } public Thanks getThanksById(int id) throws PerunException { return getCabinetManager().getThanksById(id); } public Publication getPublicationById(int id) throws PerunException { return getCabinetManager().getPublicationById(id); } public ApiCaller(ServletContext context, PerunPrincipal perunPrincipal, PerunClient client) throws InternalErrorException { Perun perun = WebApplicationContextUtils.getWebApplicationContext(context).getBean("perun", Perun.class); PerunPrincipal rpcPrincipal = new PerunPrincipal(RPCPRINCIPAL, ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL); this.rpcSession = perun.getPerunSession(rpcPrincipal, new PerunClient()); // Initialize serviceManager this.generalServiceManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("generalServiceManager", GeneralServiceManager.class); // Initialize PropagationStatsReader this.propagationStatsReader = WebApplicationContextUtils.getWebApplicationContext(context).getBean("propagationStatsReader", PropagationStatsReader.class); // Initialize CabinetManager this.cabinetManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("cabinetManager", CabinetManager.class); // Initialize RegistrarManager this.registrarManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("registrarManager", RegistrarManager.class); // Initialize Notifications this.notificationManager = WebApplicationContextUtils.getWebApplicationContext(context).getBean("perunNotifNotificationManager", PerunNotifNotificationManager.class); // Initialize VOOT Manager this.vootManager = new VOOT(); // Initialize OIDC Manager this.oidcManager = new OIDC(); this.session = perun.getPerunSession(perunPrincipal, client); } public PerunSession getSession() { return session; } private boolean stateChanging = true; public boolean isStateChanging() { return stateChanging; } public void setStateChanging(boolean stateChanging) { this.stateChanging = stateChanging; } public void stateChangingCheck() throws RpcException { if (!stateChanging) { throw new RpcException(RpcException.Type.STATE_CHANGING_CALL, "This is a state changing operation. Please use HTTP POST request."); } } public Object call(String managerName, String methodName, Deserializer parms) throws PerunException { return PerunManager.call(managerName, methodName, this, parms); } }
package org.minimalj.frontend.form; import java.lang.reflect.Method; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.minimalj.frontend.Frontend; import org.minimalj.frontend.Frontend.FormContent; import org.minimalj.frontend.Frontend.IComponent; import org.minimalj.frontend.form.element.BigDecimalFormElement; import org.minimalj.frontend.form.element.CheckBoxFormElement; import org.minimalj.frontend.form.element.CodeFormElement; import org.minimalj.frontend.form.element.Enable; import org.minimalj.frontend.form.element.EnumFormElement; import org.minimalj.frontend.form.element.EnumSetFormElement; import org.minimalj.frontend.form.element.FormElement; import org.minimalj.frontend.form.element.FormElement.FormElementListener; import org.minimalj.frontend.form.element.IntegerFormElement; import org.minimalj.frontend.form.element.LocalDateFormElement; import org.minimalj.frontend.form.element.LocalTimeFormElement; import org.minimalj.frontend.form.element.LongFormElement; import org.minimalj.frontend.form.element.StringFormElement; import org.minimalj.frontend.form.element.TextFormElement; import org.minimalj.frontend.form.element.TypeUnknownFormElement; import org.minimalj.model.Code; import org.minimalj.model.Keys; import org.minimalj.model.annotation.Enabled; import org.minimalj.model.properties.Properties; import org.minimalj.model.properties.PropertyInterface; import org.minimalj.model.validation.ValidationMessage; import org.minimalj.util.CloneHelper; import org.minimalj.util.ExceptionUtils; import org.minimalj.util.mock.Mocking; import org.minimalj.util.resources.Resources; public class Form<T> { private static Logger logger = Logger.getLogger(Form.class.getSimpleName()); protected final boolean editable; private final ResourceBundle resourceBundle; private final int columns; private final FormContent formContent; private final LinkedHashMap<PropertyInterface, FormElement<?>> elements = new LinkedHashMap<PropertyInterface, FormElement<?>>(); private final FormPanelChangeListener formPanelChangeListener = new FormPanelChangeListener(); private final FormPanelActionListener formPanelActionListener = new FormPanelActionListener(); private FormChangeListener<T> changeListener; private boolean changeFromOutsite; private final Map<PropertyInterface, List<PropertyInterface>> dependencies = new HashMap<>(); @SuppressWarnings("rawtypes") private final Map<PropertyInterface, Map<PropertyInterface, PropertyUpdater>> propertyUpdater = new HashMap<>(); private T object; public Form() { this(true); } public Form(boolean editable) { this(editable, 1); } public Form(int columns) { this(true, columns); } public Form(boolean editable, int columns) { this(null, editable, columns); } public Form(ResourceBundle resourceBundle, boolean editable) { this(resourceBundle, editable, 1); } public Form(ResourceBundle resourceBundle, boolean editable, int columns) { this.resourceBundle = resourceBundle != null ? resourceBundle : Resources.getResourceBundle(); this.editable = editable; this.columns = columns; this.formContent = Frontend.getInstance().createFormContent(columns, getColumnWidthPercentage()); } protected int getColumnWidthPercentage() { return 100; } // Methods to create the form public FormContent getContent() { return formContent; } public FormElement<?> createElement(Object key) { FormElement<?> element; PropertyInterface property; if (key == null) { throw new NullPointerException("Key must not be null"); } else if (key instanceof FormElement) { element = (FormElement<?>) key; property = element.getProperty(); if (property == null) throw new IllegalArgumentException(IComponent.class.getSimpleName() + " has no key"); } else { property = Keys.getProperty(key); // if ths happens for a getter-method there is the special line missing if (property == null) throw new IllegalArgumentException("" + key); element = createElement(property); } return element; } protected FormElement<?> createElement(PropertyInterface property) { Class<?> fieldClass = property.getClazz(); boolean editable = this.editable && !property.isFinal(); if (fieldClass == String.class) { return editable ? new StringFormElement(property) : new TextFormElement(property); } else if (fieldClass == Boolean.class) { return new CheckBoxFormElement(property, editable); } else if (fieldClass == Integer.class) { return new IntegerFormElement(property, editable); } else if (fieldClass == Long.class) { return new LongFormElement(property, editable); } else if (fieldClass == BigDecimal.class) { return new BigDecimalFormElement(property, editable); } else if (fieldClass == LocalDate.class) { return new LocalDateFormElement(property, editable); } else if (fieldClass == LocalTime.class) { return new LocalTimeFormElement(property, editable); } else if (Code.class.isAssignableFrom(fieldClass)) { return editable ? new CodeFormElement(property) : new TextFormElement(property); } else if (Enum.class.isAssignableFrom(fieldClass)) { return editable ? new EnumFormElement(property) : new TextFormElement(property); } else if (fieldClass == Set.class) { return new EnumSetFormElement(property, editable); } logger.severe("No FormElement could be created for: " + property.getName() + " of class " + fieldClass.getName()); return new TypeUnknownFormElement(property); } public void line(Object key) { FormElement<?> element = createElement(key); add(element, columns); } public void line(Object... keys) { if (keys.length > columns) throw new IllegalArgumentException("More keys than specified in the constructor"); int span = columns / keys.length; int rest = columns; for (int i = 0; i<keys.length; i++) { Object key = keys[i]; FormElement<?> element = createElement(key); add(element, i < keys.length - 1 ? span : rest); rest = rest - span; } } private void add(FormElement<?> element, int span) { String captionText = caption(element); formContent.add(captionText, element.getComponent(), span); registerNamedElement(element); } public void text(String text) { IComponent label = Frontend.getInstance().createLabel(text); formContent.add(label); } public void addTitle(String text) { IComponent label = Frontend.getInstance().createTitle(text); formContent.add(label); } /** * Declares that if the property with fromKey changes all * the properties with toKey could change. This is normally used * if the to property is a getter that calculates something that * depends on the fromKey in a simple way. * * @param fromKey * @param toKey */ public void addDependecy(Object fromKey, Object... toKey) { PropertyInterface fromProperty = Keys.getProperty(fromKey); if (!dependencies.containsKey(fromProperty)) { dependencies.put(fromProperty, new ArrayList<PropertyInterface>()); } List<PropertyInterface> list = dependencies.get(fromProperty); for (Object key : toKey) { list.add(Keys.getProperty(key)); } } /** * Declares that if the property with fromKey changes the specified * updater should be called and after its return the toKey property * could have changed.<p> * * This is used if there is a more complex relation between two properities. * * @param fromKey * @param updater * @param toKey */ @SuppressWarnings("rawtypes") public <FROM, TO> void addDependecy(FROM fromKey, PropertyUpdater<FROM, TO, T> updater, TO toKey) { PropertyInterface fromProperty = Keys.getProperty(fromKey); if (!propertyUpdater.containsKey(fromProperty)) { propertyUpdater.put(fromProperty, new HashMap<PropertyInterface, PropertyUpdater>()); } PropertyInterface toProperty = Keys.getProperty(toKey); propertyUpdater.get(fromProperty).put(toProperty, updater); addDependecy(fromKey, toKey); } public interface PropertyUpdater<FROM, TO, EDIT_OBJECT> { /** * * @param input The new value of the property that has changed * @param copyOfEditObject The current object of the This reference should <b>not</b> be changed. * It should be treated as a read only version or a copy of the object. * It's probably not a real copy as it is to expensive to copy the object for every call. * @return The new value the updater wants to set to the toKey property */ public TO update(FROM input, EDIT_OBJECT copyOfEditObject); } private void registerNamedElement(FormElement<?> field) { elements.put(field.getProperty(), field); field.setChangeListener(formPanelChangeListener); } public final void mock() { changeFromOutsite = true; try { fillWithDemoData(object); } catch (Exception x) { logger.log(Level.SEVERE, "Fill with demo data failed", x); } finally { readValueFromObject(); changeFromOutsite = false; } } protected void fillWithDemoData(T object) { for (FormElement<?> field : elements.values()) { PropertyInterface property = field.getProperty(); if (field instanceof Mocking) { Mocking demoEnabledElement = (Mocking) field; demoEnabledElement.mock(); property.setValue(object, field.getValue()); } } } private String caption(FormElement<?> field) { return Resources.getObjectFieldName(resourceBundle, field.getProperty()); } /** * * @return Collection provided by a LinkedHashMap so it will be a ordered set */ public Collection<PropertyInterface> getProperties() { return elements.keySet(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void set(PropertyInterface property, Object value) { FormElement element = elements.get(property); try { element.setValue(value); } catch (Exception x) { ExceptionUtils.logReducedStackTrace(logger, x); } } private void setValidationMessage(PropertyInterface property, List<String> validationMessages) { FormElement<?> field = elements.get(property); formContent.setValidationMessages(field.getComponent(), validationMessages); } public void setObject(T object) { if (editable && changeListener == null) throw new IllegalStateException("Listener has to be set on a editable Form"); changeFromOutsite = true; this.object = object; readValueFromObject(); changeFromOutsite = false; } private void readValueFromObject() { for (PropertyInterface property : getProperties()) { Object propertyValue = property.getValue(object); set(property, propertyValue); } updateEnable(); } private String getName(FormElement<?> field) { PropertyInterface property = field.getProperty(); return property.getName(); } public void setChangeListener(FormChangeListener<T> changeListener) { if (changeListener == null) throw new IllegalArgumentException("Listener on Form must not be null"); if (this.changeListener != null) throw new IllegalStateException("Listener on Form cannot be changed"); this.changeListener = changeListener; } public interface FormChangeListener<S> { public void changed(PropertyInterface property, Object newValue); public void commit(); } private class FormPanelChangeListener implements FormElementListener { @Override public void valueChanged(FormElement<?> changedField) { if (changeFromOutsite) return; if (changeListener == null) { logger.severe("Editable Form must have a listener"); return; } logger.fine("ChangeEvent from " + getName(changedField)); PropertyInterface property = changedField.getProperty(); Object newValue = changedField.getValue(); // Call updaters before set the new value (so they also can read the old value) executeUpdater(property, newValue); refreshDependendFields(property); property.setValue(object, newValue); // update enable/disable fields updateEnable(); changeListener.changed(property, newValue); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void refreshDependendFields(PropertyInterface property) { if (dependencies.containsKey(property)) { List<PropertyInterface> dependendProperties = dependencies.get(property); for (PropertyInterface dependendProperty : dependendProperties) { Object newDependedValue = dependendProperty.getValue(object); ((FormElement) elements.get(dependendProperty)).setValue(newDependedValue); } } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void executeUpdater(PropertyInterface property, Object value) { if (propertyUpdater.containsKey(property)) { Map<PropertyInterface, PropertyUpdater> updaters = propertyUpdater.get(property); for (Map.Entry<PropertyInterface, PropertyUpdater> entry : updaters.entrySet()) { Object ret = entry.getValue().update(value, CloneHelper.clone(object)); entry.getKey().setValue(object, ret); } } } } private void updateEnable() { for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) { PropertyInterface property = element.getKey(); Enabled enabled = property.getAnnotation(Enabled.class); if (enabled != null) { String methodName = enabled.value(); boolean invert = methodName.startsWith("!"); if (invert) methodName = methodName.substring(1); try { Object o = findParentObject(property); Class<?> clazz = o.getClass(); Method method = clazz.getMethod(methodName); boolean e = (Boolean) method.invoke(o); if (element.getValue() instanceof Enable) { ((Enable) element.getValue()).setEnabled(e ^ invert); } else { if (editable) { logger.severe("element " + property.getPath() + " should implement Enable"); } else { logger.fine("element " + property.getPath() + " should maybe implement Enable"); } } } catch (Exception x) { String fieldName = property.getName(); if (!fieldName.equals(property.getPath())) { fieldName += " (" + property.getPath() + ")"; } logger.log(Level.SEVERE, "Update enable of " + fieldName + " failed" , x); } } } } public void indicate(List<ValidationMessage> validationMessages) { for (PropertyInterface property : getProperties()) { List<String> filteredValidationMessages = ValidationMessage.filterValidationMessage(validationMessages, property); setValidationMessage(property, filteredValidationMessages); } } private Object findParentObject(PropertyInterface property) { Object result = object; String fieldPath = property.getPath(); while (fieldPath.indexOf(".") > -1) { int pos = property.getPath().indexOf("."); PropertyInterface p2 = Properties.getProperty(result.getClass(), fieldPath.substring(0, pos)); result = p2.getValue(result); fieldPath = fieldPath.substring(pos + 1); } return result; } public class FormPanelActionListener implements Runnable { @Override public void run() { if (changeListener != null) { changeListener.commit(); } } } }
package org.spongepowered.api.data; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.entity.Banner; import org.spongepowered.api.block.entity.BlockEntity; import org.spongepowered.api.block.entity.CommandBlock; import org.spongepowered.api.block.entity.EndGateway; import org.spongepowered.api.block.entity.Jukebox; import org.spongepowered.api.block.entity.Lectern; import org.spongepowered.api.block.entity.MobSpawner; import org.spongepowered.api.block.entity.Piston; import org.spongepowered.api.block.entity.Sign; import org.spongepowered.api.block.entity.StructureBlock; import org.spongepowered.api.block.entity.carrier.Beacon; import org.spongepowered.api.block.entity.carrier.BrewingStand; import org.spongepowered.api.block.entity.carrier.CarrierBlockEntity; import org.spongepowered.api.block.entity.carrier.Hopper; import org.spongepowered.api.block.entity.carrier.furnace.FurnaceBlockEntity; import org.spongepowered.api.data.meta.BannerPatternLayer; import org.spongepowered.api.data.type.ArmorMaterial; import org.spongepowered.api.data.type.ArtType; import org.spongepowered.api.data.type.AttachmentSurface; import org.spongepowered.api.data.type.BoatType; import org.spongepowered.api.data.type.BodyPart; import org.spongepowered.api.data.type.BodyParts; import org.spongepowered.api.data.type.CatType; import org.spongepowered.api.data.type.ChestAttachmentType; import org.spongepowered.api.data.type.ComparatorMode; import org.spongepowered.api.data.type.DoorHinge; import org.spongepowered.api.data.type.DyeColor; import org.spongepowered.api.data.type.FoxType; import org.spongepowered.api.data.type.HandPreference; import org.spongepowered.api.data.type.HorseColor; import org.spongepowered.api.data.type.HorseStyle; import org.spongepowered.api.data.type.InstrumentType; import org.spongepowered.api.data.type.LlamaType; import org.spongepowered.api.data.type.MatterState; import org.spongepowered.api.data.type.MooshroomType; import org.spongepowered.api.data.type.NotePitch; import org.spongepowered.api.data.type.PandaGene; import org.spongepowered.api.data.type.PandaGenes; import org.spongepowered.api.data.type.ParrotType; import org.spongepowered.api.data.type.PhantomPhase; import org.spongepowered.api.data.type.PickupRule; import org.spongepowered.api.data.type.PistonType; import org.spongepowered.api.data.type.PortionType; import org.spongepowered.api.data.type.ProfessionType; import org.spongepowered.api.data.type.RabbitType; import org.spongepowered.api.data.type.RailDirection; import org.spongepowered.api.data.type.SlabPortion; import org.spongepowered.api.data.type.SpellType; import org.spongepowered.api.data.type.SpellTypes; import org.spongepowered.api.data.type.StairShape; import org.spongepowered.api.data.type.StructureMode; import org.spongepowered.api.data.type.ToolType; import org.spongepowered.api.data.type.TropicalFishShape; import org.spongepowered.api.data.type.VillagerType; import org.spongepowered.api.data.type.WireAttachmentType; import org.spongepowered.api.data.type.WoodType; import org.spongepowered.api.data.value.ListValue; import org.spongepowered.api.data.value.MapValue; import org.spongepowered.api.data.value.SetValue; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.data.value.WeightedCollectionValue; import org.spongepowered.api.effect.particle.ParticleEffect; import org.spongepowered.api.effect.particle.ParticleOption; import org.spongepowered.api.effect.particle.ParticleType; import org.spongepowered.api.effect.potion.PotionEffect; import org.spongepowered.api.effect.potion.PotionEffectType; import org.spongepowered.api.effect.potion.PotionEffectTypes; import org.spongepowered.api.effect.sound.music.MusicDisc; import org.spongepowered.api.entity.AreaEffectCloud; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityArchetype; import org.spongepowered.api.entity.EntityType; import org.spongepowered.api.entity.ExperienceOrb; import org.spongepowered.api.entity.FallingBlock; import org.spongepowered.api.entity.Item; import org.spongepowered.api.entity.ai.goal.GoalExecutorTypes; import org.spongepowered.api.entity.explosive.EnderCrystal; import org.spongepowered.api.entity.explosive.Explosive; import org.spongepowered.api.entity.explosive.fused.FusedExplosive; import org.spongepowered.api.entity.explosive.fused.PrimedTNT; import org.spongepowered.api.entity.hanging.Hanging; import org.spongepowered.api.entity.hanging.ItemFrame; import org.spongepowered.api.entity.hanging.LeashKnot; import org.spongepowered.api.entity.hanging.Painting; import org.spongepowered.api.entity.living.Ageable; import org.spongepowered.api.entity.living.Agent; import org.spongepowered.api.entity.living.ArmorStand; import org.spongepowered.api.entity.living.Bat; import org.spongepowered.api.entity.living.Humanoid; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.animal.Animal; import org.spongepowered.api.entity.living.animal.Cat; import org.spongepowered.api.entity.living.animal.Chicken; import org.spongepowered.api.entity.living.animal.Fox; import org.spongepowered.api.entity.living.animal.Ocelot; import org.spongepowered.api.entity.living.animal.Panda; import org.spongepowered.api.entity.living.animal.Parrot; import org.spongepowered.api.entity.living.animal.Pig; import org.spongepowered.api.entity.living.animal.PolarBear; import org.spongepowered.api.entity.living.animal.Rabbit; import org.spongepowered.api.entity.living.animal.Sheep; import org.spongepowered.api.entity.living.animal.TameableAnimal; import org.spongepowered.api.entity.living.animal.Turtle; import org.spongepowered.api.entity.living.animal.Wolf; import org.spongepowered.api.entity.living.animal.cow.Mooshroom; import org.spongepowered.api.entity.living.animal.horse.Horse; import org.spongepowered.api.entity.living.animal.horse.HorseEntity; import org.spongepowered.api.entity.living.animal.horse.PackHorse; import org.spongepowered.api.entity.living.animal.horse.llama.Llama; import org.spongepowered.api.entity.living.animal.horse.llama.TraderLlama; import org.spongepowered.api.entity.living.aquatic.Dolphin; import org.spongepowered.api.entity.living.aquatic.fish.school.TropicalFish; import org.spongepowered.api.entity.living.golem.IronGolem; import org.spongepowered.api.entity.living.golem.Shulker; import org.spongepowered.api.entity.living.monster.Blaze; import org.spongepowered.api.entity.living.monster.Creeper; import org.spongepowered.api.entity.living.monster.Enderman; import org.spongepowered.api.entity.living.monster.Endermite; import org.spongepowered.api.entity.living.monster.Patroller; import org.spongepowered.api.entity.living.monster.Phantom; import org.spongepowered.api.entity.living.monster.Vex; import org.spongepowered.api.entity.living.monster.boss.Boss; import org.spongepowered.api.entity.living.monster.boss.Wither; import org.spongepowered.api.entity.living.monster.boss.dragon.EnderDragon; import org.spongepowered.api.entity.living.monster.guardian.Guardian; import org.spongepowered.api.entity.living.monster.raider.Raider; import org.spongepowered.api.entity.living.monster.raider.Ravager; import org.spongepowered.api.entity.living.monster.raider.illager.Pillager; import org.spongepowered.api.entity.living.monster.raider.illager.Vindicator; import org.spongepowered.api.entity.living.monster.raider.illager.spellcaster.Evoker; import org.spongepowered.api.entity.living.monster.raider.illager.spellcaster.Spellcaster; import org.spongepowered.api.entity.living.monster.slime.Slime; import org.spongepowered.api.entity.living.monster.spider.Spider; import org.spongepowered.api.entity.living.monster.zombie.ZombiePigman; import org.spongepowered.api.entity.living.monster.zombie.ZombieVillager; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.entity.living.player.gamemode.GameMode; import org.spongepowered.api.entity.living.trader.Trader; import org.spongepowered.api.entity.living.trader.Villager; import org.spongepowered.api.entity.projectile.DamagingProjectile; import org.spongepowered.api.entity.projectile.EyeOfEnder; import org.spongepowered.api.entity.projectile.FishingBobber; import org.spongepowered.api.entity.projectile.Potion; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.ShulkerBullet; import org.spongepowered.api.entity.projectile.arrow.Arrow; import org.spongepowered.api.entity.projectile.arrow.ArrowEntity; import org.spongepowered.api.entity.projectile.explosive.FireworkRocket; import org.spongepowered.api.entity.projectile.explosive.WitherSkull; import org.spongepowered.api.entity.projectile.explosive.fireball.FireballEntity; import org.spongepowered.api.entity.vehicle.Boat; import org.spongepowered.api.entity.vehicle.minecart.BlockOccupiedMinecart; import org.spongepowered.api.entity.vehicle.minecart.CommandBlockMinecart; import org.spongepowered.api.entity.vehicle.minecart.FurnaceMinecart; import org.spongepowered.api.entity.vehicle.minecart.Minecart; import org.spongepowered.api.entity.vehicle.minecart.MinecartEntity; import org.spongepowered.api.entity.weather.LightningBolt; import org.spongepowered.api.entity.weather.WeatherEffect; import org.spongepowered.api.event.cause.entity.damage.source.DamageSources; import org.spongepowered.api.fluid.FluidStackSnapshot; import org.spongepowered.api.item.FireworkEffect; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.enchantment.Enchantment; import org.spongepowered.api.item.inventory.Inventory; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import org.spongepowered.api.item.inventory.Slot; import org.spongepowered.api.item.inventory.equipment.EquipmentType; import org.spongepowered.api.item.inventory.slot.EquipmentSlot; import org.spongepowered.api.item.inventory.type.GridInventory; import org.spongepowered.api.item.merchant.TradeOffer; import org.spongepowered.api.item.potion.PotionType; import org.spongepowered.api.profile.GameProfile; import org.spongepowered.api.profile.property.ProfileProperty; import org.spongepowered.api.projectile.source.ProjectileSource; import org.spongepowered.api.raid.RaidWave; import org.spongepowered.api.statistic.Statistic; import org.spongepowered.api.util.Axis; import org.spongepowered.api.util.Color; import org.spongepowered.api.util.Direction; import org.spongepowered.api.util.RespawnLocation; import org.spongepowered.api.util.Ticks; import org.spongepowered.api.util.orientation.Orientation; import org.spongepowered.api.util.weighted.WeightedSerializableObject; import org.spongepowered.api.world.ServerLocation; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.api.world.weather.Weather; import org.spongepowered.api.world.weather.Weathers; import org.spongepowered.math.vector.Vector2i; import org.spongepowered.math.vector.Vector3d; import org.spongepowered.math.vector.Vector3i; import org.spongepowered.plugin.PluginContainer; import java.time.Instant; import java.util.List; import java.util.UUID; import java.util.function.Supplier; /** * An enumeration of known {@link Key}s used throughout the API. */ @SuppressWarnings({"unused", "WeakerAccess"}) public final class Keys { // SORTFIELDS:ON /** * The {@link PotionEffectTypes#ABSORPTION} amount of a {@link Living} entity. */ public static final Supplier<Key<Value<Double>>> ABSORPTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "absorption"); /** * The acceleration of a {@link DamagingProjectile}. */ public static final Supplier<Key<Value<Vector3d>>> ACCELERATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "acceleration"); /** * The item a {@link Living} entity is currently using. * For example a player eating a food or blocking with a shield. * * <p>If there is no item, the snapshot will be empty. You can check this * with {@link ItemStackSnapshot#isEmpty()}.</p> */ public static final Supplier<Key<Value<ItemStackSnapshot>>> ACTIVE_ITEM = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "active_item"); /** * Whether a {@link Player}s affects spawning. * * <p>A {@link Player} who does not affect spawning will be treated as a * spectator in regards to spawning. A {@link MobSpawner} will not be * activated by his presence and mobs around him may naturally despawn * if there is no other Player around who affects spawning.</p> */ public static final Supplier<Key<Value<Boolean>>> AFFECTS_SPAWNING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "affects_spawning"); /** * The age (in ticks) of an entity. * e.g. The age of an {@link AreaEffectCloud}. * <p>Note that in vanilla this value is not persisted for most entities.</p> */ public static final Supplier<Key<Value<Integer>>> AGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "age"); /** * The modifier to {@link Keys#VELOCITY} of a {@link Minecart} while airborne. */ public static final Supplier<Key<Value<Vector3d>>> AIRBORNE_VELOCITY_MODIFIER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "airborne_velocity_modifier"); /** * The anger level of a {@link ZombiePigman}. * * <p>Unlike {@link Keys#IS_ANGRY}, the aggressiveness represented by this key may * fade over time and the entity will become peaceful again once its anger * reaches its minimum.</p> */ public static final Supplier<Key<Value<Integer>>> ANGER_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "anger_level"); /** * The set of {@link PotionEffect}s applied on use of an {@link ItemStack}. * Readonly */ public static final Supplier<Key<WeightedCollectionValue<PotionEffect>>> APPLICABLE_POTION_EFFECTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "applicable_potion_effects"); /** * The enchantments applied to an {@link ItemStack}. * * <p>This data is usually applicable to all types of armor, weapons and * tools. Enchantments that are only stored on an item stack in order to * be transferred to another item (like on * {@link ItemTypes#ENCHANTED_BOOK}s) use the {@link #STORED_ENCHANTMENTS} * key instead.)</p> */ public static final Supplier<Key<ListValue<Enchantment>>> APPLIED_ENCHANTMENTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "applied_enchantments"); /** * The {@link ArmorMaterial} of an armor {@link ItemStack}. * Readonly */ public static final Supplier<Key<Value<ArmorMaterial>>> ARMOR_MATERIAL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "armor_material"); /** * The type of {@link ArtType} shown by {@link Painting}s. */ public static final Supplier<Key<Value<ArtType>>> ART_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "art_type"); /** * The attachment {@link AttachmentSurface} of a button or lever {@link BlockState} */ public static final Supplier<Key<Value<AttachmentSurface>>> ATTACHMENT_SURFACE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "attachment_surface"); /** * The damage dealt by an {@link ArrowEntity} on impact. */ public static final Supplier<Key<Value<Double>>> ATTACK_DAMAGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "attack_damage"); /** * The time of a {@link Ravager} is considered attacking. */ public static final Supplier<Key<Value<Ticks>>> ATTACK_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "attack_time"); /** * The author of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}. */ public static final Supplier<Key<Value<Component>>> AUTHOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "author"); /** * The {@link Axis} direction of a {@link BlockState}. */ public static final Supplier<Key<Value<Axis>>> AXIS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "axis"); /** * The ticks until a {@link Ageable} turns into an adult. */ public static final Supplier<Key<Value<Ticks>>> BABY_TICKS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "baby_ticks"); /** * The {@link BannerPatternLayer}s of a {@link Banner}. */ public static final Supplier<Key<ListValue<BannerPatternLayer>>> BANNER_PATTERN_LAYERS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "banner_pattern_layers"); /** * The width of the physical form of an {@link Entity}. * * <p>Together with {@link #HEIGHT} and {@link #SCALE} this defines * the size of an {@link Entity}.</p> * Readonly */ public static final Supplier<Key<Value<Double>>> BASE_SIZE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "base_size"); /** * The base vehicle a passenger is riding at the moment. * This may be different from {@link Keys#VEHICLE} as the * vehicle an {@link Entity} is riding may itself be the passenger of * another vehicle. * Readonly */ public static final Supplier<Key<Value<Entity>>> BASE_VEHICLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "base_vehicle"); /** * The target entity of a {@link Guardian} beam. */ public static final Supplier<Key<Value<Living>>> BEAM_TARGET_ENTITY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "beam_target_entity"); /** * The default temperature of a biome at a specific {@link ServerLocation}. * For the exact block temperature see {@link #BLOCK_TEMPERATURE}. * Readonly */ public static final Supplier<Key<Value<Double>>> BIOME_TEMPERATURE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "biome_temperature"); /** * The blast resistance of a {@link BlockState}. * Readonly */ public static final Supplier<Key<Value<Double>>> BLAST_RESISTANCE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "blast_resistance"); /** * The amount of light that is emitted by the surrounding blocks at a block {@link ServerLocation}. * The value scales normally from 0 to 1. * <p>In vanilla minecraft is this value in steps of 1/15 from 0 to 1.</p> * <p>For the skylight see {@link #SKY_LIGHT}.</p> * Readonly */ public static final Supplier<Key<Value<Integer>>> BLOCK_LIGHT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "block_light"); /** * The {@link BlockState} of a {@link BlockOccupiedMinecart} or {@link FallingBlock}. */ public static final Supplier<Key<Value<BlockState>>> BLOCK_STATE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "block_state"); /** * The temperature at a specific {@link ServerLocation}. * For the default biome temperature see {@link #BIOME_TEMPERATURE}. * Readonly */ public static final Supplier<Key<Value<Double>>> BLOCK_TEMPERATURE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "block_temperature"); /** * The type of the boat */ public static Supplier<Key<Value<BoatType>>> BOAT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "boat_type"); /** * The rotation of specific body parts of a {@link ArmorStand} or {@link Living}. * * <p>This value provides a mapping, effectively combining the data * referenced by {@link #HEAD_ROTATION}, {@link #CHEST_ROTATION}, * {@link #RIGHT_ARM_ROTATION}, {@link #LEFT_ARM_ROTATION}, * {@link #RIGHT_LEG_ROTATION}, and {@link #LEFT_LEG_ROTATION}.</p> */ public static final Supplier<Key<MapValue<BodyPart, Vector3d>>> BODY_ROTATIONS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "body_rotations"); /** * The {@link BossBar} displayed to the client by a {@link Boss}. * Readonly but mutable? */ public static final Supplier<Key<Value<BossBar>>> BOSS_BAR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "boss_bar"); /** * The {@link BlockType}s able to be broken by an {@link ItemStack}. */ public static final Supplier<Key<SetValue<BlockType>>> BREAKABLE_BLOCK_TYPES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "breakable_block_types"); /** * The current breeder of an {@link Animal}, usually a {@link Player}s UUID. */ public static final Supplier<Key<Value<UUID>>> BREEDER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "breeder"); /** * The ticks until an {@link Animal} can breed again. Also see {@link #CAN_BREED}. */ public static final Supplier<Key<Value<Ticks>>> BREEDING_COOLDOWN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "breeding_cooldown"); /** * The burntime of an {@link ItemStack} fuel in a furnace. * See {@link #FUEL} for the time * Readonly */ public static final Supplier<Key<Value<Integer>>> BURN_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "burn_time"); /** * Whether an {@link Animal} can breed. * In Vanilla, animals can breed if their {@link Keys#BREEDING_COOLDOWN} is equal to 0. */ public static final Supplier<Key<Value<Boolean>>> CAN_BREED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_breed"); /** * Whether a {@link FallingBlock} can drop as an item. */ public static final Supplier<Key<Value<Boolean>>> CAN_DROP_AS_ITEM = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_drop_as_item"); /** * Whether a {@link Humanoid} can fly. * * <p>For a {@link Player} this means they are able to toggle flight mode * by double-tapping the jump button.</p> */ public static final Supplier<Key<Value<Boolean>>> CAN_FLY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_fly"); /** * Whether a {@link Living} entity may change blocks. * This mostly applies to {@link Enderman} or * {@link Creeper}s, but also to some projectiles like {@link FireballEntity}s or {@link WitherSkull}. */ public static final Supplier<Key<Value<Boolean>>> CAN_GRIEF = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_grief"); /** * The set of harvestable {@link BlockType}s with an {@link ItemStack}. {@link #EFFICIENCY} * Readonly */ public static final Supplier<Key<SetValue<BlockType>>> CAN_HARVEST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_harvest"); /** * Whether a {@link FallingBlock} will damage an {@link Entity} it lands on. */ public static final Supplier<Key<Value<Boolean>>> CAN_HURT_ENTITIES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_hurt_entities"); /** * Whether a {@link Raider} can join a raid. */ public static final Supplier<Key<Value<Boolean>>> CAN_JOIN_RAID = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_join_raid"); /** * Whether a {@link Boat} can move on land. */ public static final Supplier<Key<Value<Boolean>>> CAN_MOVE_ON_LAND = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_move_on_land"); /** * Whether a {@link FallingBlock} will place itself upon landing. */ public static final Supplier<Key<Value<Boolean>>> CAN_PLACE_AS_BLOCK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "can_place_as_block"); /** * The current casting time of a {@link Spellcaster}. */ public static final Supplier<Key<Value<Integer>>> CASTING_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "casting_time"); /** * The type of a {@link Cat}. */ public static final Supplier<Key<Value<CatType>>> CAT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "cat_type"); /** * The attachment of a {@link BlockTypes#CHEST} or {@link BlockTypes#TRAPPED_CHEST} {@link BlockState}. */ public static final Supplier<Key<Value<ChestAttachmentType>>> CHEST_ATTACHMENT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "chest_attachment_type"); /** * The rotation of the {@link BodyParts#CHEST}. */ public static final Supplier<Key<Value<Vector3d>>> CHEST_ROTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "chest_rotation"); /** * The {@link Color} of an {@link ItemStack} * <p> * e.g. {@link ItemTypes#LEATHER_CHESTPLATE} or {@link ItemTypes#POTION} custom color * </p> * or an {@link AreaEffectCloud}. */ public static final Supplier<Key<Value<Color>>> COLOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "color"); /** * A command stored in a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Supplier<Key<Value<String>>> COMMAND = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "command"); /** * The {@link ComparatorMode} of a {@link BlockTypes#COMPARATOR} {@link BlockState}. */ public static final Supplier<Key<Value<ComparatorMode>>> COMPARATOR_MODE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "comparator_mode"); /** * The connected directions of a {@link BlockState}. * <p> * e.g. {@link BlockTypes#GLASS_PANE}, {@link BlockTypes#IRON_BARS}, {@link BlockTypes#CHEST}, * </p> */ public static final Supplier<Key<SetValue<Direction>>> CONNECTED_DIRECTIONS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "connected_directions"); /** * The container {@link ItemType} of an {@link ItemStack}. * e.g. {@link ItemTypes#BUCKET} for a {@link ItemTypes#WATER_BUCKET} stack. * Readonly */ public static final Supplier<Key<Value<ItemType>>> CONTAINER_ITEM = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "container_item"); /** * The amount of ticks a {@link Hopper} has to wait before transferring the next item. (in Vanilla this is 8 ticks) * or * The amount of ticks a {@link EndGateway} has to wait for the next teleportation. */ public static final Supplier<Key<Value<Ticks>>> COOLDOWN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "cooldown"); /** * The creator, usually of an {@link Entity}. It is up to the implementation to define. */ public static final Supplier<Key<Value<UUID>>> CREATOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "creator"); /** * The current {@link SpellType} a {@link Spellcaster} is casting. */ public static final Supplier<Key<Value<SpellType>>> CURRENT_SPELL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "current_spell"); /** * The damage dealt towards entities of a specific {@link EntityType} by a {@link DamagingProjectile}. * * <p>Note that in events, the damage defined for the provided * {@link EntityType} will take priority over the "default" damage as * defined from {@link DamagingProjectile#attackDamage()}.</p> * * <p>Types not present in this mapping will be * dealt damage to according to {@link #ATTACK_DAMAGE}.</p> */ public static final Supplier<Key<MapValue<EntityType<?>, Double>>> CUSTOM_ATTACK_DAMAGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "custom_attack_damage"); /** * The resource pack model index of an {@link ItemStack}. * * <p>Resource packs can use the same index in their files to replace the * item model of an ItemStack.</p> */ public static final Supplier<Key<Value<Integer>>> CUSTOM_MODEL_DATA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "custom_model_data"); /** * The custom name of an {@link Entity}. */ public static final Supplier<Key<Value<Component>>> CUSTOM_NAME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "custom_name"); /** * The damage absorbed by an armor {@link ItemStack}. * Readonly */ public static final Supplier<Key<Value<Double>>> DAMAGE_ABSORPTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "damage_absorption"); /** * How much damage a {@link FallingBlock} deals to {@link Living} entities * it hits per block fallen. * * <p>This damage is capped by {@link #MAX_FALL_DAMAGE}.</p> */ public static final Supplier<Key<Value<Double>>> DAMAGE_PER_BLOCK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "damage_per_block"); /** * The distance at which a {@link BlockState} will decay. * This usually applies to leaves, for example {@link BlockTypes#OAK_LEAVES}. */ public static final Supplier<Key<Value<Integer>>> DECAY_DISTANCE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "decay_distance"); /** * The modifier to {@link Keys#VELOCITY} of a {@link Minecart} while derailed. */ public static final Supplier<Key<Value<Vector3d>>> DERAILED_VELOCITY_MODIFIER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "derailed_velocity_modifier"); /** * The despawn delay (in ticks) of a {@link Item}, {@link Endermite}, {@link Weather} {@link TraderLlama} or {@link EyeOfEnder}. */ public static final Supplier<Key<Value<Ticks>>> DESPAWN_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "despawn_delay"); /** * The detonator of a {@link PrimedTNT}. */ public static final Supplier<Key<Value<Living>>> DETONATOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "detonator"); /** * The {@link Direction} a {@link BlockState}, {@link Hanging}, or {@link Shulker} is facing or the * heading of a {@link ShulkerBullet}. */ public static final Supplier<Key<Value<Direction>>> DIRECTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "direction"); /** * The display name of an {@link Entity}, {@link ItemStack} or {@link BlockEntity}. * * <p>On an {@link Entity}, this represents a combination of {@link Keys#CUSTOM_NAME} (if set), scoreboard info, and any click data. As such * this is readonly.</p> */ public static final Supplier<Key<Value<Component>>> DISPLAY_NAME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "display_name"); /** * The dominant {@link HandPreference} of an {@link Agent} entity. * * <p><em>NOTE:</em> For {@link Player}s is this key read-only, the * {@link HandPreference} of a player can not be changed server-side.</p> */ public static final Supplier<Key<Value<HandPreference>>> DOMINANT_HAND = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "dominant_hand"); /** * The {@link DoorHinge} of a door {@link BlockState}. */ public static final Supplier<Key<Value<DoorHinge>>> DOOR_HINGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "door_hinge"); /** * Whether exact teleport location should be used with a {@link EndGateway}. */ public static final Supplier<Key<Value<Boolean>>> DO_EXACT_TELEPORT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "do_exact_teleport"); /** * The remaining duration (in ticks) of an {@link AreaEffectCloud}. */ public static final Supplier<Key<Value<Ticks>>> DURATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "duration"); /** * The amount of ticks the duration of an {@link AreaEffectCloud} * is increased or reduced when it applies its effect. */ public static final Supplier<Key<Value<Ticks>>> DURATION_ON_USE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "duration_on_use"); /** * The color of a dyeable {@link BlockState}, {@link ItemStack} or entity like {@link Cat}s. * or * The base {@link DyeColor} of a {@link Banner} or {@link TropicalFish}. */ public static final Supplier<Key<Value<DyeColor>>> DYE_COLOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "dye_color"); /** * The time a {@link Panda} has been eating (in ticks) */ public static final Supplier<Key<Value<Ticks>>> EATING_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "eating_time"); /** * The efficiency of an {@link ItemStack} tool. Affects mining speed of supported materials. {@link #CAN_HARVEST} * Readonly */ public static final Supplier<Key<Value<Double>>> EFFICIENCY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "efficiency"); /** * The time (in ticks) until a {@link Chicken} lays an {@link ItemTypes#EGG}. * * <p> * Vanilla will calculate the egg timer by taking a random value between * 0 (inclusive) and 6000 (exclusive) and then add that by another 6000. * This unit ends up being in ticks. Once the chicken lays the egg, this * calculation is ran again. * </p> */ public static final Supplier<Key<Value<Ticks>>> EGG_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "egg_time"); /** * The age (in ticks) of an {@link EndGateway} */ public static final Supplier<Key<Value<Ticks>>> END_GATEWAY_AGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "end_gateway_age"); /** * The {@link EquipmentType} that the target inventory supports. This usually applies to {@link EquipmentSlot}s. * or * The {@link EquipmentType} of an {@link ItemStack} * Readonly */ public static final Supplier<Key<Value<EquipmentType>>> EQUIPMENT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "equipment_type"); public static final Supplier<Key<Value<Double>>> EXHAUSTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "exhaustion"); /** * The amount of experience a {@link Player} has or an {@link ExperienceOrb} contains. */ public static final Supplier<Key<Value<Integer>>> EXPERIENCE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "experience"); /** * The total experience a {@link Player} requires to advance from his current level to the next one. * Readonly */ public static final Supplier<Key<Value<Integer>>> EXPERIENCE_FROM_START_OF_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "experience_from_start_of_level"); /** * The current level a {@link Player} has. */ public static final Supplier<Key<Value<Integer>>> EXPERIENCE_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "experience_level"); /** * The amount of experience a {@link Player} has collected towards the next level. */ public static final Supplier<Key<Value<Integer>>> EXPERIENCE_SINCE_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "experience_since_level"); public static final Supplier<Key<Value<Integer>>> EXPLOSION_RADIUS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "explosion_radius"); /** * The eye height of an {@link Entity}. * Readonly */ public static final Supplier<Key<Value<Double>>> EYE_HEIGHT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "eye_height"); /** * The eye position of an {@link Entity}. * Readonly */ public static final Supplier<Key<Value<Vector3d>>> EYE_POSITION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "eye_position"); /** * The distance an {@link Entity} has fallen. */ public static final Supplier<Key<Value<Double>>> FALL_DISTANCE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fall_distance"); /** * The amount of ticks a {@link FallingBlock} has been falling for. */ public static final Supplier<Key<Value<Ticks>>> FALL_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fall_time"); /** * The {@link FireworkEffect}s of a * {@link ItemTypes#FIREWORK_STAR}, {@link ItemTypes#FIREWORK_ROCKET} {@link ItemStack} or a * {@link FireworkRocket}. */ public static final Supplier<Key<ListValue<FireworkEffect>>> FIREWORK_EFFECTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "firework_effects"); /** * The flight duration of a {@link FireworkRocket} * * <p>The duration is tiered and will stay partially random. A rocket will * fly for roughly {@code modifier * 10 + (random number from 0 to 13)} * ticks in Vanilla Minecraft.</p> */ public static final Supplier<Key<Value<Ticks>>> FIREWORK_FLIGHT_MODIFIER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "firework_flight_modifier"); /** * The delay in ticks until the {@link Entity} will be damaged by the fire. */ public static final Supplier<Key<Value<Ticks>>> FIRE_DAMAGE_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fire_damage_delay"); /** * The amount of ticks an {@link Entity} is still burning. */ public static final Supplier<Key<Value<Ticks>>> FIRE_TICKS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fire_ticks"); /** * The time a {@link User} first joined on the Server. */ public static final Supplier<Key<Value<Instant>>> FIRST_DATE_JOINED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "first_date_joined"); /** * A {@link Fox fox's} first trusted {@link UUID}, usually a {@link Player}. */ public static final Supplier<Key<Value<UUID>>> FIRST_TRUSTED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "first_trusted"); /** * The {@link FluidStackSnapshot} contained within an item container. * Item containers may include buckets and other mod added items. * See {@link #CONTAINER_ITEM} */ public static final Supplier<Key<Value<FluidStackSnapshot>>> FLUID_ITEM_STACK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fluid_item_stack"); /** * The fluid level of a liquid {@link BlockState}. */ public static final Supplier<Key<Value<Integer>>> FLUID_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fluid_level"); /** * The directional tank information. * TODO dataholder? cauldron blockstate? modded? */ public static final Supplier<Key<MapValue<Direction, List<FluidStackSnapshot>>>> FLUID_TANK_CONTENTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fluid_tank_contents"); /** * The speed at which an {@link Player} flies. */ public static final Supplier<Key<Value<Double>>> FLYING_SPEED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "flying_speed"); /** * The food level of a {@link Humanoid}. * * <p>For a {@link Humanoid}, food level has health effects, depending on game difficulty and * hunger levels. If the food level is high enough, the humanoid may heal. If the food level is at 0, * the humanoid may starve.</p> */ public static final Supplier<Key<Value<Integer>>> FOOD_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "food_level"); /** * The type of a {@link Fox}. */ public static final Supplier<Key<Value<FoxType>>> FOX_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fox_type"); /** * Represents the {@link Key} for the amount of fuel left in a {@link BrewingStand} or {@link FurnaceBlockEntity} or {@link FurnaceMinecart} * * <p>One {@link ItemTypes#BLAZE_POWDER} adds 20 fuel to the brewing stand.</p> * <p>The fuel value corresponds with the number of batches of potions that can be brewed.</p> * * <p>See {@link #BURN_TIME} for the burn time added by a fuel {@link ItemStack} to a furnace</p> */ public static final Supplier<Key<Value<Integer>>> FUEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fuel"); /** * The time (in ticks) a {@link FusedExplosive}'s fuse will burn before the explosion. */ public static final Supplier<Key<Value<Ticks>>> FUSE_DURATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "fuse_duration"); /** * The {@link GameMode} a {@link Humanoid} has. */ public static final Supplier<Key<Value<GameMode>>> GAME_MODE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "game_mode"); /** * The player represented by a {@link BlockTypes#PLAYER_HEAD} (and {@link BlockTypes#PLAYER_WALL_HEAD}) * {@link BlockState} or a {@link ItemTypes#PLAYER_HEAD} {@link ItemStack}. * * <p>The offered game profile will be set exactly, unlike in vanilla where the game profile will * be resolved automatically for properties (including textures). You can obtain a game profile with * properties using {@link org.spongepowered.api.profile.GameProfileManager#getProfile}.</p> */ public static final Supplier<Key<Value<GameProfile>>> GAME_PROFILE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "game_profile"); /** * The generation of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}. * Depending on the book's generation it may be impossible to copy it. */ public static final Supplier<Key<Value<Integer>>> GENERATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "generation"); /** * The "growth stage" state of a {@link BlockState}. * e.g. {@link BlockTypes#CACTUS} or {@link BlockTypes#WHEAT} etc. */ public static final Supplier<Key<Value<Integer>>> GROWTH_STAGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "growth_stage"); /** * The hardness of a {@link BlockState}s {@link BlockType}. * Readonly */ public static final Supplier<Key<Value<Double>>> HARDNESS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hardness"); /** * Whether an {@link ArmorStand}'s arms are visible. */ public static final Supplier<Key<Value<Boolean>>> HAS_ARMS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_arms"); /** * Whether an {@link ArmorStand} has a visible base plate. */ public static final Supplier<Key<Value<Boolean>>> HAS_BASE_PLATE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_base_plate"); /** * Whether a {@link PackHorse} has a chest. */ public static final Supplier<Key<Value<Boolean>>> HAS_CHEST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_chest"); /** *Whether a {@link Turtle} currently has an egg. */ public static final Supplier<Key<Value<Boolean>>> HAS_EGG = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_egg"); /** * Whether a {@link Dolphin} has a fish. * <p> * Dolphins will navigate to a treasure (if a structure that provides one is nearby) * if they have been given a fish. * </p> */ public static final Supplier<Key<Value<Boolean>>> HAS_FISH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_fish"); /** * Whether an {@link ArmorStand} is a "marker" stand. * * <p>If {@code true}, the armor stand's bounding box is near * impossible to see, and the armor stand can no longer be * interacted with.</p> */ public static final Supplier<Key<Value<Boolean>>> HAS_MARKER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_marker"); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#DOWN} direction. See {@link #PORES}. */ public static final Supplier<Key<Value<Boolean>>> HAS_PORES_DOWN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_pores_down"); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#EAST} direction. See {@link #PORES}. */ public static final Supplier<Key<Value<Boolean>>> HAS_PORES_EAST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_pores_east"); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#NORTH} direction. See {@link #PORES}. */ public static final Supplier<Key<Value<Boolean>>> HAS_PORES_NORTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_pores_north"); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#SOUTH} direction. See {@link #PORES}. */ public static final Supplier<Key<Value<Boolean>>> HAS_PORES_SOUTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_pores_south"); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#UP} direction. See {@link #PORES}. */ public static final Supplier<Key<Value<Boolean>>> HAS_PORES_UP = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_pores_up"); /** * Whether a giant mushroom {@link BlockState} has pores on the {@link Direction#WEST} direction. See {@link #PORES}. */ public static final Supplier<Key<Value<Boolean>>> HAS_PORES_WEST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_pores_west"); /** * Whether a server player has viewed the credits. * * <p>The credits are displayed the first time a player returns to the overworld safely using an end portal.</p> */ public static final Supplier<Key<Value<Boolean>>> HAS_VIEWED_CREDITS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "has_viewed_credits"); /** * The rotation of a {@link Living}'s or {@link ArmorStand}'s head. * * <p>The format of the rotation is represented by:</p> * * <ul><li>{@code x -&gt; pitch</code></li><li> <code>y -&gt; yaw</code></li><li><code>z -&gt; roll * }</li></ul> * * <p>Note that the pitch will be the same x value returned by * {@link Entity#getRotation()} and Minecraft does not currently support * head roll so the z value will always be zero.</p> */ public static final Supplier<Key<Value<Vector3d>>> HEAD_ROTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "head_rotation"); /** * The {@link EnderCrystal} currently healing an {@link EnderDragon}. */ public static final Supplier<Key<Value<EnderCrystal>>> HEALING_CRYSTAL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "healing_crystal"); /** * A {@link Living}'s or {@link EnderCrystal}'s current health. * * <p>The range of the health depends on the object on which this * method is defined. For {@link Player Players} in Minecraft, the nominal range is * between 0 and 20, inclusive, but the range can be adjusted.</p> * * <p>Convention dictates that health does not fall below 0 but this * convention may be broken.</p> */ public static final Supplier<Key<Value<Double>>> HEALTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "health"); /** * How much health a half-heart on a {@link Player}'s GUI will stand for. * TODO wrong javadocs @gabizou? */ public static final Supplier<Key<Value<Double>>> HEALTH_SCALE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "health_scale"); /** * The height of the physical form of an {@link Entity}. * * <p>Together with {@link #BASE_SIZE} and {@link #SCALE} this defines the size of an * {@link Entity}.</p> * Readonly */ public static final Supplier<Key<Value<Double>>> HEIGHT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "height"); /** * The {@link ItemType} a {@link BlockState} represents. * Readonly */ public static final Supplier<Key<Value<ItemType>>> HELD_ITEM = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "held_item"); /** * The hidden {@link PandaGene gene} of a {@link Panda}. */ public static final Supplier<Key<Value<PandaGene>>> HIDDEN_GENE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hidden_gene"); /** * Whether the attributes of an {@link ItemStack} are hidden. */ public static final Supplier<Key<Value<Boolean>>> HIDE_ATTRIBUTES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hide_attributes"); /** * Whether the {@link #BREAKABLE_BLOCK_TYPES} of an {@link ItemStack} are hidden. */ public static final Supplier<Key<Value<Boolean>>> HIDE_CAN_DESTROY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hide_can_destroy"); /** * Whether the {@link #PLACEABLE_BLOCK_TYPES} of an {@link ItemStack} are hidden. */ public static final Supplier<Key<Value<Boolean>>> HIDE_CAN_PLACE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hide_can_place"); /** * Whether the {@link #APPLIED_ENCHANTMENTS} of an {@link ItemStack} are hidden. */ public static final Supplier<Key<Value<Boolean>>> HIDE_ENCHANTMENTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hide_enchantments"); /** * Whether miscellaneous values of an {@link ItemStack} are hidden. * e.g. potion effects or shield pattern info */ public static final Supplier<Key<Value<Boolean>>> HIDE_MISCELLANEOUS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hide_miscellaneous"); /** * Whether {@link #IS_UNBREAKABLE} state of an {@link ItemStack} is hidden. */ public static final Supplier<Key<Value<Boolean>>> HIDE_UNBREAKABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "hide_unbreakable"); /** * The {@link Vector3i position} where a {@link Turtle} lays {@link BlockTypes#TURTLE_EGG eggs}. */ public static final Supplier<Key<Value<Vector3i>>> HOME_POSITION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "home_position"); /** * The {@link HorseColor} of a {@link Horse}. */ public static final Supplier<Key<Value<HorseColor>>> HORSE_COLOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "horse_color"); /** * The {@link HorseStyle} of a {@link Horse}. */ public static final Supplier<Key<Value<HorseStyle>>> HORSE_STYLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "horse_style"); /** * Whether an {@link Item} will not despawn for an infinite time. */ public static final Supplier<Key<Value<Boolean>>> INFINITE_DESPAWN_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "infinite_despawn_delay"); /** * Whether an {@link Item} has an infinite pickup delay. */ public static final Supplier<Key<Value<Boolean>>> INFINITE_PICKUP_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "infinite_pickup_delay"); /** * The {@link InstrumentType} of a {@link BlockTypes#NOTE_BLOCK} {@link BlockState}. */ public static final Supplier<Key<Value<InstrumentType>>> INSTRUMENT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "instrument_type"); /** * Whether a {@link BlockTypes#DAYLIGHT_DETECTOR} {@link BlockState} is inverted. */ public static final Supplier<Key<Value<Boolean>>> INVERTED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "inverted"); /** * The amount of ticks an {@link Entity} will remain invulnerable for. */ public static final Supplier<Key<Value<Ticks>>> INVULNERABILITY_TICKS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "invulnerability_ticks"); /** * Whether an {@link Entity} is invulnerable. * * <p>This does not protect from the void, players in creative mode, * and manual killing like the /kill command.</p> */ public static final Supplier<Key<Value<Boolean>>> INVULNERABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "invulnerable"); /** * Whether a fence gate {@link BlockState} is in a wall. */ public static final Supplier<Key<Value<Boolean>>> IN_WALL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "in_wall"); /** * Whether an {@link Ageable} is considered an adult. */ public static final Supplier<Key<Value<Boolean>>> IS_ADULT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_adult"); /** * Whether a {@link Blaze} is currently burning. * * <p>Unlike {@link Keys#FIRE_TICKS}, the burning effect will not damage * the burning entity.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_AFLAME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_aflame"); /** * Whether an {@link Agent}s AI is enabled. */ public static final Supplier<Key<Value<Boolean>>> IS_AI_ENABLED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_ai_enabled"); /** * Whether an entity is currently aggressive. * e.g. {@link Wolf wolves} or {@link ZombiePigman} */ public static final Supplier<Key<Value<Boolean>>> IS_ANGRY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_angry"); /** * Whether a {@link BlockState} is "attached" to another block. */ public static final Supplier<Key<Value<Boolean>>> IS_ATTACHED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_attached"); /** * Whether an entity is begging for food. * e.g. {@link Cat cats} or tamed {@link Wolf wolves} */ public static final Supplier<Key<Value<Boolean>>> IS_BEGGING_FOR_FOOD = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_begging_for_food"); /** * Whether {@link Raider}s are currently celebrating. */ public static final Supplier<Key<Value<Boolean>>> IS_CELEBRATING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_celebrating"); /** * Whether a {@link Creeper} is charged. */ public static final Supplier<Key<Value<Boolean>>> IS_CHARGED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_charged"); /** * Whether a {@link Pillager} is charging it's crossbow. */ public static final Supplier<Key<Value<Boolean>>> IS_CHARGING_CROSSBOW = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_charging_crossbow"); /** * Whether a {@link Spider} is currently climbing. */ public static final Supplier<Key<Value<Boolean>>> IS_CLIMBING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_climbing"); /** * Whether a {@link BlockState} is connected to the {@link Direction#EAST}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Supplier<Key<Value<Boolean>>> IS_CONNECTED_EAST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_connected_east"); /** * Whether a {@link BlockState} is connected to the {@link Direction#NORTH}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Supplier<Key<Value<Boolean>>> IS_CONNECTED_NORTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_connected_north"); /** * Whether a {@link BlockState} is connected to the {@link Direction#SOUTH}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Supplier<Key<Value<Boolean>>> IS_CONNECTED_SOUTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_connected_south"); /** * Whether a {@link BlockState} is connected to the {@link Direction#UP}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Supplier<Key<Value<Boolean>>> IS_CONNECTED_UP = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_connected_up"); /** * Whether a {@link BlockState} is connected to the {@link Direction#WEST}. * Also see {@link #CONNECTED_DIRECTIONS}. */ public static final Supplier<Key<Value<Boolean>>> IS_CONNECTED_WEST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_connected_west"); /** * Whether an {@link Arrow} will cause a critical hit. */ public static final Supplier<Key<Value<Boolean>>> IS_CRITICAL_HIT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_critical_hit"); /** * Whether a {@link Fox} is currently crouching. */ public static final Supplier<Key<Value<Boolean>>> IS_CROUCHING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_crouching"); /** * Whether a custom name is visible on an {@link Entity}. */ public static final Supplier<Key<Value<Boolean>>> IS_CUSTOM_NAME_VISIBLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_custom_name_visible"); /** * Whether a {@link Fox} is currently defending. */ public static final Supplier<Key<Value<Boolean>>> IS_DEFENDING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_defending"); /** * Whether a {@link BlockState} is disarmed. * e.g. {@link BlockTypes#TRIPWIRE}s and {@link BlockTypes#TRIPWIRE_HOOK}s. */ public static final Supplier<Key<Value<Boolean>>> IS_DISARMED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_disarmed"); /** * Whether an entity is eating. * e.g. {@link Panda} */ public static final Supplier<Key<Value<Boolean>>> IS_EATING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_eating"); /** * Whether a {@link WeatherEffect} like {@link LightningBolt} is harmful to other {@link Entity entities}. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_EFFECT_ONLY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_effect_only"); /** * Whether a {@link Player} is flying with an {@link ItemTypes#ELYTRA}. */ public static final Supplier<Key<Value<Boolean>>> IS_ELYTRA_FLYING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_elytra_flying"); /** * Whether a piston {@link BlockState} is currently extended. * TODO {@link Piston}? */ public static final Supplier<Key<Value<Boolean>>> IS_EXTENDED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_extended"); /** * Whether a {@link Fox} is currently faceplanted. */ public static final Supplier<Key<Value<Boolean>>> IS_FACEPLANTED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_faceplanted"); /** * Whether a {@link BlockState} is filled. * <p>e.g. {@link BlockTypes#END_PORTAL_FRAME}s.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_FILLED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_filled"); /** * Whether a {@link BlockState} is flammable. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_FLAMMABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_flammable"); /** * Whether an {@link Entity} is flying. TODO only player? * * <p>This key only tells whether an entity is flying at the moment. On a * {@link Player} it does not necessarily mean that the player may toggle * freely between flying and walking. To check whether a player may switch * his flying state, check {@link #CAN_FLY}.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_FLYING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_flying"); /** * Whether an entity is frightened. * * <p>In vanilla, {@link Panda}s that have a {@link Panda#knownGene()} * of {@link PandaGenes#WORRIED} and are in a {@link ServerWorld world} whose {@link Weather} is currently a * {@link Weathers#THUNDER} are considered "frightened".</p> */ public static final Supplier<Key<Value<Boolean>>> IS_FRIGHTENED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_frightened"); /** * Whether the block at the {@link ServerLocation} is a full block. */ public static final Supplier<Key<Value<Boolean>>> IS_FULL_BLOCK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_full_block"); /** * Whether an {@link Entity} has a glowing outline. */ public static final Supplier<Key<Value<Boolean>>> IS_GLOWING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_glowing"); /** * Whether {@link Turtle} is proceeding to it's {@link Vector3i home position}. */ public static final Supplier<Key<Value<Boolean>>> IS_GOING_HOME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_going_home"); /** * Whether something is affected by gravity. * e.g. {@link Entity}s and {@link BlockState}s * Readonly(BlockState.class) */ public static final Supplier<Key<Value<Boolean>>> IS_GRAVITY_AFFECTED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_gravity_affected"); /** * Whether a {@link Cat} is hissing. */ public static final Supplier<Key<Value<Boolean>>> IS_HISSING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_hissing"); /** * Whether a {@link Ravager} is immobilized. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_IMMOBILIZED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_immobilized"); /** * Whether a {@link ServerLocation} is indirectly powered. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_INDIRECTLY_POWERED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_indirectly_powered"); /** * Whether a {@link Fox} is currently interested in something. */ public static final Supplier<Key<Value<Boolean>>> IS_INTERESTED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_interested"); /** * Whether an {@link Entity} is currently invisible. * This will only simply render the entity as vanished, * but not prevent any entity updates being sent to clients. * To fully "vanish" an {@link Entity}, use {@link #VANISH}. */ public static final Supplier<Key<Value<Boolean>>> IS_INVISIBLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_invisible"); /** * Whether a {@link Boat} is currently in {@link BlockTypes#WATER}. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_IN_WATER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_in_water"); public static final Supplier<Key<Value<Boolean>>> IS_JOHNNY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_johnny"); /** * Whether a {@link Turtle} is currently digging to lay an egg. */ public static final Supplier<Key<Value<Boolean>>> IS_LAYING_EGG = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_laying_egg"); /** * Whether a {@link Patroller} is the leader. */ public static final Supplier<Key<Value<Boolean>>> IS_LEADER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_leader"); /** * Whether a {@link BlockState} is lit. * e.g. {@link BlockTypes#FURNACE}, {@link BlockTypes#CAMPFIRE} * or {@link BlockTypes#REDSTONE_TORCH}. */ public static final Supplier<Key<Value<Boolean>>> IS_LIT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_lit"); /** *Whether a {@link Cat} is lying down. */ public static final Supplier<Key<Value<Boolean>>> IS_LYING_DOWN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_lying_down"); /** * Whether a {@link Panda} is lying on it's back. */ public static final Supplier<Key<Value<Boolean>>> IS_LYING_ON_BACK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_lying_on_back"); /** * Whether a bed {@link BlockState} is occupied. * e.g. {@link BlockTypes#WHITE_BED}. */ public static final Supplier<Key<Value<Boolean>>> IS_OCCUPIED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_occupied"); /** * Whether a {@link Minecart} is on it's rail * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_ON_RAIL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_on_rail"); /** * Whether a door/fencegate/trapdoor {@link BlockState} is open. */ public static final Supplier<Key<Value<Boolean>>> IS_OPEN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_open"); /** * Whether a {@link BlockState} is passable (can be walked through). * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_PASSABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_passable"); /** * Whether a {@link Patroller} is currently patrolling. */ public static final Supplier<Key<Value<Boolean>>> IS_PATROLLING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_patrolling"); /** * Whether an {@link Entity} or leaves {@link BlockState} will * be prevented from despawning/decaying. * * <p>In Vanilla, entities may despawn if the player moves too far from * them. A persisting entity will not be removed due to no players being * near it.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_PERSISTENT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_persistent"); /** * Whether players are prevented from placing * items from an equipment slot on an {@link ArmorStand} */ public static final Supplier<Key<MapValue<EquipmentType, Boolean>>> IS_PLACING_DISABLED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_placing_disabled"); public static final Supplier<Key<Value<Boolean>>> IS_PLAYER_CREATED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_player_created"); /** * Whether a {@link Fox} is currently pouncing. */ public static final Supplier<Key<Value<Boolean>>> IS_POUNCING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_pouncing"); /** * Whether a {@link BlockState} is powered. * * <p>Applies to blocks that may be powered in order to emit a * Redstone signal of consistently maximum strength, such as * {@link BlockTypes#LEVER}, {@link BlockTypes#OAK_BUTTON}, * {@link BlockTypes#OAK_PRESSURE_PLATE}, and their stone * counterparts.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_POWERED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_powered"); /** * Whether a {@link FusedExplosive} is currently primed. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_PRIMED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_primed"); /** * Whether a {@link Cat} is purring. */ public static final Supplier<Key<Value<Boolean>>> IS_PURRING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_purring"); /** * Whether a {@link Cat} is relaxed. */ public static final Supplier<Key<Value<Boolean>>> IS_RELAXED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_relaxed"); /** * Whether a {@link BlockState} can be replaced by a player without breaking it first. * e.g. {@link BlockTypes#WATER} * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_REPLACEABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_replaceable"); /** * Whether a {@link Ravager} is roaring. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_ROARING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_roaring"); /** * Whether a {@link Panda} is rolling around. */ public static final Supplier<Key<Value<Boolean>>> IS_ROLLING_AROUND = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_rolling_around"); /** * Whether an entity is saddled. * e.g. {@link Horse}s and {@link Pig}s */ public static final Supplier<Key<Value<Boolean>>> IS_SADDLED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_saddled"); /** * Whether an {@link Enderman} is screaming. */ public static final Supplier<Key<Value<Boolean>>> IS_SCREAMING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_screaming"); /** * Whether a {@link Sheep} is sheared. */ public static final Supplier<Key<Value<Boolean>>> IS_SHEARED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sheared"); /** * Whether an {@link Entity} is silent. * * <p>A silent entity will not emit sounds or make noises.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_SILENT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_silent"); /** * Whether a {@link Wolf}, {@link Cat}, {@link Panda}, or {@link Fox} is sitting. */ public static final Supplier<Key<Value<Boolean>>> IS_SITTING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sitting"); /** * Whether a {@link Bat}, {@link Fox} or {@link Player} is sleeping. * * <p>If a player is considered sleeping as per this data value, the player does * not need to be in bed in order for the other players to be able to * advance through the night by going to bed.</p> * Readonly(Player.class) */ public static final Supplier<Key<Value<Boolean>>> IS_SLEEPING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sleeping"); /** * Whether a {@link Player Player's} sleeping status is ignored when checking whether to * skip the night due to players sleeping. The time in a world will be * advanced to day if all players in it either are sleeping or are set to ignore. */ public static final Supplier<Key<Value<Boolean>>> IS_SLEEPING_IGNORED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sleeping_ignored"); /** * Whether an {@link ArmorStand} is small. */ public static final Supplier<Key<Value<Boolean>>> IS_SMALL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_small"); /** * Whether an {@link Entity} is sneaking. * * <p>Sneaking entities generally move slower and do not make walking * sounds.</p> */ public static final Supplier<Key<Value<Boolean>>> IS_SNEAKING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sneaking"); /** * Whether a {@link Panda} is sneezing. */ public static final Supplier<Key<Value<Boolean>>> IS_SNEEZING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sneezing"); /** * Whether a {@link BlockTypes#DIRT} {@link BlockState} is snowy. */ public static final Supplier<Key<Value<Boolean>>> IS_SNOWY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_snowy"); /** * Whether a {@link BlockState} is solid. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_SOLID = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_solid"); /** * Whether an {@link Entity} is sprinting. */ public static final Supplier<Key<Value<Boolean>>> IS_SPRINTING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_sprinting"); /** * Whether a {@link PolarBear} is currently standing. */ public static final Supplier<Key<Value<Boolean>>> IS_STANDING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_standing"); /** * Whether a {@link Ravager} is stunned. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_STUNNED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_stunned"); /** * Whether a {@link BlockState} is a surrogate block for a block that was provided in an environment * (almost always modded), that the block type provider no longer exists. * If true this may indicate that the surrogate block functions differently than the original block. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_SURROGATE_BLOCK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_surrogate_block"); /** * Whether players are prevented from taking * items from an equipment slot on an {@link ArmorStand} */ public static final Supplier<Key<MapValue<EquipmentType, Boolean>>> IS_TAKING_DISABLED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_taking_disabled"); /** * Whether a {@link TameableAnimal} is currently tamed */ public static final Supplier<Key<Value<Boolean>>> IS_TAMED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_tamed"); /** * Whether a {@link Trader} is currently trading with a {@link Player}. * Readonly */ public static final Supplier<Key<Value<Boolean>>> IS_TRADING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_trading"); /** * Whether a {@link Turtle} is currently traveling. */ public static final Supplier<Key<Value<Boolean>>> IS_TRAVELING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_traveling"); /** * Whether an {@link Ocelot} is currently trusting of {@link Player}s. */ public static final Supplier<Key<Value<Boolean>>> IS_TRUSTING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_trusting"); /** * Whether an {@link ItemStack} or {@link BlockState} is unbreakable. * * <p>Setting this to {@code true} will prevent the item stack's * {@link #ITEM_DURABILITY} from changing.</p> * Readonly(BlockState.class) */ public static final Supplier<Key<Value<Boolean>>> IS_UNBREAKABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_unbreakable"); /** * Whether a {@link Panda} is unhappy. */ public static final Supplier<Key<Value<Boolean>>> IS_UNHAPPY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_unhappy"); /** * Whehter a {@link BlockState} is waterlogged. */ public static final Supplier<Key<Value<Boolean>>> IS_WATERLOGGED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_waterlogged"); /** * Whether an {@link Entity} like {@link Wolf} is wet. * Readonly(Entity.class) except Wolf */ public static final Supplier<Key<Value<Boolean>>> IS_WET = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "is_wet"); /** * The durability of an {@link ItemStack}. {@link #MAX_DURABILITY} */ public static final Supplier<Key<Value<Integer>>> ITEM_DURABILITY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "item_durability"); /** * The {@link ItemStackSnapshot item} in an * {@link Item}, {@link ItemFrame}, {@link Jukebox}, {@link Lectern} or * {@link Potion}. */ public static final Supplier<Key<Value<ItemStackSnapshot>>> ITEM_STACK_SNAPSHOT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "item_stack_snapshot"); /** * The knockback strength applied by an {@link ArrowEntity}. * * <p>For the knockback provided by hits with a weapon according to the * enchantment of the same name, see {@link #APPLIED_ENCHANTMENTS}.</p> */ public static final Supplier<Key<Value<Double>>> KNOCKBACK_STRENGTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "knockback_strength"); /** * The known {@link PandaGene gene} of a {@link Panda}. */ public static final Supplier<Key<Value<PandaGene>>> KNOWN_GENE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "known_gene"); /** * The last attacking {@link Entity} of a {@link Living}. */ public static final Supplier<Key<Value<Entity>>> LAST_ATTACKER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "last_attacker"); /** * The output yielded by the last command of a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Supplier<Key<Value<Component>>> LAST_COMMAND_OUTPUT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "last_command_output"); /** * The last damage a {@link Living} received. */ public static final Supplier<Key<Value<Double>>> LAST_DAMAGE_RECEIVED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "last_damage_received"); /** * The last time a {@link User} joined on the server. */ public static final Supplier<Key<Value<Instant>>> LAST_DATE_JOINED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "last_date_joined"); /** * The last time a {@link User} has been playing on the server. */ public static final Supplier<Key<Value<Instant>>> LAST_DATE_PLAYED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "last_date_played"); /** * The amount of layers a {@link BlockState} has. * e.g. {@link BlockTypes#SNOW}, {@link BlockTypes#CAKE} */ public static final Supplier<Key<Value<Integer>>> LAYER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "layer"); /** * The holder of a leashed {@link Agent} * e.g. a {@link Player} or {@link LeashKnot}. * <p>Usually, a {@link LeashKnot} will always exist so long as there is * a leashed {@link Entity} attached. If the leash is broken, the leash * hitch is removed.</p> */ public static final Supplier<Key<Value<Entity>>> LEASH_HOLDER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "leash_holder"); /** * The rotation of an {@link ArmorStand}'s left arm. */ public static final Supplier<Key<Value<Vector3d>>> LEFT_ARM_ROTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "left_arm_rotation"); /** * The rotation of an {@link ArmorStand}'s left leg. */ public static final Supplier<Key<Value<Vector3d>>> LEFT_LEG_ROTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "left_leg_rotation"); /** * The amount of ticks till a {@link Vex} starts * taking damage due to living too long. * * <p>When this value hits 0 or lower, the Vex will receive damage and * then the value will set back to 20 until the Vex dies.</p> * * <p>If the Vex was summoned by a player, this value will be pegged at 0 * and the Vex will not take any damage.</p> */ public static final Supplier<Key<Value<Ticks>>> LIFE_TICKS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "life_ticks"); /** * The amount of light that emitted by a {@link BlockState}. * Readonly */ public static final Supplier<Key<Value<Integer>>> LIGHT_EMISSION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "light_emission"); /** * A {@link Llama}'s {@link LlamaType}. */ public static final Supplier<Key<Value<LlamaType>>> LLAMA_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "llama_type"); /** * The token used to lock a {@link CarrierBlockEntity}. Or the token on an {@link ItemStack} to unlock it. */ public static final Supplier<Key<Value<String>>> LOCK_TOKEN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "lock_token"); /** * The displayed description ("lore") text of an {@link ItemStack}. * * <p>The lore text is usually displayed when the player hovers his cursor * over the stack. For the contents of a book see {@link #PAGES} * instead.</p> */ public static final Supplier<Key<ListValue<Component>>> LORE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "lore"); /** * The matter state of a {@link BlockState} * Readonly */ public static final Supplier<Key<Value<MatterState>>> MATTER_STATE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "matter_state"); /** * The maximum air supply a {@link Living} may have. * * <p>For the current amount of air, check {@link #REMAINING_AIR}.</p> */ public static final Supplier<Key<Value<Integer>>> MAX_AIR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_air"); /** * The maximum amount of ticks a {@link FurnaceBlockEntity} * can burn with the currently used fuel item. */ public static final Supplier<Key<Value<Ticks>>> MAX_BURN_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_burn_time"); /** * The total time the current {@link ItemStack} in a * {@link FurnaceBlockEntity} has to be cooked. */ public static final Supplier<Key<Value<Ticks>>> MAX_COOK_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_cook_time"); /** * The maximum durability of an {@link ItemStack}. {@link #ITEM_DURABILITY} * Readonly */ public static final Supplier<Key<Value<Integer>>> MAX_DURABILITY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_durability"); /** * The maximum exhuastion of a {@link Humanoid}. Readonly. * * @see Keys#EXHAUSTION */ public static final Supplier<Key<Value<Double>>> MAX_EXHAUSTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_exhaustion"); /** * The maximum damage a {@link FallingBlock} can deal. */ public static final Supplier<Key<Value<Double>>> MAX_FALL_DAMAGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_fall_damage"); /** * The maximum food level of a {@link Humanoid}. Readonly. * * @see Keys#FOOD_LEVEL */ public static final Supplier<Key<Value<Integer>>> MAX_FOOD_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_food_level"); /** * The maximum health of a {@link Living}. * * <p>The maximum health set here may affect the attribute increasing * health points. The base health should be minded that it may be lower * than the total maximum health of the entity.</p> */ public static final Supplier<Key<Value<Double>>> MAX_HEALTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_health"); /** * The maximum number of entities around a {@link MobSpawner}. * A spawner will not spawn entities if there are more * entities around than this value permits. */ public static final Supplier<Key<Value<Integer>>> MAX_NEARBY_ENTITIES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_nearby_entities"); /** * The maximum saturation of a {@link Humanoid}. Readonly. * * @see Keys#SATURATION */ public static final Supplier<Key<Value<Double>>> MAX_SATURATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_saturation"); /** * The maximum amount of ticks between two * batches of entities spawned by a {@link MobSpawner}. */ public static final Supplier<Key<Value<Ticks>>> MAX_SPAWN_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_spawn_delay"); /** * The max speed of a {@link Boat}. In vanilla, this is 0.4 */ public static final Supplier<Key<Value<Double>>> MAX_SPEED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_speed"); /** * The maximum stack size of slots in an inventory. For most vanilla inventories this is 64. * Readonly */ public static final Supplier<Key<Value<Integer>>> MAX_STACK_SIZE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "max_stack_size"); /** * The represented block's offset of a {@link MinecartEntity}. */ public static final Supplier<Key<Value<Integer>>> MINECART_BLOCK_OFFSET = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "minecart_block_offset"); /** * The minimum amount of ticks between two * batches of entities spawned by a {@link MobSpawner}. */ public static final Supplier<Key<Value<Ticks>>> MIN_SPAWN_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "min_spawn_delay"); /** * The moisture value of a {@link BlockTypes#FARMLAND} {@link BlockState}. */ public static final Supplier<Key<Value<Integer>>> MOISTURE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "moisture"); /** * The type of a {@link Mooshroom}. */ public static final Supplier<Key<Value<MooshroomType>>> MOOSHROOM_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "mooshroom_type"); /** * The type of {@link MusicDisc} an {@link ItemStack} holds. */ public static final Supplier<Key<Value<MusicDisc>>> MUSIC_DISC = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "music_disc"); /** * The next entity that will be spawned by a {@link MobSpawner}. * * <p>Normally the entities to be spawned are determined by a random value * applied to the {@link #SPAWNABLE_ENTITIES} weighted collection. If this * value exists, it will override the random spawn with a definite one.</p> */ public static final Supplier<Key<Value<WeightedSerializableObject<EntityArchetype>>>> NEXT_ENTITY_TO_SPAWN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "next_entity_to_spawn"); /** * The pitch of a {@link BlockTypes#NOTE_BLOCK} {@link BlockState}. */ public static final Supplier<Key<Value<NotePitch>>> NOTE_PITCH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "note_pitch"); /** * The notifier, usually of an {@link Entity}. It is up to the implementation to define. */ public static final Supplier<Key<Value<UUID>>> NOTIFIER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "notifier"); /** * The deceleration a {@link Boat} while it has {@link Keys#PASSENGERS}. */ public static final Supplier<Key<Value<Double>>> OCCUPIED_DECELERATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "occupied_deceleration"); /** * Whether an {@link Entity} is currently considered to be on the ground. * Readonly */ public static final Supplier<Key<Value<Boolean>>> ON_GROUND = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "on_ground"); /** * The {@link Orientation} of an {@link ItemFrame}. */ public static final Supplier<Key<Value<Orientation>>> ORIENTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "orientation"); /** * The content of a {@link ItemTypes#WRITTEN_BOOK} {@link ItemStack}. * * <p>Use {@link Keys#PLAIN_PAGES} if you wish to inspect the contents * of a {@link ItemTypes#WRITABLE_BOOK}.</p> */ public static final Supplier<Key<ListValue<Component>>> PAGES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "pages"); /** * The {@link ParrotType type} of a {@link Parrot}. */ public static final Supplier<Key<Value<ParrotType>>> PARROT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "parrot_type"); /** * The particle type of an {@link AreaEffectCloud}. * * <p>Only a few {@link ParticleOption}s will be usable for this * effect for specific {@link ParticleType}s and not every * {@link ParticleType} will be applicable.</p> */ public static final Supplier<Key<Value<ParticleEffect>>> PARTICLE_EFFECT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "particle_effect"); /** * The amount of ticks a {@link FurnaceBlockEntity} has * been cooking the current item for. * * <p>Once this value reaches the {@link #MAX_COOK_TIME}, the * item will be finished cooking.</p> */ public static final Supplier<Key<Value<Ticks>>> PASSED_COOK_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "passed_cook_time"); /** * The entities that act as passengers for an {@link Entity}. * * <p>For example, a {@link Player} riding on a {@link Horse} or a * {@link Pig} would be considered its passenger.</p> */ public static final Supplier<Key<ListValue<Entity>>> PASSENGERS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "passengers"); /** * A {@link TropicalFish}'s pattern color. */ public static final Supplier<Key<Value<DyeColor>>> PATTERN_COLOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "pattern_color"); /** * The {@link PhantomPhase phase} of a {@link Phantom}. */ public static final Supplier<Key<Value<PhantomPhase>>> PHANTOM_PHASE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "phantom_phase"); /** * The pickup delay (in ticks) of an {@link Item}. */ public static final Supplier<Key<Value<Ticks>>> PICKUP_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "pickup_delay"); /** * The {@link PickupRule} of an {@link ArrowEntity}. */ public static final Supplier<Key<Value<PickupRule>>> PICKUP_RULE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "pickup_rule"); /** * The piston type of a piston {@link BlockState} TODO dataholder {@link Piston}. */ public static final Supplier<Key<Value<PistonType>>> PISTON_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "piston_type"); /** * The block types an {@link ItemStack} may be placed on. */ public static final Supplier<Key<SetValue<BlockType>>> PLACEABLE_BLOCK_TYPES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "placeable_block_types"); /** * The content of a {@link ItemTypes#WRITABLE_BOOK} {@link ItemStack}. * * <p>Use {@link Keys#PAGES} if you wish to get the contents of a * {@link ItemTypes#WRITTEN_BOOK}</p> */ public static final Supplier<Key<ListValue<String>>> PLAIN_PAGES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "plain_pages"); /** * The plugin that created an {@link Inventory} */ public static final Supplier<Key<Value<PluginContainer>>> PLUGIN_CONTAINER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "plugin_container"); /** * The pore sides of a {@link BlockTypes#BROWN_MUSHROOM_BLOCK} or * {@link BlockTypes#RED_MUSHROOM_BLOCK} {@link BlockState}. * See {@link #HAS_PORES_UP}, {@link #HAS_PORES_DOWN}, {@link #HAS_PORES_NORTH}, {@link #HAS_PORES_EAST}, {@link #HAS_PORES_SOUTH}, {@link #HAS_PORES_WEST}. */ public static final Supplier<Key<SetValue<Direction>>> PORES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "pores"); /** * The {@link PortionType} of a {@link BlockState}. * e.g. {@link BlockTypes#OAK_DOOR}, {@link BlockTypes#ROSE_BUSH} or {@link BlockTypes#WHITE_BED} * For slabs use {@link #SLAB_PORTION} instead */ public static final Supplier<Key<Value<PortionType>>> PORTION_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "portion_type"); /** * The potential max speed of a {@link Minecart}. */ public static final Supplier<Key<Value<Double>>> POTENTIAL_MAX_SPEED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "potential_max_speed"); /** * The potion effects that are present on an {@link Entity} * <p>or applied by an {@link AreaEffectCloud} or {@link ArrowEntity}</p> * <p>or stored on an {@link ItemStack}.</p> */ public static final Supplier<Key<ListValue<PotionEffect>>> POTION_EFFECTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "potion_effects"); /** * The potion type of an {@link ItemStack}. */ public static final Supplier<Key<Value<PotionType>>> POTION_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "potion_type"); /** * The signal power of a {@link BlockState}. * * <p>Applies to blocks that may emit a Redstone signal of variable * strength, such as {@link BlockTypes#REDSTONE_WIRE}, * {@link BlockTypes#DAYLIGHT_DETECTOR}, * {@link BlockTypes#LIGHT_WEIGHTED_PRESSURE_PLATE} etc.</p> */ public static final Supplier<Key<Value<Integer>>> POWER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "power"); /** * A {@link Beacon}'s primary effect. */ public static final Supplier<Key<Value<PotionEffectType>>> PRIMARY_POTION_EFFECT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "primary_potion_effect_type"); /** * The {@link Villager} or {@link ZombieVillager}'s {@link ProfessionType}. */ public static final Supplier<Key<Value<ProfessionType>>> PROFESSION_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "profession_type"); /** * The {@link Villager} or {@link ZombieVillager}'s {@link ProfessionType} level. */ public static final Supplier<Key<Value<Integer>>> PROFESSION_LEVEL = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "profession_level"); /** * The type of a {@link Rabbit}. */ public static final Supplier<Key<Value<RabbitType>>> RABBIT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "rabbit_type"); /** * The radius of an {@link AreaEffectCloud}. */ public static final Supplier<Key<Value<Double>>> RADIUS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "radius"); /** * The amount the radius of an * {@link AreaEffectCloud} grows or shrinks each time it applies its * effect. */ public static final Supplier<Key<Value<Double>>> RADIUS_ON_USE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "radius_on_use"); /** * The amount the radius of an * {@link AreaEffectCloud} grows or shrinks per tick. */ public static final Supplier<Key<Value<Double>>> RADIUS_PER_TICK = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "radius_per_tick"); /** * The wave number of a raid a {@link Raider} is in. * Readonly but mutable */ public static final Supplier<Key<Value<RaidWave>>> RAID_WAVE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "raid_wave"); /** * The {@link RailDirection} of a {@link BlockState}. */ public static final Supplier<Key<Value<RailDirection>>> RAIL_DIRECTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "rail_direction"); /** * The delay (in ticks) after which an * {@link AreaEffectCloud} will reapply its effect on a previously * affected {@link Entity}. */ public static final Supplier<Key<Value<Ticks>>> REAPPLICATION_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "reapplication_delay"); /** * The redstone delay on a {@link BlockTypes#REPEATER} {@link BlockState}. */ public static final Supplier<Key<Value<Integer>>> REDSTONE_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "redstone_delay"); /** * The amount of air a {@link Living} has left. */ public static final Supplier<Key<Value<Integer>>> REMAINING_AIR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "remaining_air"); /** * The remaining amount of ticks the current brewing * process of a {@link BrewingStand} will take. * * <p>If nothing is being brewed, the remaining brew time will be 0.</p> */ public static final Supplier<Key<Value<Ticks>>> REMAINING_BREW_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "remaining_brew_time"); /** * Represents the {@link Key} for the remaining number of ticks to pass * before another attempt to spawn entities is made by a {@link MobSpawner}. */ public static final Supplier<Key<Value<Ticks>>> REMAINING_SPAWN_DELAY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "remaining_spawn_delay"); /** * The amount of food a food {@link ItemStack} restores when eaten. * Readonly */ public static final Supplier<Key<Value<Integer>>> REPLENISHED_FOOD = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "replenished_food"); /** * The amount of saturation a food {@link ItemStack} provides when eaten. * Readonly */ public static final Supplier<Key<Value<Double>>> REPLENISHED_SATURATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "replenished_saturation"); /** * The {@link InstrumentType} of a {@link BlockState} when placed under a {@link BlockTypes#NOTE_BLOCK}. * Readonly */ public static final Supplier<Key<Value<InstrumentType>>> REPRESENTED_INSTRUMENT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "represented_instrument"); /** * How close a {@link Player} has to be around the {@link MobSpawner} * in order for it to attempt to spawn entities. */ public static final Supplier<Key<Value<Double>>> REQUIRED_PLAYER_RANGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "required_player_range"); /** * The spawn locations a {@link Player} * may have for various worlds based on {@link UUID} of the world. */ public static final Supplier<Key<MapValue<ResourceKey, RespawnLocation>>> RESPAWN_LOCATIONS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "respawn_locations"); /** * The rotation of an {@link ArmorStand}'s right arm. */ public static final Supplier<Key<Value<Vector3d>>> RIGHT_ARM_ROTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "right_arm_rotation"); /** * The rotation of an {@link ArmorStand}'s right leg. */ public static final Supplier<Key<Value<Vector3d>>> RIGHT_LEG_ROTATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "right_leg_rotation"); /** * The time a {@link Ravager} is roaring. */ public static final Supplier<Key<Value<Ticks>>> ROARING_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "roaring_time"); public static final Supplier<Key<Value<Double>>> SATURATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "saturation"); /** * The "scale" for the size of an {@link Entity}. * * <p>Together with {@link #BASE_SIZE} and {@link #HEIGHT} this defines the size of an {@link Entity}.</p> */ public static final Supplier<Key<Value<Double>>> SCALE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "scale"); public static final Supplier<Key<SetValue<String>>> SCOREBOARD_TAGS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "scoreboard_tags"); /** * A {@link Beacon}'s secondary effect. */ public static final Supplier<Key<Value<PotionEffectType>>> SECONDARY_POTION_EFFECT_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "secondary_potion_effect_type"); /** * A {@link Fox fox's} second trusted {@link UUID}, usually a {@link Player}. */ public static final Supplier<Key<Value<UUID>>> SECOND_TRUSTED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "second_trusted"); /** * The shooter of a {@link Projectile}. */ public static final Supplier<Key<Value<ProjectileSource>>> SHOOTER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "shooter"); /** * Whether a {@link EnderCrystal} should show it's bottom bedrock platform. */ public static final Supplier<Key<Value<Boolean>>> SHOW_BOTTOM = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "show_bottom"); /** * The lines displayed on a {@link Sign}. */ public static final Supplier<Key<ListValue<Component>>> SIGN_LINES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "sign_lines"); /** * The size of a {@link Slime}. * or * The size of a {@link Phantom}. In vanilla, this ranges between 0 and 64. */ public static final Supplier<Key<Value<Integer>>> SIZE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "size"); /** * The skin of a {@link Humanoid}. * * <p>Skins can only be manipulated by supplying the UUID of a player * having that skin. The binary skin data is signed by Mojang so fully * customized skins are not possible.</p> * Readonly (Player) */ public static final Supplier<Key<Value<ProfileProperty>>> SKIN_PROFILE_PROPERTY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "skin_profile_property"); /** * The "moisture" state of a {@link Dolphin}. * * <p> * Vanilla sets the dolphin's skin moisture to 2400 so long as the entity * is in water, being rained on, or in a bubble column. If not, the dolphin * will loose 1 moisture per tick. Once this value is 0 or below, the dolphin * will be damaged via {@link DamageSources#DRYOUT} with a value of 1 per tick * until death. * </p> */ public static final Supplier<Key<Value<Integer>>> SKIN_MOISTURE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "skin_moisture"); /** * The skylight value at a {@link ServerLocation}. * For the blocklight see {@link #BLOCK_LIGHT}. * Readonly */ public static final Supplier<Key<Value<Integer>>> SKY_LIGHT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "sky_light"); /** * The {@link SlabPortion} of a {@link BlockState}. */ public static final Supplier<Key<Value<SlabPortion>>> SLAB_PORTION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "slab_portion"); /** * The sleep timer of a {@link Player}. */ public static final Supplier<Key<Value<Integer>>> SLEEP_TIMER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "sleep_timer"); /** * The index of a {@link Slot} in an {@link Inventory} * Readonly */ public static final Supplier<Key<Value<Integer>>> SLOT_INDEX = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "slot_index"); /** * The position of a {@link Slot} within a {@link GridInventory}. * Readonly */ public static final Supplier<Key<Value<Vector2i>>> SLOT_POSITION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "slot_position"); /** * The side of a particular {@link Slot}, for use in querying "sided inventories". * Readonly */ public static final Supplier<Key<Value<Direction>>> SLOT_SIDE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "slot_side"); /** * Whether a {@link Minecart} slows down when it has no {@link Keys#PASSENGERS}. */ public static final Supplier<Key<Value<Boolean>>> SLOWS_UNOCCUPIED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "slows_unoccupied"); /** * The time a {@link Panda} has been sneezing (in ticks) */ public static final Supplier<Key<Value<Ticks>>> SNEEZING_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "sneezing_time"); /** * The list of {@link EntityArchetype}s able to be spawned by a {@link MobSpawner}. */ public static final Supplier<Key<WeightedCollectionValue<EntityArchetype>>> SPAWNABLE_ENTITIES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "spawnable_entities"); /** * How many entities a {@link MobSpawner} has spawned so far. */ public static final Supplier<Key<Value<Integer>>> SPAWN_COUNT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "spawn_count"); /** * How far away from the {@link MobSpawner} the entities spawned by it may appear. */ public static final Supplier<Key<Value<Double>>> SPAWN_RANGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "spawn_range"); /** * The {@link Entity target} of the spectator camera of a {@link Player}. */ public static final Supplier<Key<Value<Entity>>> SPECTATOR_TARGET = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "spectator_target"); /** * The {@link StairShape} of a {@link BlockState}. */ public static final Supplier<Key<Value<StairShape>>> STAIR_SHAPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "stair_shape"); /** * The {@link Statistic}s of a {@link Player}. */ public static final Supplier<Key<MapValue<Statistic, Long>>> STATISTICS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "statistics"); /** * The enchantments stored on an {@link ItemStack}. * * <p>Stored enchantments are meant to be transferred. Usually this key * applies to {@link ItemTypes#ENCHANTED_BOOK} {@link ItemStack}s. Enchantments * affecting the item stack are retrieved via {@link #APPLIED_ENCHANTMENTS} * instead.</p> */ public static final Supplier<Key<ListValue<Enchantment>>> STORED_ENCHANTMENTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "stored_enchantments"); /** * A {@link Llama}s carrying strength. The higher the strength, * the more items it can carry (effectively the size of inventory). */ public static final Supplier<Key<Value<Integer>>> STRENGTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "strength"); /** * The author of a structure from a {@link StructureBlock}. */ public static final Supplier<Key<Value<String>>> STRUCTURE_AUTHOR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_author"); /** * Whether a {@link StructureBlock} should * ignore entities when saving a structure. */ public static final Supplier<Key<Value<Boolean>>> STRUCTURE_IGNORE_ENTITIES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_ignore_entities"); /** * The integrity of a {@link StructureBlock}. */ public static final Supplier<Key<Value<Double>>> STRUCTURE_INTEGRITY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_integrity"); /** * The mode of a {@link StructureBlock}. */ public static final Supplier<Key<Value<StructureMode>>> STRUCTURE_MODE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_mode"); /** * The position of a {@link StructureBlock}. */ public static final Supplier<Key<Value<Vector3i>>> STRUCTURE_POSITION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_position"); /** * Whether a {@link StructureBlock} is powered. */ public static final Supplier<Key<Value<Boolean>>> STRUCTURE_POWERED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_powered"); /** * The seed of a {@link StructureBlock} */ public static final Supplier<Key<Value<Long>>> STRUCTURE_SEED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_seed"); /** * Whether a * {@link StructureBlock} should make all {@link BlockTypes#AIR}, * {@link BlockTypes#CAVE_AIR}, {@link BlockTypes#STRUCTURE_VOID} visible. */ public static final Supplier<Key<Value<Boolean>>> STRUCTURE_SHOW_AIR = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_show_air"); /** * Whether a {@link StructureBlock} shows the bounding box. */ public static final Supplier<Key<Value<Boolean>>> STRUCTURE_SHOW_BOUNDING_BOX = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_show_bounding_box"); /** * The size of a {@link StructureBlock}s structure. */ public static final Supplier<Key<Value<Vector3i>>> STRUCTURE_SIZE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "structure_size"); /** * The amount of "stuck arrows" in a {@link Living}. */ public static final Supplier<Key<Value<Integer>>> STUCK_ARROWS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "stuck_arrows"); /** * The time (in ticks) a {@link Ravager} is stunned. */ public static final Supplier<Key<Value<Ticks>>> STUNNED_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "stunned_time"); /** * The amount of successful executions of a command * stored in a {@link CommandBlock} or {@link CommandBlockMinecart}. */ public static final Supplier<Key<Value<Integer>>> SUCCESS_COUNT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "success_count"); /** * Whether a {@link BlockState} is suspended. */ public static final Supplier<Key<Value<Boolean>>> SUSPENDED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "suspended"); /** * The swiftness of an {@link Entity} e.g. {@link Minecart}s. * <p>This is equivalent to the magnitude of the {@link #VELOCITY} vector</p> */ public static final Supplier<Key<Value<Double>>> SWIFTNESS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "swiftness"); /** * The tamer of a {@link TameableAnimal} or {@link HorseEntity}. */ public static final Supplier<Key<Value<UUID>>> TAMER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "tamer"); /** * The targeted entity either by an {@link Agent} and it's * {@link GoalExecutorTypes#TARGET} selector or by a {@link FishingBobber} or {@link ShulkerBullet}. */ public static final Supplier<Key<Value<Entity>>> TARGET_ENTITY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "target_entity"); /** * A target location. * e.g. An {@link EyeOfEnder} target or a {@link Player}'s compass. */ public static final Supplier<Key<Value<Vector3d>>> TARGET_LOCATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "target_location"); /** * A target block position. * e.g. A {@link Patroller}'s patrol target, * the travel position of a {@link Turtle}, * the exit portal position of a {@link EndGateway} or * an {@link EnderCrystal}'s beam target. */ public static final Supplier<Key<Value<Vector3i>>> TARGET_POSITION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "target_position"); /** * The remaining fuse time in ticks of a {@link FusedExplosive}. * This value may be set to an arbitrary value * if the explosive is not primed. */ public static final Supplier<Key<Value<Ticks>>> TICKS_REMAINING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "ticks_remaining"); /** * The {@link ToolType} of an {@link ItemStack} tool. * Readonly */ public static final Supplier<Key<Value<ToolType>>> TOOL_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "tool_type"); /** * Whether a {@link CommandBlock} does track its output. * * <p>If this is set, the output of the most recent execution can be * retrieved using {@link #LAST_COMMAND_OUTPUT}.</p> */ public static final Supplier<Key<Value<Boolean>>> TRACKS_OUTPUT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "tracks_output"); /** * Tge {@link TradeOffer}s offered by a {@link Trader}. */ public static final Supplier<Key<ListValue<TradeOffer>>> TRADE_OFFERS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "trade_offers"); /** * Whether an {@link Entity} is transient. * This prevents the entity from being saved to disk. * The rules for this are as follows... * If the entity type says that it isn't transient then this key is readonly. * If the entity type says that it is transient, then this key dictates the current state. */ public static final Supplier<Key<Value<Boolean>>> TRANSIENT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "transient"); /** * A {@link TropicalFish}'s shape. */ public static final Supplier<Key<Value<TropicalFishShape>>> TROPICAL_FISH_SHAPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "tropical_fish_shape"); /** * The time a {@link Panda} has been unhappy (in ticks) */ public static final Supplier<Key<Value<Ticks>>> UNHAPPY_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "unhappy_time"); /** * The {@link UUID} of a custom inventory. */ public static final Supplier<Key<Value<UUID>>> UNIQUE_ID = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "unique_id"); /** * The deceleration a {@link Boat} while it does not have {@link Keys#PASSENGERS}. */ public static final Supplier<Key<Value<Double>>> UNOCCUPIED_DECELERATION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "unoccupied_deceleration"); /** * Whether a {@link BlockTypes#TNT} {@link BlockState} is unstable. */ public static final Supplier<Key<Value<Boolean>>> UNSTABLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "unstable"); /** * Whether changes to {@link Keys#SKIN_PROFILE_PROPERTY} should * be reflected in an entitie's {@link GameProfile}. */ public static final Supplier<Key<Value<Boolean>>> UPDATE_GAME_PROFILE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "update_game_profile"); /** * Whether an {@link Entity} is vanished. * * <p>The presence of a vanished entity will not be made known to a client; * no packets pertaining to this entity are sent. Client-side, this entity * will cease to exist. Server-side it may still be targeted by hostile * entities or collide with other entities.</p> * * <p>Vanishing an {@link Entity} ridden by other entities (see * {@link #PASSENGERS} will cause problems.</p> * <p> */ public static final Supplier<Key<Value<Boolean>>> VANISH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "vanish"); /** * Whether an {@link Entity} ignores collision with other entities. * * <p>This state will be ignored if the {@link Entity} is not also * vanished as per {@link #VANISH}.</p> */ public static final Supplier<Key<Value<Boolean>>> VANISH_IGNORES_COLLISION = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "vanish_ignores_collision"); /** * Whether an {@link Entity} can be targeted for attack by another entity. * This prevents neither {@link Player}s from attacking the entity nor * will it be protected from untargeted damage like fire or explosions. * * <p>This state will be ignored if the {@link Entity} is not also * vanished as per {@link #VANISH}.}.</p> */ public static final Supplier<Key<Value<Boolean>>> VANISH_PREVENTS_TARGETING = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "vanish_prevents_targeting"); /** * The vehicle an {@link Entity} is riding. * * <p>Vehicles may be nested as a vehicle might itself ride another entity. * To get the vehicle on bottom, use {@link Keys#BASE_VEHICLE}.</p> */ public static final Supplier<Key<Value<Entity>>> VEHICLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "vehicle"); /** * The velocity of an {@link Entity}. */ public static final Supplier<Key<Value<Vector3d>>> VELOCITY = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "velocity"); /** * The type of a {@link Villager} or {@link ZombieVillager}. */ public static final Supplier<Key<Value<VillagerType>>> VILLAGER_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "villager_type"); /** * The duration in ticks after which an * {@link AreaEffectCloud} will begin to apply its effect to entities. */ public static final Supplier<Key<Value<Ticks>>> WAIT_TIME = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wait_time"); /** * The base speed at which a {@link Player} or {@link Living} walks. */ public static final Supplier<Key<Value<Double>>> WALKING_SPEED = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "walking_speed"); /** * Whether a thrown {@link EyeOfEnder} will shatter. */ public static final Supplier<Key<Value<Boolean>>> WILL_SHATTER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "will_shatter"); /** * The {@link WireAttachmentType}s of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} for its neighboring blocks. */ public static final Supplier<Key<MapValue<Direction, WireAttachmentType>>> WIRE_ATTACHMENTS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wire_attachments"); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#EAST}. */ public static final Supplier<Key<Value<WireAttachmentType>>> WIRE_ATTACHMENT_EAST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wire_attachment_east"); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#NORTH}. */ public static final Supplier<Key<Value<WireAttachmentType>>> WIRE_ATTACHMENT_NORTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wire_attachment_north"); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#SOUTH}. */ public static final Supplier<Key<Value<WireAttachmentType>>> WIRE_ATTACHMENT_SOUTH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wire_attachment_south"); /** * The {@link WireAttachmentType} of a {@link BlockTypes#REDSTONE_WIRE} {@link BlockState} * for its neighboring block to the {@link Direction#WEST}. */ public static final Supplier<Key<Value<WireAttachmentType>>> WIRE_ATTACHMENT_WEST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wire_attachment_west"); /** * The entities targeted by the three {@link Wither} heads. In vanilla the wither only targets {@link Living}. {@code null} for no target entity. */ public static final Supplier<Key<ListValue<Entity>>> WITHER_TARGETS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wither_targets"); /** * The {@link Sheep} who is being targeted by the {@link SpellTypes#WOLOLO} * spell being casted by an {@link Evoker} */ public static final Supplier<Key<Value<Sheep>>> WOLOLO_TARGET = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wololo_target"); /** * The {@link WoodType} of a {@link Boat}. * TODO BlockState dataholders? */ public static final Supplier<Key<Value<WoodType>>> WOOD_TYPE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(Key.class, "wood_type"); // SORTFIELDS:OFF private Keys() { throw new AssertionError("You should not be attempting to instantiate this class."); } }
package org.utplsql.cli; import org.utplsql.api.compatibility.CompatibilityProxy; import org.utplsql.api.reporter.CoreReporters; import org.utplsql.api.reporter.Reporter; import org.utplsql.api.reporter.ReporterFactory; import org.utplsql.cli.config.ReporterConfig; import org.utplsql.cli.reporters.ReporterOptionsAware; import javax.sql.DataSource; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; class ReporterManager { private final List<ReporterOptions> reporterOptionsList; private List<Exception> reporterGatherErrors; private ExecutorService executorService; ReporterManager(ReporterConfig[] reporterConfigs ) { reporterOptionsList = new ArrayList<>(); if ( reporterConfigs != null && reporterConfigs.length > 0 ) { loadOptionsFromConfigs( reporterConfigs ); } else { reporterOptionsList.add(getDefaultReporterOption()); } } private void loadOptionsFromConfigs( ReporterConfig[] reporterConfigs ) { boolean printToScreen = false; for (ReporterConfig reporterConfig : reporterConfigs) { ReporterOptions option = new ReporterOptions( reporterConfig.getName(), reporterConfig.getOutput()); option.forceOutputToScreen(reporterConfig.isForceToScreen()); reporterOptionsList.add(option); // Check printToScreen validity if (option.outputToScreen() && printToScreen) throw new IllegalArgumentException("You cannot configure more than one reporter to output to screen"); printToScreen = option.outputToScreen(); } } private ReporterOptions getDefaultReporterOption() { return new ReporterOptions(CoreReporters.UT_DOCUMENTATION_REPORTER.name()); } private void abortGathering(Exception e) { addGatherError(e); executorService.shutdownNow(); } private void addGatherError( Exception e ) { if ( reporterGatherErrors == null ) { reporterGatherErrors = new ArrayList<>(); } reporterGatherErrors.add(e); } boolean haveGatherErrorsOccured() { return reporterGatherErrors != null && !reporterGatherErrors.isEmpty(); } List<Exception> getGatherErrors() { return reporterGatherErrors; } /** Initializes the reporters so we can use the id to gather results * * @param conn Active Connection * @return List of Reporters * @throws SQLException */ List<Reporter> initReporters(Connection conn, ReporterFactory reporterFactory, CompatibilityProxy compatibilityProxy) throws SQLException { final List<Reporter> reporterList = new ArrayList<>(); for (ReporterOptions ro : reporterOptionsList) { Reporter reporter = reporterFactory.createReporter(ro.getReporterName()); if ( reporter instanceof ReporterOptionsAware) ((ReporterOptionsAware) reporter).setReporterOptions(ro); reporter.init(conn, compatibilityProxy, reporterFactory); ro.setReporterObj(reporter); reporterList.add(reporter); } return reporterList; } /** Starts a separate thread for each Reporter to gather its results * * @param executorService * @param dataSource */ void startReporterGatherers(ExecutorService executorService, final DataSource dataSource) { if ( this.executorService != null && !this.executorService.isShutdown()) throw new IllegalStateException("There is already a running executor service!"); this.executorService = executorService; reporterOptionsList.forEach((reporterOption) -> executorService.submit( new GatherReporterOutputTask(dataSource, reporterOption, this::abortGathering) )); } List<ReporterOptions> getReporterOptionsList() { return reporterOptionsList; } int getNumberOfReporters() { return reporterOptionsList.size(); } /** Gathers Reporter Output based on ReporterOptions and prints it to a file, System.out or both */ private static class GatherReporterOutputTask implements Runnable { private final DataSource dataSource; private final ReporterOptions option; private final Consumer<Exception> abortFunction; GatherReporterOutputTask( DataSource dataSource, ReporterOptions reporterOption, Consumer<Exception> abortFunction ) { if ( reporterOption.getReporterObj() == null ) throw new IllegalArgumentException("Reporter " + reporterOption.getReporterName() + " is not initialized"); this.dataSource = dataSource; this.option = reporterOption; this.abortFunction = abortFunction; } @Override public void run() { List<PrintStream> printStreams = new ArrayList<>(); PrintStream fileOutStream = null; try (Connection conn = dataSource.getConnection()) { if (option.outputToScreen()) { printStreams.add(System.out); option.getReporterObj().getOutputBuffer().setFetchSize(1); } if (option.outputToFile()) { fileOutStream = new PrintStream(new FileOutputStream(option.getOutputFileName())); printStreams.add(fileOutStream); } option.getReporterObj().getOutputBuffer().printAvailable(conn, printStreams); } catch (SQLException | FileNotFoundException e) { abortFunction.accept(e); } finally { if (fileOutStream != null) fileOutStream.close(); } } } }
package refinedstorage.tile; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import refinedstorage.block.BlockMachine; import refinedstorage.tile.config.IRedstoneModeConfig; import refinedstorage.tile.config.RedstoneMode; public abstract class TileMachine extends TileBase implements INetworkTile, IRedstoneModeConfig { protected boolean connected = false; protected RedstoneMode redstoneMode = RedstoneMode.IGNORE; protected TileController controller; private Block machineBlock; public void onConnected(TileController controller) { if (worldObj != null && worldObj.getBlockState(pos).getBlock() == machineBlock) { markDirty(); this.connected = true; this.controller = controller; worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, true)); } } public void onDisconnected() { if (worldObj != null && worldObj.getBlockState(pos).getBlock() == machineBlock) { markDirty(); this.connected = false; this.controller = null; worldObj.setBlockState(pos, worldObj.getBlockState(pos).withProperty(BlockMachine.CONNECTED, false)); } } public TileController getController() { return controller; } @Override public void update() { if (worldObj == null) { super.update(); return; } if (ticks == 0) { machineBlock = worldObj.getBlockState(pos).getBlock(); } super.update(); if (!worldObj.isRemote && isConnected()) { updateMachine(); } } public boolean isConnected() { return connected; } @Override public RedstoneMode getRedstoneMode() { return redstoneMode; } @Override public void setRedstoneMode(RedstoneMode mode) { markDirty(); this.redstoneMode = mode; } @Override public BlockPos getMachinePos() { return pos; } @Override public void receiveData(ByteBuf buf) { boolean lastConnected = connected; connected = buf.readBoolean(); if (lastConnected != connected) { worldObj.notifyBlockUpdate(pos, worldObj.getBlockState(pos), worldObj.getBlockState(pos), 2 | 4); } } @Override public void sendData(ByteBuf buf) { buf.writeBoolean(connected); } @Override public void receiveContainerData(ByteBuf buf) { redstoneMode = RedstoneMode.getById(buf.readInt()); } @Override public void sendContainerData(ByteBuf buf) { buf.writeInt(redstoneMode.id); } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey(RedstoneMode.NBT)) { redstoneMode = RedstoneMode.getById(nbt.getInteger(RedstoneMode.NBT)); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger(RedstoneMode.NBT, redstoneMode.id); } public abstract int getEnergyUsage(); public abstract void updateMachine(); }
package scrum.server.admin; import ilarkesto.auth.AuthenticationFailedException; import ilarkesto.auth.OpenId; import ilarkesto.base.Str; import ilarkesto.base.Utl; import ilarkesto.base.time.DateAndTime; import ilarkesto.core.logging.Log; import ilarkesto.integration.ldap.Ldap; import ilarkesto.io.IO; import ilarkesto.ui.web.HtmlRenderer; import ilarkesto.webapp.Servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.openid4java.consumer.VerificationResult; import scrum.client.ScrumGwtApplication; import scrum.server.WebSession; import scrum.server.common.AHttpServlet; public class LoginServlet extends AHttpServlet { private static final long serialVersionUID = 1; private static Log log = Log.get(LoginServlet.class); @Override protected void onRequest(HttpServletRequest req, HttpServletResponse resp, WebSession session) throws IOException { String historyToken = req.getParameter("historyToken"); if (session.getUser() != null) { resp.sendRedirect(getStartPage(historyToken)); return; } if (tokenLogin(req, resp, session)) { resp.sendRedirect(getStartPage(historyToken)); return; } if (OpenId.isOpenIdCallback(req)) { loginOpenId(resp, session, req); return; } if (req.getParameter("createAccount") != null) { createAccount(req.getParameter("username"), req.getParameter("email"), req.getParameter("password"), historyToken, req, resp, session); return; } if (req.getParameter("passwordRequest") != null) { passwordRequest(req.getParameter("email"), historyToken, resp, session); return; } String openId = req.getParameter("openid"); if (openId != null) { redirectOpenId(openId, req.getParameter("keepmeloggedin") != null, historyToken, resp, session, req); return; } String username = req.getParameter("username"); if (username != null) { login(username, req.getParameter("password"), req.getParameter("keepmeloggedin") != null, historyToken, req, resp, session); return; } renderLoginPage(resp, null, null, historyToken, null, req.getParameter("showPasswordRequest") != null, req.getParameter("showCreateAccount") != null); } private void passwordRequest(String login, String historyToken, HttpServletResponse resp, WebSession session) throws UnsupportedEncodingException, IOException { if (login == null || Str.isBlank(login)) { renderLoginPage(resp, login, null, historyToken, "E-Mail required.", true, false); return; } User user = null; if (login.contains("@")) { user = userDao.getUserByEmail(login.toLowerCase()); } if (user == null) { user = userDao.getUserByName(login); } if (user == null) { renderLoginPage(resp, login, login, historyToken, "User '" + login + "' does not exist.", true, false); return; } if (user.isAdmin()) { renderLoginPage(resp, login, login, historyToken, "Admins can not request new passwords.", true, false); return; } if (!user.isEmailVerified()) { renderLoginPage(resp, login, login, historyToken, "User '" + login + "' has no verified email. Please contact the admin: " + systemConfig.getAdminEmail(), true, false); return; } user.triggerNewPasswordRequest(); renderLoginPage(resp, login, login, historyToken, "New password has been sent to " + login, false, false); } private void createAccount(String username, String email, String password, String historyToken, HttpServletRequest req, HttpServletResponse resp, WebSession session) throws UnsupportedEncodingException, IOException { if (webApplication.getSystemConfig().isRegistrationDisabled()) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Feature is disabled.", false, false); return; } if (Str.isBlank(username)) username = null; if (Str.isBlank(email)) email = null; if (Str.isBlank(password)) password = null; if (username == null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Username required.", false, true); return; } if (systemConfig.isUserEmailMandatory() && email == null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. E-Mail required.", false, true); return; } if (password == null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Password required.", false, true); return; } if (Str.containsNonLetterOrDigit(username)) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Name '" + username + "' contains an illegal character. Only letters and digits allowed.", false, true); return; } if (email != null && !Str.isEmail(email)) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Illegal email address.", false, true); return; } if (userDao.getUserByName(username) != null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Name '" + username + "' is already used.", false, true); log.warn("Registration failed. User name already exists:", username); return; } if (email != null && userDao.getUserByEmail(email) != null) { renderLoginPage(resp, username, email, historyToken, "Creating account failed. Email '" + email + "' is already used.", false, true); log.warn("Registration failed. User email already exists:", email); return; } User user = userDao.postUser(email, username, password); user.setLastLoginDateAndTime(DateAndTime.now()); user.triggerEmailVerification(); webApplication.getTransactionService().commit(); webApplication.triggerRegisterNotification(user, req.getRemoteHost()); webApplication.sendToClients(user); session.setUser(user); resp.sendRedirect(getStartPage(historyToken)); } private String getStartPage(String historyToken) { String url = getDefaultStartPage(); if (historyToken != null) url += "#" + historyToken; url = webApplication.createUrl(url); return url; } private void loginOpenId(HttpServletResponse resp, WebSession session, HttpServletRequest request) throws UnsupportedEncodingException, IOException { HttpSession httpSession = request.getSession(); String historyToken = (String) httpSession.getAttribute("openidHistoryToken"); boolean keepmeloggedin = httpSession.getAttribute("openidKeepmeloggedin") != null; VerificationResult openIdResult; try { openIdResult = OpenId.getVerificationFromCallback(request); } catch (RuntimeException ex) { log.error("OpenID authentication failed.", ex); renderLoginPage(resp, null, null, historyToken, "OpenID authentication failed: " + Str.format(Utl.getRootCause(ex)), false, false); return; } String openId = OpenId.getOpenId(openIdResult); if (openId == null) { renderLoginPage(resp, null, null, historyToken, "OpenID authentication failed.", false, false); return; } String email = OpenId.getEmail(openIdResult); String nickname = OpenId.getNickname(openIdResult); String fullName = OpenId.getFullname(openIdResult); User user = userDao.getUserByOpenId(openId); if (user == null) { if (webApplication.getSystemConfig().isRegistrationDisabled()) { renderLoginPage(resp, null, null, historyToken, "There is no user with the OpenID " + openId + " and creating new users is disabled.", false, false); return; } if (!webApplication.getSystemConfig().isOpenIdDomainAllowed(openId)) { renderLoginPage(resp, null, null, historyToken, "Registration failed. OpenID domains are limited to: " + webApplication.getSystemConfig().getOpenIdDomains(), false, false); log.warn("Registration failed. OpenID domains are limited to:", webApplication.getSystemConfig() .getOpenIdDomains()); return; } if (email != null) { if (userDao.getUserByEmail(email) != null) { renderLoginPage(resp, null, null, historyToken, "Creating account failed. Email '" + email + "' is already used.", false, false); log.warn("Registration failed. Email already exists:", email); return; } } if (email == null && webApplication.getSystemConfig().isUserEmailMandatory()) { renderLoginPage(resp, null, null, historyToken, "Creating account failed. Required email address was not included in OpenID response.", false, false); return; } user = userDao.postUserWithOpenId(openId, nickname, fullName, email); webApplication.getTransactionService().commit(); webApplication.triggerRegisterNotification(user, request.getRemoteHost()); } log.info("User authenticated by OpenID:", openId, "->", user); if (user.isDisabled()) { renderLoginPage(resp, null, null, historyToken, "User is disabled.", false, false); return; } user.setLastLoginDateAndTime(DateAndTime.now()); if (!user.isEmailSet()) user.setEmail(email); session.setUser(user); if (keepmeloggedin) Servlet.setCookie(resp, ScrumGwtApplication.LOGIN_TOKEN_COOKIE, user.getLoginToken(), LOGIN_TOKEN_COOKIE_MAXAGE); resp.sendRedirect(getStartPage(historyToken)); } private void redirectOpenId(String openId, boolean keepmeloggedin, String historyToken, HttpServletResponse resp, WebSession session, HttpServletRequest request) throws UnsupportedEncodingException, IOException { HttpSession httpSession = request.getSession(); if (Str.isBlank(openId)) openId = null; if (openId == null) { renderLoginPage(resp, null, null, historyToken, "Login failed. OpenID required.", false, true); return; } String returnUrl = webApplication.createUrl("login.html"); if (!returnUrl.startsWith("http")) { returnUrl = request.getRequestURL().toString(); } String openIdUrl; try { openIdUrl = OpenId.createAuthenticationRequestUrl(openId, returnUrl, httpSession, true, false, false, false, true, webApplication.getSystemConfig().isUserEmailMandatory()); } catch (RuntimeException ex) { log.error("OpenID authentication failed.", ex); renderLoginPage(resp, null, null, historyToken, "OpenID authentication failed: " + Str.format(Utl.getRootCause(ex)), false, false); return; } httpSession.setAttribute("openidHistoryToken", historyToken); httpSession.setAttribute("openidKeepmeloggedin", keepmeloggedin ? "true" : null); resp.sendRedirect(openIdUrl); } private void login(String username, String password, boolean keepmeloggedin, String historyToken, HttpServletRequest request, HttpServletResponse resp, WebSession session) throws UnsupportedEncodingException, IOException { User user = null; if (username.contains("@")) user = userDao.getUserByEmail(username.toLowerCase()); if (user == null) user = userDao.getUserByName(username); boolean admin = user != null && user.isAdmin(); boolean authenticated; String email = null; if (systemConfig.isLdapEnabled(true) && !admin) { // LDAP authentication try { email = Ldap.authenticateUserGetEmail(systemConfig.getLdapUrl(), systemConfig.getLdapUser(), systemConfig.getLdapPassword(), systemConfig.getLdapBaseDn(), systemConfig.getLdapUserFilterRegex(), username, password); authenticated = true; } catch (AuthenticationFailedException ex) { authenticated = false; } catch (Exception ex) { log.error("LDAP authentication failed.", ex); renderLoginPage(resp, username, null, historyToken, "LDAP authentication failed: " + Str.getRootCauseMessage(ex), false, false); return; } if (user == null) { if (webApplication.getSystemConfig().isRegistrationDisabled()) { renderLoginPage(resp, null, null, historyToken, "There is no user " + username + " and creating new users is disabled.", false, false); return; } user = userDao.postUser(email, username, Str.generatePassword(23)); if (Str.isEmail(email)) user.setEmail(email); webApplication.triggerRegisterNotification(user, request.getRemoteHost()); } } else { // default password authentication authenticated = user != null && user.matchesPassword(password); } if (!authenticated || user == null) { renderLoginPage(resp, username, null, historyToken, "Login failed.", false, false); return; } if (user.isDisabled()) { renderLoginPage(resp, username, null, historyToken, "User is disabled.", false, false); return; } user.setLastLoginDateAndTime(DateAndTime.now()); session.setUser(user); if (keepmeloggedin) Servlet.setCookie(resp, ScrumGwtApplication.LOGIN_TOKEN_COOKIE, user.getLoginToken(), LOGIN_TOKEN_COOKIE_MAXAGE); resp.sendRedirect(getStartPage(historyToken)); } private void renderLoginPage(HttpServletResponse resp, String username, String email, String historyToken, String message, boolean passwordRequest, boolean createAccount) throws UnsupportedEncodingException, IOException { if (webApplication.getSystemConfig().isRegistrationDisabled()) createAccount = false; String charset = IO.UTF_8; resp.setContentType("text/html"); HtmlRenderer html = new HtmlRenderer(resp.getOutputStream(), charset); html.startHTMLstandard(); String title = "Kunagi Login"; if (webApplication.getConfig().isShowRelease()) title += " " + applicationInfo.getRelease(); if (systemConfig.isInstanceNameSet()) title += " @ " + systemConfig.getInstanceName(); html.startHEAD(title, "EN"); html.META("X-UA-Compatible", "chrome=1"); html.LINKfavicon(); html.LINKcss("scrum.ScrumGwtApplication/screen.css"); html.endHEAD(); html.startBODY(); html.startDIV("loginPage"); html.startDIV("panel"); String logoUrl = webApplication.getSystemConfig().getLoginPageLogoUrl(); if (Str.isBlank(logoUrl)) logoUrl = "kunagi.png"; html.IMG(logoUrl, "Kunagi", null, null, null, null); html.DIV("separator", null); if (message != null) renderMessage(html, message); if (!createAccount && !passwordRequest) renderLogin(html, username, historyToken); if (passwordRequest) renderPasswordRequest(html, username, historyToken); if (createAccount) renderCreateAccount(html, username, email, historyToken); html.DIV("separator", null); html.startDIV("kunagiLink"); html.text("Kunagi " + webApplication.getReleaseLabel() + " | "); html.A("http://kunagi.org", "kunagi.org"); html.endDIV(); html.endDIV(); html.endDIV(); html.comment(applicationInfo.toString()); html.SCRIPTjavascript(null, "document.getElementById('username').focus();"); String analyticsId = systemConfig.getGoogleAnalyticsId(); if (analyticsId != null) html.googleAnalytics(analyticsId); html.endBODY(); html.endHTML(); html.flush(); } private void renderLogin(HtmlRenderer html, String username, String historyToken) { if (!webApplication.getSystemConfig().isOpenIdDisabled()) { html.H2("Login with OpenID"); renderOpenIdLoginForm(html, historyToken); html.DIV("separator", null); html.H2("Login with Password"); } renderRetroLoginForm(html, username, historyToken); html.BR(); html.A("login.html?showPasswordRequest=true", "Forgot your password?"); if (!systemConfig.isRegistrationDisabled()) { html.nbsp(); html.nbsp(); html.A("login.html?showCreateAccount=true", "Create new account"); } if (webApplication.isAdminPasswordDefault()) { html.DIV("separator", null); html.startDIV("configMessage"); html.html("<h2>Warning!</h2>The administrator user <code>admin</code> has the default password <code>" + systemConfig.getDefaultUserPassword() + "</code>. Please change it."); html.endDIV(); } if (systemConfig.isLoginPageMessageSet()) { html.DIV("separator", null); html.startDIV("configMessage"); html.html(systemConfig.getLoginPageMessage()); html.endDIV(); } } public void renderRetroLoginForm(HtmlRenderer html, String username, String historyToken) { html.startFORM(null, "loginForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("username", "Username / E-Mail"); html.endTD(); html.startTD(); html.LABEL("password", "Password"); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.INPUTtext("username", "username", username, 80); html.endTD(); html.startTD(); html.INPUTpassword("password", "password", 80, ""); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.INPUTcheckbox("keepmeloggedin", "keepmeloggedin", false); html.LABEL("keepmeloggedin", "Keep me logged in"); html.endTD(); html.startTD().setAlignRight(); html.INPUTsubmit("login", "Login", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.endFORM(); } public void renderOpenIdLoginForm(HtmlRenderer html, String historyToken) { renderOpenIdLink(OpenId.MYOPENID, "MyOpenID", historyToken, html); renderOpenIdLink(OpenId.GOOGLE, "Google", historyToken, html); renderOpenIdLink(OpenId.YAHOO, "Yahoo!", historyToken, html); renderOpenIdLink(OpenId.LAUNCHPAD, "Launchpad", historyToken, html); renderOpenIdLink(OpenId.AOL, "AOL", historyToken, html); renderOpenIdLink(OpenId.VERISIGN, "Verisign", historyToken, html); renderOpenIdLink(OpenId.WORDPRESS, "WordPress", historyToken, html); renderOpenIdLink(OpenId.FLICKR, "Flickr", historyToken, html); // renderOpenIdLink(OpenId.BLOGSPOT, "Blogger", historyToken, html); renderOpenIdLink(OpenId.MYVIDOOP, "Vidoop", historyToken, html); html.DIVclear(); html.BR(); html.startFORM(null, "openIdForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("openid", "Custom OpenID"); html.endTD(); html.TD(""); html.endTR(); html.startTR(); html.startTD(null, 2); html.INPUTtext("openid", "openid", null, 80); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.INPUTcheckbox("keepmeloggedinOpenId", "keepmeloggedin", false); html.LABEL("keepmeloggedinOpenId", "Keep me logged in"); html.endTD(); html.startTD().setAlignRight(); html.INPUTsubmit("login", "Login", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.BR(); html.A("http://openid.net/get-an-openid/", "Don't have an OpenID?", true); html.endFORM(); } private void renderOpenIdLink(String openId, String label, String historyToken, HtmlRenderer html) { StringBuilder sb = new StringBuilder(); sb.append("login.html?openid=").append(Str.encodeUrlParameter(openId)); sb.append("&login=Login"); if (historyToken != null) sb.append("&historyToken=").append(Str.encodeUrlParameter(historyToken)); html.startA("openid", sb.toString()); html.startDIV("button"); html.text(label); html.endDIV(); html.endA(); } private void renderPasswordRequest(HtmlRenderer html, String username, String historyToken) { html.H2("Request new password"); html.startFORM(null, "passwordRequestForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("email", "E-Mail"); html.endTD(); html.TD(" "); html.endTR(); html.startTR(); html.startTD(); html.INPUTtext("email", "email", username, 80); html.endTD(); html.startTD(); html.INPUTsubmit("passwordRequest", "Request password", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.endFORM(); html.BR(); html.A("login.html", "Back to Login"); } private void renderCreateAccount(HtmlRenderer html, String username, String email, String historyToken) { html.H2("Create account"); html.startDIV("createAccount"); html.startFORM(null, "loginForm", false); html.INPUThidden("historyToken", historyToken); html.startTABLE().setAlignCenter(); html.startTR(); html.startTD(); html.LABEL("username", "Username"); html.endTD(); html.startTD(); html.INPUTtext("username", "username", username, 80); html.endTD(); html.endTR(); html.startTR(); html.startTD(); if (!webApplication.getSystemConfig().isUserEmailMandatory()) html.startDIV("optionalLabel"); html.LABEL("email", "E-Mail"); if (!webApplication.getSystemConfig().isUserEmailMandatory()) html.endDIV(); html.endTD(); html.startTD(); html.INPUTtext("email", "email", email, 80); html.endTD(); html.endTR(); html.startTR(); html.startTD(); html.LABEL("password", "Password"); html.endTD(); html.startTD(); html.INPUTpassword("password", "password", 80, ""); html.endTD(); html.endTR(); html.startTR(); html.TD(""); html.startTD(); html.INPUTsubmit("createAccount", "Create account", null, 's'); html.endTD(); html.endTR(); html.endTABLE(); html.endFORM(); html.endDIV(); html.BR(); html.A("login.html", "Back to Login"); if (systemConfig.isRegisterPageMessageSet()) { html.DIV("separator", null); html.startDIV("configMessage"); html.html(systemConfig.getRegisterPageMessage()); html.endDIV(); } } private void renderMessage(HtmlRenderer html, String message) { html.startDIV("message"); html.text(message); html.endDIV(); html.DIV("separator", null); } }
package sds.assemble.controlflow; import java.util.LinkedHashSet; import java.util.Set; import sds.assemble.LineInstructions; import sds.classfile.bytecode.BranchOpcode; import sds.classfile.bytecode.OpcodeInfo; import sds.classfile.bytecode.LookupSwitch; import sds.classfile.bytecode.TableSwitch; /** * This class is for node of control flow graph. * @author inagaki */ public class CFNode { private Set<CFEdge> parents; private Set<CFEdge> children; private CFNode dominator; private CFNode immediateDominator; private OpcodeInfo start; private OpcodeInfo end; private int jumpPoint = -1; private int[] switchJump = new int[0]; private int hash; private String instStr; // package-private fields. CFNodeType nodeType; boolean inTry = false; boolean isCatchEntry = false; boolean isFinallyEntry = false; /** * constructor. * @param inst instrcutions of a line. */ public CFNode(LineInstructions inst) { int size = inst.getOpcodes().size(); this.start = inst.getOpcodes().getAll()[0]; if(size == 1) { this.end = start; } else { this.end = inst.getOpcodes().getAll()[size-1]; } StringBuilder sb = new StringBuilder(); for(OpcodeInfo info : inst.getOpcodes().getAll()) { sb.append(info.getOpcodeType()).append(" "); } this.instStr = sb.toString(); this.nodeType = CFNodeType.getType(inst.getOpcodes(), end); if(nodeType == CFNodeType.Entry) { // if_xx for(OpcodeInfo op : inst.getOpcodes().getAll()) { if(op instanceof BranchOpcode) { this.jumpPoint = ((BranchOpcode)op).getBranch() + op.getPc(); } } } else if(nodeType == CFNodeType.Exit || nodeType == CFNodeType.LoopExit) { // goto this.jumpPoint = ((BranchOpcode)end).getBranch() + end.getPc(); } else if(nodeType == CFNodeType.Switch) { // switch for(OpcodeInfo op : inst.getOpcodes().getAll()) { if(op instanceof LookupSwitch) { LookupSwitch look = (LookupSwitch)op; this.switchJump = new int[look.getMatch().length + 1]; int[] offsets = look.getOffset(); for(int i = 0; i < switchJump.length-1; i++) { switchJump[i] = offsets[i] + look.getPc(); } switchJump[switchJump.length - 1] = look.getDefault() + look.getPc(); break; } else if(op instanceof TableSwitch) { TableSwitch table = (TableSwitch)op; this.switchJump = new int[table.getJumpOffsets().length + 1]; int[] offsets = table.getJumpOffsets(); for(int i = 0; i < switchJump.length-1; i++) { switchJump[i] = offsets[i] + table.getPc(); } switchJump[switchJump.length - 1] = table.getDefault() + table.getPc(); break; } } } // calc hash char[] val1 = String.valueOf(start.getPc()).toCharArray(); char[] val2 = String.valueOf(end.getPc()).toCharArray(); char[] val3 = start.getOpcodeType().toString().toCharArray(); char[] val4 = end.getOpcodeType().toString().toCharArray(); for(int i = 0; i < val1.length; i++) { hash = 31 * hash + val1[i]; } for(int i = 0; i < val2.length; i++) { hash = 31 * hash + val2[i]; } for(int i = 0; i < val3.length; i++) { hash = 31 * hash + val3[i]; } for(int i = 0; i < val4.length; i++) { hash = 31 * hash + val4[i]; } this.parents = new LinkedHashSet<>(); this.children = new LinkedHashSet<>(); } /** * returns index into code array of jump point.<br> * if this node type is Entry or Exit (and that of Loop), this method returns -1. * @return jump point index */ public int getJumpPoint() { return jumpPoint; } /** * returns indexes into code array of jump point. * @return jump point indexes */ public int[] getSwitchJump() { return switchJump; } /** * returns node type. * @return node type */ public CFNodeType getType() { return nodeType; } /** * returns parent nodes. * @return parent nodes */ public Set<CFEdge> getParents() { return parents; } /** * returns child nodes. * @return child nodes */ public Set<CFEdge> getChildren() { return children; } /** * returns immediate dominator node. * @return immediate dominator node */ public CFNode getImmediateDominator() { return immediateDominator; } /** * returns dominator node. * @return dominator node */ public CFNode getDominator() { return dominator; } /** * sets immediate dominator node. * @param node immediate dominator node */ public void setImmediateDominator(CFNode node) { this.immediateDominator = node; } /** * sets dominator node. * @param node dominator node */ public void setDominator(CFNode node) { this.dominator = node; } /** * adds parent node of this. * @param parent parent node */ public void addParent(CFNode parent) { addParent(parent, CFEdgeType.Normal); } /** * adds parent node of this. * @param parent parent node * @param type edge type */ public void addParent(CFNode parent, CFEdgeType type) { if(!isRoot()) { CFEdge edge = new CFEdge(this, parent, type); if(parents.isEmpty()) { this.immediateDominator = parent; this.parents.add(edge); } else { if(!parents.contains(edge)) { parents.add(edge); } } } } /** * adds child node of this. * @param child child node */ public void addChild(CFNode child) { addChild(child, CFEdgeType.Normal); } /** * adds child node of this. * @param child child node * @param type edge type */ public void addChild(CFNode child, CFEdgeType type) { CFEdge edge = new CFEdge(this, child, type); if(!children.contains(edge)) { children.add(edge); } } /** * returns whether specified pc is in range of opcode pc of this opcodes. * @param pc index into code array * @return if specified pc is in range of opcode pc, this method returns true.<br> * Otherwise, this method returns false. */ public boolean isInPcRange(int pc) { return start.getPc() <= pc && pc <= end.getPc(); } /** * returns whether this node is root. * @return if this node is root, this method returns true.<br> * Otherwise, this method returns false. */ public boolean isRoot() { return start.getPc() == 0; } /** * returns start opcode of instructions of this node. * @return start opcode */ public OpcodeInfo getStart() { return start; } /** * returns end opcode of instructions of this node. * @return end opcode */ public OpcodeInfo getEnd() { return end; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if(!(obj instanceof CFNode)) { return false; } CFNode node = (CFNode)obj; return start.getPc() == node.getStart().getPc() && end.getPc() == node.getEnd().getPc(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("#").append(start.getPc()).append("-").append(end.getPc()) .append(" [").append(nodeType).append("]").append("\n"); if(inTry) sb.append(" in try\n"); if(isCatchEntry) sb.append(" catch entry\n"); if(isFinallyEntry) sb.append(" finally entry\n"); sb.append(" opcodes: ").append(instStr).append("\n"); if(parents.size() == 1) { sb.append(" immediate dominator: ").append(parents.iterator().next()); } else if(parents.size() > 1) { sb.append(" dominator: ") .append(dominator.getStart().getPc()).append("-") .append(dominator.getEnd().getPc()) .append("\n parents: "); for(CFEdge edge : parents) { sb.append(edge.toString()).append(" "); } } else { sb.append(" parents: not exist"); } sb.append("\n children: "); for(CFEdge edge : children) { sb.append(edge.toString()).append(" "); } return sb.toString(); } }
package soot.compat.crafttweaker; import com.blamejared.mtlib.helpers.InputHelper; import com.blamejared.mtlib.utils.BaseListAddition; import com.blamejared.mtlib.utils.BaseListRemoval; import com.google.common.collect.Lists; import crafttweaker.CraftTweakerAPI; import crafttweaker.annotations.ZenRegister; import crafttweaker.api.item.IItemStack; import crafttweaker.api.liquid.ILiquidStack; import crafttweaker.api.oredict.IOreDictEntry; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import teamroots.embers.recipe.ItemMeltingOreRecipe; import teamroots.embers.recipe.ItemMeltingRecipe; import teamroots.embers.recipe.RecipeRegistry; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @ZenRegister @ZenClass(Melter.clazz) public class Melter { public static final String clazz = "mods.embers.Melter"; @ZenMethod public static void add(ILiquidStack output, IItemStack input) { ItemStack stack = InputHelper.toStack(input); ItemMeltingRecipe recipe = new ItemMeltingRecipe(stack,InputHelper.toFluid(output),stack.getMetadata() != OreDictionary.WILDCARD_VALUE,stack.hasTagCompound()); CraftTweakerAPI.apply(new Add(recipe)); } @ZenMethod public static void add(ILiquidStack output, IOreDictEntry input) { ItemMeltingOreRecipe recipe = new ItemMeltingOreRecipe(input.getName(),InputHelper.toFluid(output)); CraftTweakerAPI.apply(new AddOre(recipe)); } @ZenMethod public static void remove(IItemStack input) { CraftTweakerAPI.apply(new RemoveByInput(InputHelper.toStack(input))); } @ZenMethod public static void remove(ILiquidStack output) { CraftTweakerAPI.apply(new RemoveByOutput(InputHelper.toFluid(output))); CraftTweakerAPI.apply(new RemoveByOreOutput(InputHelper.toFluid(output))); } @ZenMethod public static void remove(IOreDictEntry input) { CraftTweakerAPI.apply(new RemoveByOre(input.getName())); } private static List<ItemMeltingRecipe> getRecipesByOutput(FluidStack stack) { return RecipeRegistry.meltingRecipes.stream().filter(recipe -> stack.isFluidStackIdentical(recipe.getFluid())).collect(Collectors.toCollection(ArrayList::new)); } private static List<ItemMeltingOreRecipe> getOreRecipesByOutput(FluidStack stack) { return RecipeRegistry.meltingOreRecipes.stream().filter(recipe -> stack.isFluidStackIdentical(recipe.getFluid())).collect(Collectors.toCollection(ArrayList::new)); } private static List<ItemMeltingRecipe> getRecipesByInput(ItemStack stack) { return RecipeRegistry.meltingRecipes.stream().filter(recipe -> ItemStack.areItemStacksEqual(recipe.getStack(),stack)).collect(Collectors.toCollection(ArrayList::new)); } private static List<ItemMeltingOreRecipe> getRecipesByInput(String ore) { return RecipeRegistry.meltingOreRecipes.stream().filter(recipe -> recipe.getOreName().equals(ore)).collect(Collectors.toCollection(ArrayList::new)); } public static class Add extends BaseListAddition<ItemMeltingRecipe> { public Add(ItemMeltingRecipe recipe) { super("Melter", RecipeRegistry.meltingRecipes, Lists.newArrayList(recipe)); } @Override protected String getRecipeInfo(ItemMeltingRecipe recipe) { return recipe.toString(); } } public static class AddOre extends BaseListAddition<ItemMeltingOreRecipe> { public AddOre(ItemMeltingOreRecipe recipe) { super("Melter", RecipeRegistry.meltingOreRecipes, Lists.newArrayList(recipe)); } @Override protected String getRecipeInfo(ItemMeltingOreRecipe recipe) { return recipe.toString(); } } public static class RemoveByOutput extends BaseListRemoval<ItemMeltingRecipe> { protected RemoveByOutput(FluidStack output) { super("Melter", RecipeRegistry.meltingRecipes, getRecipesByOutput(output)); } @Override protected String getRecipeInfo(ItemMeltingRecipe recipe) { return recipe.toString(); } } public static class RemoveByInput extends BaseListRemoval<ItemMeltingRecipe> { protected RemoveByInput(ItemStack input) { super("Melter", RecipeRegistry.meltingRecipes, getRecipesByInput(input)); } @Override protected String getRecipeInfo(ItemMeltingRecipe recipe) { return recipe.toString(); } } public static class RemoveByOreOutput extends BaseListRemoval<ItemMeltingOreRecipe> { protected RemoveByOreOutput(FluidStack output) { super("Melter", RecipeRegistry.meltingOreRecipes, getOreRecipesByOutput(output)); } @Override protected String getRecipeInfo(ItemMeltingOreRecipe recipe) { return recipe.toString(); } } public static class RemoveByOre extends BaseListRemoval<ItemMeltingOreRecipe> { protected RemoveByOre(String input) { super("Melter", RecipeRegistry.meltingOreRecipes, getRecipesByInput(input)); } @Override protected String getRecipeInfo(ItemMeltingOreRecipe recipe) { return recipe.toString(); } } }
package space.pxls.server; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.exceptions.UnirestException; import io.undertow.websockets.core.WebSocketChannel; import space.pxls.App; import space.pxls.data.DBPixelPlacement; import space.pxls.user.Role; import space.pxls.user.User; import space.pxls.util.PxlsTimer; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.lang.Math; public class PacketHandler { private UndertowServer server; private PxlsTimer userData = new PxlsTimer(5); private int getCooldown() { // TODO: make these parameters somehow configurable // expondent function of form a*exp(-b*(x - d)) + c double a = -8.04044740e+01; double b = 1.19078478e-03; double c = 9.63956320e+01; double d = -2.14065886e+00; double x = (double)server.getConnections().size(); return (int)Math.ceil(a*Math.exp(-b*(x - d)) + c); } public PacketHandler(UndertowServer server) { this.server = server; } public void userdata(WebSocketChannel channel, User user) { if (user != null) { server.send(channel, new Packet.ServerUserInfo(user.getName(), user.isBanned(), user.getRole().name() == "SHADOWBANNED" ? "USER" : user.getRole().name(), user.isBanned() ? user.getBanExpiryTime() : null, user.isBanned() ? user.getBanReason() : "")); } } public void connect(WebSocketChannel channel, User user) { if (user != null) { userdata(channel, user); sendCooldownData(channel, user); user.flagForCaptcha(); } updateUserData(); } public void disconnect(WebSocketChannel channel, User user) { updateUserData(); } public void accept(WebSocketChannel channel, User user, Object obj, String ip) { if (user != null) { if (obj instanceof Packet.ClientPlace) handlePlace(channel, user, ((Packet.ClientPlace) obj), ip); if (obj instanceof Packet.ClientUndo) handleUndo(channel, user, ((Packet.ClientUndo) obj)); if (obj instanceof Packet.ClientCaptcha) handleCaptcha(channel, user, ((Packet.ClientCaptcha) obj)); if (obj instanceof Packet.ClientShadowBanMe) handleShadowBanMe(channel, user, ((Packet.ClientShadowBanMe) obj)); if (obj instanceof Packet.ClientBanMe) handleBanMe(channel, user, ((Packet.ClientBanMe) obj)); if (user.getRole().greaterEqual(Role.MODERATOR)) { if (obj instanceof Packet.ClientAdminCooldownOverride) handleCooldownOverride(channel, user, ((Packet.ClientAdminCooldownOverride) obj)); if (obj instanceof Packet.ClientAdminMessage) handleAdminMessage(channel, user, ((Packet.ClientAdminMessage) obj)); } } } private void handleAdminMessage(WebSocketChannel channel, User user, Packet.ClientAdminMessage obj) { User u = App.getUserManager().getByName(obj.username); if (u != null) { Packet.ServerAlert msg = new Packet.ServerAlert(obj.message); for (WebSocketChannel ch : u.getConnections()) { server.send(ch, msg); } } } private void handleShadowBanMe(WebSocketChannel channel, User user, Packet.ClientShadowBanMe obj) { App.getDatabase().adminLog("self-shadowban via script", user.getId()); user.shadowban("auto-ban via script"); } private void handleBanMe(WebSocketChannel channel, User user, Packet.ClientBanMe obj) { App.getDatabase().adminLog("self-ban via script", user.getId()); user.ban(86400, "auto-ban via script"); } private void handleCooldownOverride(WebSocketChannel channel, User user, Packet.ClientAdminCooldownOverride obj) { user.setOverrideCooldown(obj.override); sendCooldownData(user); } private void handleUndo(WebSocketChannel channel, User user, Packet.ClientUndo cu){ if (!user.canUndoNow()) { return; } if (user.isShadowBanned()) { user.setLastUndoTime(); user.setCooldown(0); sendCooldownData(user); return; } user.setLastUndoTime(); user.setCooldown(0); DBPixelPlacement thisPixel = App.getDatabase().getUserUndoPixel(user); DBPixelPlacement recentPixel = App.getDatabase().getPixelAt(thisPixel.x, thisPixel.y); if (thisPixel.id != recentPixel.id) return; DBPixelPlacement lastPixel = App.getDatabase().getPixelByID(thisPixel.secondaryId); if (lastPixel != null) { App.getDatabase().putUserUndoPixel(lastPixel, user, thisPixel.id); App.putPixel(lastPixel.x, lastPixel.y, lastPixel.color, user, false, "(user undo)", false); broadcastPixelUpdate(lastPixel.x, lastPixel.y, lastPixel.color); } else { int defaultColor = App.getConfig().getInt("board.defaultColor"); App.getDatabase().putUserUndoPixel(thisPixel.x, thisPixel.y, defaultColor, user, thisPixel.id); App.putPixel(thisPixel.x, thisPixel.y, defaultColor, user, false, "(user undo)", false); broadcastPixelUpdate(thisPixel.x, thisPixel.y, defaultColor); } sendCooldownData(user); } private void handlePlace(WebSocketChannel channel, User user, Packet.ClientPlace cp, String ip) { if (cp.x < 0 || cp.x >= App.getWidth() || cp.y < 0 || cp.y >= App.getHeight()) return; if (cp.color < 0 || cp.color >= App.getConfig().getStringList("board.palette").size()) return; if (user.isBanned()) return; if (user.canPlace()) { if (user.updateCaptchaFlagPrePlace() && App.isCaptchaEnabled()) { server.send(channel, new Packet.ServerCaptchaRequired()); } else { if (App.getPixel(cp.x, cp.y) != cp.color) { int seconds = getCooldown(); if (App.getDatabase().didPixelChange(cp.x, cp.y)) { seconds = seconds * 2; } if (user.isShadowBanned()) { // ok let's just pretend to set a pixel... System.out.println("shadowban pixel!"); Packet.ServerPlace msg = new Packet.ServerPlace(Collections.singleton(new Packet.ServerPlace.Pixel(cp.x, cp.y, cp.color))); for (WebSocketChannel ch : user.getConnections()) { server.send(ch, msg); } if (user.canUndo()) { server.send(channel, new Packet.CanUndo(App.getConfig().getDuration("undo.window", TimeUnit.SECONDS))); } } else { boolean mod_action = user.isOverridingCooldown(); App.putPixel(cp.x, cp.y, cp.color, user, mod_action, ip, true); App.saveMap(); broadcastPixelUpdate(cp.x, cp.y, cp.color); } if (!user.isOverridingCooldown()) { user.setCooldown(seconds); user.setLastPixelTime(); App.getDatabase().updateUserTime(user.getId(), seconds); if (user.canUndo()) { server.send(channel, new Packet.CanUndo(App.getConfig().getDuration("undo.window", TimeUnit.SECONDS))); } } } } } sendCooldownData(user); } private void handleCaptcha(WebSocketChannel channel, User user, Packet.ClientCaptcha cc) { if (!user.isFlaggedForCaptcha()) return; if (user.isBanned()) return; Unirest .post("https: .field("secret", App.getConfig().getString("captcha.secret")) .field("response", cc.token) //.field("remoteip", "null") .asJsonAsync(new Callback<JsonNode>() { @Override public void completed(HttpResponse<JsonNode> response) { JsonNode body = response.getBody(); String hostname = App.getConfig().getString("host"); boolean success = body.getObject().getBoolean("success") && body.getObject().getString("hostname").equals(hostname); if (success) { user.validateCaptcha(); } server.send(channel, new Packet.ServerCaptchaStatus(success)); } @Override public void failed(UnirestException e) { } @Override public void cancelled() { } }); } private void updateUserData() { userData.run(() -> { server.broadcast(new Packet.ServerUsers(server.getConnections().size())); }); } private void sendCooldownData(WebSocketChannel channel, User user) { server.send(channel, new Packet.ServerCooldown(user.getRemainingCooldown())); } private void sendCooldownData(User user) { for (WebSocketChannel ch: user.getConnections()) { sendCooldownData(ch, user); } } private void broadcastPixelUpdate(int x, int y, int color) { server.broadcast(new Packet.ServerPlace(Collections.singleton(new Packet.ServerPlace.Pixel(x, y, color)))); } }
package tars.logic.commands; import tars.commons.core.Messages; import tars.commons.core.UnmodifiableObservableList; import tars.commons.exceptions.DuplicateTaskException; import tars.commons.flags.Flag; import tars.commons.util.MarkTaskTracker; import tars.model.task.*; import java.util.ArrayList; /** * Marks a task identified using it's last displayed index from tars as done or * undone. * * @@author A0121533W */ public class MarkCommand extends Command { public static final String COMMAND_WORD = "mark"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": mark a task as done or undone." + "Parameters: -do <INDEX>[ <INDEX> <INDEX> ...] -ud <INDEX>[ <INDEX> <INDEX> …]\n" + "Parameters: -do <START_INDEX>..<END_INDEX> -ud <START_INDEX>..<END_INDEX>\n" + "Example: " + COMMAND_WORD + " -do 3 5 7 -ud 2 4 6\n" + "OR " + COMMAND_WORD + " -do 1..3 -ud 4..6"; private String markDone; private String markUndone; private MarkTaskTracker tracker; /** * Convenience constructor using raw values. * * @throws InvalidRangeException */ public MarkCommand(String markDone, String markUndone) { this.markDone = markDone.replace(Flag.DONE, " ").trim(); this.markUndone = markUndone.replace(Flag.UNDONE, " ").trim(); this.tracker = new MarkTaskTracker(); } /** * Get string of indexes separated by spaces given a start and end index */ private String rangeIndexString(String range) throws InvalidRangeException { if (!range.contains("..")) { return range; } String rangeToReturn = ""; int toIndex = range.indexOf(".."); String start = range.substring(0, toIndex); String end = range.substring(toIndex + 2); int startInt = Integer.parseInt(start); int endInt = Integer.parseInt(end); if (startInt > endInt) { throw new InvalidRangeException(); } for (int i = startInt; i <= endInt; i++) { rangeToReturn += String.valueOf(i) + " "; } return rangeToReturn.trim(); } @Override public CommandResult execute() { assert model != null; if (!this.markDone.equals("") || !this.markUndone.equals("")) { if (!this.markDone.equals("")) { try { Status done = new Status(true); String markDone = rangeIndexString(this.markDone); ArrayList<ReadOnlyTask> markDoneTasks = getTasksFromIndexes(markDone.split(" "), done); model.mark(markDoneTasks, Flag.DONE); } catch (InvalidTaskDisplayedException e) { return new CommandResult(e.getMessage()); } catch (DuplicateTaskException dte) { return new CommandResult(dte.getMessage()); } catch (InvalidRangeException ire) { return new CommandResult(ire.getMessage()); } } if (!this.markUndone.equals("")) { try { Status undone = new Status(false); String markUndone = rangeIndexString(this.markUndone); ArrayList<ReadOnlyTask> markUndoneTasks = getTasksFromIndexes(markUndone.split(" "), undone); model.mark(markUndoneTasks, Flag.UNDONE); } catch (InvalidTaskDisplayedException e) { return new CommandResult(e.getMessage()); } catch (DuplicateTaskException dte) { return new CommandResult(dte.getMessage()); } catch (InvalidRangeException ire) { return new CommandResult(ire.getMessage()); } } return new CommandResult(getResult()); } return new CommandResult(getResult()); } /** * Prepares feedback message to user * * @return */ private String getResult() { String commandResult = tracker.getResult(); return commandResult; } /** * Gets Tasks to mark done or undone from indexes * * @param indexes * @return * @throws InvalidTaskDisplayedException */ private ArrayList<ReadOnlyTask> getTasksFromIndexes(String[] indexes, Status status) throws InvalidTaskDisplayedException { UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); ArrayList<ReadOnlyTask> tasksList = new ArrayList<ReadOnlyTask>(); for (int i = 0; i < indexes.length; i++) { int targetIndex = Integer.valueOf(indexes[i]); if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); throw new InvalidTaskDisplayedException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } ReadOnlyTask task = lastShownList.get(targetIndex - 1); if (!task.getStatus().equals(status)) { tasksList.add(task); tracker.addToMark(targetIndex, status); } else { tracker.addAlreadyMarked(targetIndex, status); } } return tasksList; } /** * Signals an index exceed the size of the internal list. */ public class InvalidTaskDisplayedException extends Exception { public InvalidTaskDisplayedException(String message) { super(message); } } /** * Signals invalid range entered */ public class InvalidRangeException extends Exception { private static final String MESSAGE_INVALID_RANGE = "Start index must be before end index"; public InvalidRangeException() { super(MESSAGE_INVALID_RANGE); } } }
package tf.gpx.edit.viewer; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Base64; import java.util.Iterator; import java.util.List; import java.util.Set; import javafx.css.PseudoClass; import javafx.geometry.BoundingBox; import javafx.scene.CacheHint; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.Border; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.tuple.Pair; import tf.gpx.edit.helper.EarthGeometry; import tf.gpx.edit.helper.GPXEditorPreferences; import tf.gpx.edit.items.GPXLineItem; import tf.gpx.edit.items.GPXRoute; import tf.gpx.edit.items.GPXTrack; import tf.gpx.edit.items.GPXTrackSegment; import tf.gpx.edit.items.GPXWaypoint; import tf.gpx.edit.main.GPXEditor; /** * Helper class to hold stuff required by both HeightChart and LineChart * @author thomas */ public interface IChartBasics<T extends XYChart> { static String DATA_SEP = "-"; static String SHIFT_NODE = "ShiftNode"; public static enum ChartType { HEIGHTCHART, SPEEDCHART; } public static enum ColorPseudoClass { BLACK(PseudoClass.getPseudoClass("line-color-Black")), DARKRED(PseudoClass.getPseudoClass("line-color-DarkRed")), DARKGREEN(PseudoClass.getPseudoClass("line-color-DarkGreen")), DARKYELLOW(PseudoClass.getPseudoClass("line-color-GoldenRod")), DARKBLUE(PseudoClass.getPseudoClass("line-color-DarkBlue")), DARKMAGENTA(PseudoClass.getPseudoClass("line-color-DarkMagenta")), DARKCYAN(PseudoClass.getPseudoClass("line-color-DarkCyan")), DARKGRAY(PseudoClass.getPseudoClass("line-color-DarkGray")), LIGHTGRAY(PseudoClass.getPseudoClass("line-color-LightGray")), RED(PseudoClass.getPseudoClass("line-color-Red")), GREEN(PseudoClass.getPseudoClass("line-color-Green")), YELLOW(PseudoClass.getPseudoClass("line-color-Yellow")), BLUE(PseudoClass.getPseudoClass("line-color-Blue")), MAGENTA(PseudoClass.getPseudoClass("line-color-Magenta")), CYAN(PseudoClass.getPseudoClass("line-color-Cyan")), WHITE(PseudoClass.getPseudoClass("line-color-White")), SILVER(PseudoClass.getPseudoClass("line-color-Silver")); private final PseudoClass myPseudoClass; ColorPseudoClass(final PseudoClass pseudoClass) { myPseudoClass = pseudoClass; } public PseudoClass getPseudoClass() { return myPseudoClass; } public static PseudoClass getPseudoClassForColorName(final String colorName) { PseudoClass result = BLACK.getPseudoClass(); for (ColorPseudoClass color : ColorPseudoClass.values()) { if (color.name().toUpperCase().equals(colorName.toUpperCase())) { result = color.getPseudoClass(); } } return result; } } default void initialize() { getChart().setVisible(false); getChart().setAnimated(false); getChart().setCache(true); getChart().setCacheShape(true); getChart().setCacheHint(CacheHint.SPEED); getChart().setLegendVisible(false); getChart().setCursor(Cursor.DEFAULT); getChart().getXAxis().setAnimated(false); getChart().getYAxis().setAnimated(false); } // what any decent CHart needs to implement public abstract List<GPXLineItem> getGPXLineItems(); public void setGPXLineItems(final List<GPXLineItem> lineItems); public abstract double getMinimumDistance(); public abstract void setMinimumDistance(final double value); public abstract double getMaximumDistance(); public abstract void setMaximumDistance(final double value); public abstract double getMinimumYValue(); public abstract void setMinimumYValue(final double value); public abstract double getMaximumYValue(); public abstract void setMaximumYValue(final double value); public abstract List<Pair<GPXWaypoint, Double>> getPoints(); public abstract ChartsPane getChartsPane(); public abstract void setChartsPane(final ChartsPane pane); // only extensions of XYChart allowed public abstract T getChart(); public abstract Iterator<XYChart.Data<Double, Double>> getDataIterator(final XYChart.Series<Double, Double> series); // as default I don't shown file waypoints default boolean fileWaypointsInChart() { return false; } public abstract void setCallback(final GPXEditor gpxEditor); default void setEnable(final boolean enabled) { getChart().setDisable(!enabled); getChart().setVisible(enabled); getChart().toFront(); } @SuppressWarnings("unchecked") default void setGPXWaypoints(final List<GPXLineItem> lineItems, final boolean doFitBounds) { setGPXLineItems(lineItems); if (getChart().isDisabled()) { return; } // invisble update - much faster getChart().setVisible(false); getPoints().clear(); getChart().getData().clear(); // TFE, 20191230: avoid mess up when metadata is selected - nothing todo after clearing if (CollectionUtils.isEmpty(lineItems) || GPXLineItem.GPXLineItemType.GPXMetadata.equals(lineItems.get(0).getType())) { // nothing more todo... return; } setMinimumDistance(0d); setMaximumDistance(0d); setMinimumYValue(Double.MAX_VALUE); setMaximumYValue(Double.MIN_VALUE); final boolean alwaysShowFileWaypoints = Boolean.valueOf(GPXEditorPreferences.ALWAYS_SHOW_FILE_WAYPOINTS.get()); // TFE, 20191112: create series per track & route to be able to handle different colors final List<XYChart.Series<Double, Double>> seriesList = new ArrayList<>(); // TFE, 20200212: file waypoints need special treatment // need to calculate distance from other waypoints to show correctly on chart XYChart.Series<Double, Double> fileWaypointSeries = null; // show file waypoints only once boolean fileShown = false; for (GPXLineItem lineItem : lineItems) { // only files can have file waypoints if (fileWaypointsInChart()) { if (GPXLineItem.GPXLineItemType.GPXFile.equals(lineItem.getType())) { fileWaypointSeries = getXYChartSeriesForGPXLineItem(lineItem); } else if (alwaysShowFileWaypoints && !fileShown) { // add file waypoints as well, even though file isn't selected fileWaypointSeries = getXYChartSeriesForGPXLineItem(lineItem.getGPXFile()); fileShown = true; } } if (GPXLineItem.GPXLineItemType.GPXFile.equals(lineItem.getType()) || GPXLineItem.GPXLineItemType.GPXTrack.equals(lineItem.getType())) { for (GPXTrack gpxTrack : lineItem.getGPXTracks()) { // add track segments individually for (GPXTrackSegment gpxTrackSegment : gpxTrack.getGPXTrackSegments()) { seriesList.add(getXYChartSeriesForGPXLineItem(gpxTrackSegment)); } } } // track segments can have waypoints if (GPXLineItem.GPXLineItemType.GPXTrackSegment.equals(lineItem.getType())) { seriesList.add(getXYChartSeriesForGPXLineItem(lineItem)); } // files and routes can have routes if (GPXLineItem.GPXLineItemType.GPXFile.equals(lineItem.getType()) || GPXLineItem.GPXLineItemType.GPXRoute.equals(lineItem.getType())) { for (GPXRoute gpxRoute : lineItem.getGPXRoutes()) { seriesList.add(getXYChartSeriesForGPXLineItem(gpxRoute)); } } } if (fileWaypointSeries != null && CollectionUtils.isNotEmpty(fileWaypointSeries.getData())) { // get the required preferences final int waypointIconSize = Integer.valueOf(GPXEditorPreferences.WAYPOINT_ICON_SIZE.get()); final int waypointLabelSize = Integer.valueOf(GPXEditorPreferences.WAYPOINT_LABEL_SIZE.get()); final int waypointLabelAngle = Integer.valueOf(GPXEditorPreferences.WAYPOINT_LABEL_ANGLE.get()); final int waypointThreshold = Integer.valueOf(GPXEditorPreferences.WAYPOINT_THRESHOLD.get()); // merge seriesList into one big series to iterate all in one loop XYChart.Series<Double, Double> flatSeries = new XYChart.Series<>(); for (XYChart.Series<Double, Double> series : seriesList) { flatSeries.getData().addAll(series.getData()); } for (XYChart.Data<Double, Double> data : fileWaypointSeries.getData()) { // 1. check file waypoints against other waypoints for minimum distance final GPXWaypoint fileWaypoint = (GPXWaypoint) data.getExtraValue(); XYChart.Data<Double, Double> closest = null; double mindistance = Double.MAX_VALUE; for (XYChart.Data<Double, Double> waypoint : flatSeries.getData()) { final double distance = EarthGeometry.distanceGPXWaypoints(fileWaypoint, (GPXWaypoint) waypoint.getExtraValue()); if (distance < mindistance) { closest = waypoint; mindistance = distance; } } if (closest != null && (mindistance < waypointThreshold || waypointThreshold == 0)) { // System.out.println(fileWaypointSeries.getData().indexOf(data) + 1 + ": " + fileWaypoint.getName() + ", " + ((GPXWaypoint) closest.getExtraValue()).getID() + ", " + closest.getXValue()); data.setXValue(closest.getXValue()); // 2. add text & icon as label to node final Label text = new Label(fileWaypoint.getName()); text.getStyleClass().add("item-id"); text.setFont(Font.font("Verdana", waypointLabelSize)); text.setRotate(360.0 - waypointLabelAngle); text.setBorder(Border.EMPTY); text.setBackground(Background.EMPTY); text.setVisible(true); text.setMouseTransparent(true); // nodes are shown center-center aligned, hack needed to avoid that text.setUserData(SHIFT_NODE); // add waypoint icon final String iconBase64 = MarkerManager.getInstance().getIcon(MarkerManager.getInstance().getMarkerForSymbol(fileWaypoint.getSym()).getIconName()); final Image image = new Image(new ByteArrayInputStream(Base64.getDecoder().decode(iconBase64)), waypointIconSize, waypointIconSize, false, false); text.setGraphic(new ImageView(image)); text.setGraphicTextGap(0); data.setNode(text); } // add each file waypoint as own series - we don't want to have aera or linees drawn... final XYChart.Series<Double, Double> series = new XYChart.Series<>(); series.getData().add(data); setSeriesUserData(series, fileWaypoint); seriesList.add(series); } } int dataCount = 0; for (XYChart.Series<Double, Double> series : seriesList) { dataCount += series.getData().size(); } showData(seriesList, dataCount); setAxis(getMinimumDistance(), getMaximumDistance(), getMinimumYValue(), getMaximumYValue()); // hide heightchart of no waypoints have been set getChart().setVisible(dataCount > 0); } @SuppressWarnings("unchecked") private void showData(final List<XYChart.Series<Double, Double>> seriesList, final int dataCount) { // TFE, 20180516: ignore fileWaypointsCount in count of wwaypoints to show. Otherwise no trackSegments get shown if already enough waypoints... // file fileWaypointsCount don't count into MAX_WAYPOINTS //final long fileWaypointsCount = lineItem.getCombinedGPXWaypoints(GPXLineItem.GPXLineItemType.GPXFile).size(); //final double ratio = (GPXTrackviewer.MAX_WAYPOINTS - fileWaypointsCount) / (lineItem.getCombinedGPXWaypoints(null).size() - fileWaypointsCount); // TFE, 20190819: make number of waypoints to show a preference final double ratio = Double.valueOf(GPXEditorPreferences.MAX_WAYPOINTS_TO_SHOW.get()) / // might have no waypoints at all... Math.max(dataCount, 1); // TFE, 20191125: only show up to GPXEditorPreferenceStore.MAX_WAYPOINTS_TO_SHOW wayoints // similar logic to TrackMap.showWaypoints - could maybe be abstracted int count = 0, i = 0, j = 0; for (XYChart.Series<Double, Double> series : seriesList) { if (!series.getData().isEmpty()) { final XYChart.Series<Double, Double> reducedSeries = new XYChart.Series<>(); reducedSeries.setName(series.getName()); final GPXWaypoint firstWaypoint = (GPXWaypoint) series.getData().get(0).getExtraValue(); if (firstWaypoint.isGPXFileWaypoint()) { // we show all file waypoints reducedSeries.getData().addAll(series.getData()); } else { // we only show a subset of other waypoints - up to MAX_WAYPOINTS for (XYChart.Data<Double, Double> data : series.getData()) { i++; if (i * ratio >= count) { reducedSeries.getData().add(data); count++; } } } getChart().getData().add(reducedSeries); if (!GPXLineItem.GPXLineItemType.GPXFile.equals(firstWaypoint.getType())) { // and now color the series nodes according to lineitem color final PseudoClass color = IChartBasics.ColorPseudoClass.getPseudoClassForColorName(getSeriesColor(reducedSeries)); reducedSeries.getNode().pseudoClassStateChanged(color, true); Set<Node> nodes = getChart().lookupAll(".series" + j); for (Node n : nodes) { n.pseudoClassStateChanged(color, true); } } j++; } } // add labels to series on base chart if (getChartsPane().getBaseChart().equals(this)) { for (XYChart.Series<Double, Double> series : seriesList) { // only if not empty and not for file waypoints if (!series.getData().isEmpty() && !((GPXWaypoint) series.getData().get(0).getExtraValue()).isGPXFileWaypoint()) { // add item ID as text "in the middle" of the waypoints above x-axis - for base chart final Text text = new Text(getSeriesID(series)); text.getStyleClass().add("item-id"); text.setFont(Font.font("Verdana", 9)); text.setTextAlignment(TextAlignment.LEFT); text.setRotate(270.0); text.setVisible(true); text.setMouseTransparent(true); // calculate "middle" for x and 10% above lower for y final double xPosText = (series.getData().get(0).getXValue() + series.getData().get(series.getData().size()-1).getXValue()) / 2.0; if (xPosText > 0.0) { // add data point with this text as node final XYChart.Data<Double, Double> idLabel = new XYChart.Data<>(xPosText, getChart().getYAxis().getZeroPosition()); idLabel.setExtraValue((GPXWaypoint) series.getData().get(0).getExtraValue()); idLabel.setNode(text); // add each label as own series - we don't want to have aera or linees drawn... final XYChart.Series<Double, Double> idSeries = new XYChart.Series<>(); idSeries.getData().add(idLabel); getChart().getData().add(idSeries); } } } } // final AtomicInteger shownCount = new AtomicInteger(0); // getChart().getData().forEach((t) -> { // XYChart.Series<Double, Double> series = (XYChart.Series<Double, Double>) t; // shownCount.set(shownCount.get() + series.getData().size()); // System.out.println("Datapoints added: " + shownCount.get()); } @SuppressWarnings("unchecked") default void adaptLayout() { // shift nodes to center-left from center-center getChart().getData().forEach((t) -> { final XYChart.Series<Double, Double> series = (XYChart.Series<Double, Double>) t; for (Iterator<XYChart.Data<Double, Double>> it = getDataIterator(series); it.hasNext(); ) { XYChart.Data<Double, Double> data = it.next(); final double xVal = getChart().getXAxis().getDisplayPosition(data.getXValue()); final double yVal = getChart().getYAxis().getDisplayPosition(data.getYValue()); if (Double.isNaN(xVal) || Double.isNaN(yVal)) { continue; } Node symbol = data.getNode(); if (symbol != null && SHIFT_NODE.equals((String) symbol.getUserData())) { symbol.applyCss(); // inverse of relocate to get original x / y values // setLayoutX(x - getLayoutBounds().getMinX()); // setLayoutY(y - getLayoutBounds().getMinY()); final double x = symbol.getLayoutX() + symbol.getLayoutBounds().getMinX(); final double y = symbol.getLayoutY() + symbol.getLayoutBounds().getMinY(); final double w = symbol.prefWidth(-1); final double h = symbol.prefHeight(-1); // shift h/2 against previous y value // symbol.resizeRelocate(x-(w/2), y-(h/2),w,h); // factor in getRotate() to calculate vertical shift value! // 0 degrees: -(h/2) // 90 degrees: -(w/2) // 180 degrees: -(h/2) // 270 degrees: -(w/2) // => cos(getRotate()) * (-h/2) + sin(getRotate()) * (-w/2) // => - abs(cos(getRotate()) * h/2 + sin(getRotate()) * w/2) final double angle = symbol.getRotate() * Math.PI / 180.0; final double shiftValue = Math.abs(Math.cos(angle) * h/2.0 + Math.sin(angle) * w/2.0); // System.out.println("Shifting node: " + ((GPXWaypoint) data.getExtraValue()).getName() + " by " + shiftValue + " instead " + w/2.0); symbol.setLayoutY(symbol.getLayoutY() - shiftValue); } } }); } @SuppressWarnings("unchecked") default boolean hasData() { boolean result = false; final List<XYChart.Series<Double, Double>> seriesList = (List<XYChart.Series<Double, Double>>) getChart().getData(); for (XYChart.Series<Double, Double> series: seriesList) { if (!series.getData().isEmpty()) { result = true; break; } } return result; } private XYChart.Series<Double, Double> getXYChartSeriesForGPXLineItem(final GPXLineItem lineItem) { final List<XYChart.Data<Double, Double>> dataList = new ArrayList<>(); for (GPXWaypoint gpxWaypoint : lineItem.getGPXWaypoints()) { setMaximumDistance(getMaximumDistance() + gpxWaypoint.getDistance()); final double yValue = getYValueAndSetMinMax(gpxWaypoint); XYChart.Data<Double, Double> data = new XYChart.Data<>(getMaximumDistance() / 1000.0, yValue); data.setExtraValue(gpxWaypoint); dataList.add(data); getPoints().add(Pair.of(gpxWaypoint, getMaximumDistance())); } final XYChart.Series<Double, Double> series = new XYChart.Series<>(); series.getData().addAll(dataList); setSeriesUserData(series, lineItem); return series; } private static void setSeriesUserData(final XYChart.Series<Double, Double> series, final GPXLineItem lineItem) { String seriesID = lineItem.getCombinedID(); // add track id for track segments if (GPXLineItem.GPXLineItemType.GPXTrackSegment.equals(lineItem.getType())) { seriesID = lineItem.getParent().getCombinedID() + "." + seriesID; } series.setName(seriesID + DATA_SEP + lineItem.getColor()); } private static String getSeriesID(final XYChart.Series<Double, Double> series) { return series.getName().split(DATA_SEP)[0]; } private static String getSeriesColor(final XYChart.Series<Double, Double> series) { return series.getName().split(DATA_SEP)[1]; } public abstract double getYValueAndSetMinMax(final GPXWaypoint gpxWaypoint); default void setAxis(final double minDist, final double maxDist, final double minHght, final double maxHght) { double distance = maxDist - minDist; // calculate scaling for ticks so their number is smaller than 25 double tickUnit = 1.0; if (distance / 1000.0 > 24.9) { tickUnit = 2.0; } if (distance / 1000.0 > 49.9) { tickUnit = 5.0; } if (distance / 1000.0 > 499.9) { tickUnit = 50.0; } if (distance / 1000.0 > 4999.9) { tickUnit = 500.0; } ((NumberAxis) getChart().getXAxis()).setTickUnit(tickUnit); // TFE, 20181124: set lower limit as well since it might have changed in setViewLimits ((NumberAxis) getChart().getXAxis()).setLowerBound(minDist / 1000.0); ((NumberAxis) getChart().getXAxis()).setUpperBound(maxDist / 1000.0); // System.out.println("minHght: " + minHght + ", maxHght:" + maxHght); ((NumberAxis) getChart().getYAxis()).setTickUnit(10.0); ((NumberAxis) getChart().getYAxis()).setLowerBound(minHght); ((NumberAxis) getChart().getYAxis()).setUpperBound(maxHght); } @SuppressWarnings("unchecked") default XYChart.Data<Double, Double> getNearestDataForXValue(final Double xValue) { final List<XYChart.Series<Double, Double>> seriesList = (List<XYChart.Series<Double, Double>>) getChart().getData(); XYChart.Data<Double, Double> nearestData = null; double distance = Double.MAX_VALUE; for (XYChart.Series<Double, Double> series: seriesList) { for (XYChart.Data<Double, Double> data : series.getData()) { double xData = data.getXValue(); double dataDistance = Math.abs(xValue - xData); if (dataDistance < distance) { distance = dataDistance; nearestData = data; } } } return nearestData; } // set lineStart bounding box to limit which waypoints are shown // or better: to define, what min and max x-axis to use default void setViewLimits(final BoundingBox newBoundingBox) { if (getPoints().isEmpty()) { // nothing to show yet... return; } // init with maximum values double minDist = getMinimumDistance(); double maxDist = getMaximumDistance(); double minHght = getMinimumYValue(); double maxHght = getMaximumYValue(); if (newBoundingBox != null) { minHght = Double.MAX_VALUE; maxHght = Double.MIN_VALUE; boolean waypointFound = false; // 1. iterate over myPoints for (Pair<GPXWaypoint, Double> point: getPoints()) { GPXWaypoint waypoint = point.getLeft(); if (!waypoint.isGPXFileWaypoint() && newBoundingBox.contains(waypoint.getLatitude(), waypoint.getLongitude())) { // 2. if waypoint in bounding box: // if first waypoint use this for minDist // use this for maxDist if (!waypointFound) { minDist = point.getRight(); } maxDist = point.getRight(); final double elevation = waypoint.getElevation(); minHght = Math.min(minHght, elevation); maxHght = Math.max(maxHght, elevation); waypointFound = true; } if (!waypointFound) { minDist = 0.0; maxDist = 0.0; } } // if no waypoint in bounding box show nothing } setAxis(minDist, maxDist, minHght, maxHght); } @SuppressWarnings("unchecked") default void updateGPXWaypoints(final List<GPXWaypoint> gpxWaypoints) { // TODO: fill with life } default void setSelectedGPXWaypoints(final List<GPXWaypoint> gpxWaypoints, final Boolean highlightIfHidden, final Boolean useLineMarker) { if (getChart().isDisabled()) { return; } } default void clearSelectedGPXWaypoints() { if (getChart().isDisabled()) { return; } } default void updateLineColor(final GPXLineItem lineItem) { // nothing todo } default void loadPreferences() { // nothing todo } default void savePreferences() { // nothing todo } }
package tigase.db.jdbc; import tigase.db.AuthRepository; import tigase.db.AuthorizationException; import tigase.db.DBInitException; import tigase.db.DataRepository; import tigase.db.RepositoryFactory; import tigase.db.TigaseDBException; import tigase.db.UserExistsException; import tigase.db.UserNotFoundException; import tigase.util.Algorithms; import tigase.util.Base64; import tigase.util.TigaseStringprepException; import tigase.xmpp.BareJID; import static tigase.db.AuthRepository.*; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.RealmCallback; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; /** * The user authentication connector allows for customized SQL queries to be * used. Queries are defined in the configuration file and they can be either * plain SQL queries or stored procedures. * * If the query starts with characters: <code>{ call</code> then the server * assumes this is a stored procedure call, otherwise it is executed as a plain * SQL query. Each configuration value is stripped from white characters on both * ends before processing. * * Please don't use semicolon <code>';'</code> at the end of the query as many * JDBC drivers get confused and the query may not work for unknown obvious * reason. * * Some queries take arguments. Arguments are marked by question marks * <code>'?'</code> in the query. Refer to the configuration parameters * description for more details about what parameters are expected in each * query. * * Example configuration. * * The first example shows how to put a stored procedure as a query with 2 * required parameters. * * <pre> * add-user-query={ call TigAddUserPlainPw(?, ?) } * </pre> * * The same query with plain SQL parameters instead: * * <pre> * add-user-query=insert into users (user_id, password) values (?, ?) * </pre> * * Created: Sat Nov 11 22:22:04 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class TigaseCustomAuth implements AuthRepository { /** * Private logger for class instances. */ private static final Logger log = Logger.getLogger(TigaseCustomAuth.class.getName()); /** * Query executing periodically to ensure active connection with the database. * * Takes no arguments. * * Example query: * * <pre> * select 1 * </pre> */ public static final String DEF_CONNVALID_KEY = "conn-valid-query"; /** * Database initialization query which is run after the server is started. * * Takes no arguments. * * Example query: * * <pre> * update tig_users set online_status = 0 * </pre> */ public static final String DEF_INITDB_KEY = "init-db-query"; /** * Query adding a new user to the database. * * Takes 2 arguments: <code>(user_id (JID), password)</code> * * Example query: * * <pre> * insert into tig_users (user_id, user_pw) values (?, ?) * </pre> */ public static final String DEF_ADDUSER_KEY = "add-user-query"; /** * Removes a user from the database. * * Takes 1 argument: <code>(user_id (JID))</code> * * Example query: * * <pre> * delete from tig_users where user_id = ? * </pre> */ public static final String DEF_DELUSER_KEY = "del-user-query"; /** * Retrieves user password from the database for given user_id (JID). * * Takes 1 argument: <code>(user_id (JID))</code> * * Example query: * * <pre> * select user_pw from tig_users where user_id = ? * </pre> */ public static final String DEF_GETPASSWORD_KEY = "get-password-query"; /** * Updates (changes) password for a given user_id (JID). * * Takes 2 arguments: <code>(password, user_id (JID))</code> * * Example query: * * <pre> * update tig_users set user_pw = ? where user_id = ? * </pre> */ public static final String DEF_UPDATEPASSWORD_KEY = "update-password-query"; /** * Performs user login. Normally used when there is a special SP used for this * purpose. This is an alternative way to a method requiring retrieving user * password. Therefore at least one of those queries must be defined: * <code>user-login-query</code> or <code>get-password-query</code>. * * If both queries are defined then <code>user-login-query</code> is used. * Normally this method should be only used with plain text password * authentication or sasl-plain. * * The Tigase server expects a result set with user_id to be returned from the * query if login is successful and empty results set if the login is * unsuccessful. * * Takes 2 arguments: <code>(user_id (JID), password)</code> * * Example query: * * <pre> * select user_id from tig_users where (user_id = ?) AND (user_pw = ?) * </pre> */ public static final String DEF_USERLOGIN_KEY = "user-login-query"; /** * This query is called when user logs out or disconnects. It can record that * event in the database. * * Takes 1 argument: <code>(user_id (JID))</code> * * Example query: * * <pre> * update tig_users, set online_status = online_status - 1 where user_id = ? * </pre> */ public static final String DEF_USERLOGOUT_KEY = "user-logout-query"; /** Field description */ public static final String DEF_USERS_COUNT_KEY = "users-count-query"; /** Field description */ public static final String DEF_USERS_DOMAIN_COUNT_KEY = "" + "users-domain-count-query"; /** * Comma separated list of NON-SASL authentication mechanisms. Possible * mechanisms are: <code>password</code> and <code>digest</code>. * <code>digest</code> mechanism can work only with * <code>get-password-query</code> active and only when password are stored in * plain text format in the database. */ public static final String DEF_NONSASL_MECHS_KEY = "non-sasl-mechs"; /** * Comma separated list of SASL authentication mechanisms. Possible mechanisms * are all mechanisms supported by Java implementation. The most common are: * <code>PLAIN</code>, <code>DIGEST-MD5</code>, <code>CRAM-MD5</code>. * * "Non-PLAIN" mechanisms will work only with the * <code>get-password-query</code> active and only when passwords are stored * in plain text format in the database. */ public static final String DEF_SASL_MECHS_KEY = "sasl-mechs"; public static final String NO_QUERY = "none"; /** Field description */ public static final String DEF_INITDB_QUERY = "{ call TigInitdb() }"; /** Field description */ public static final String DEF_ADDUSER_QUERY = "{ call TigAddUserPlainPw(?, ?) }"; /** Field description */ public static final String DEF_DELUSER_QUERY = "{ call TigRemoveUser(?) }"; /** Field description */ public static final String DEF_GETPASSWORD_QUERY = "{ call TigGetPassword(?) }"; /** Field description */ public static final String DEF_UPDATEPASSWORD_QUERY = "{ call TigUpdatePasswordPlainPwRev(?, ?) }"; /** Field description */ public static final String DEF_USERLOGIN_QUERY = "{ call TigUserLoginPlainPw(?, ?) }"; /** Field description */ public static final String DEF_USERLOGOUT_QUERY = "{ call TigUserLogout(?) }"; /** Field description */ public static final String DEF_USERS_COUNT_QUERY = "{ call TigAllUsersCount() }"; /** Field description */ public static final String DEF_USERS_DOMAIN_COUNT_QUERY = "" + "select count(*) from tig_users where user_id like ?"; /** Field description */ public static final String DEF_NONSASL_MECHS = "password"; /** Field description */ public static final String DEF_SASL_MECHS = "PLAIN"; /** Field description */ public static final String SP_STARTS_WITH = "{ call"; private DataRepository data_repo = null; private String initdb_query = DEF_INITDB_QUERY; private String getpassword_query = DEF_GETPASSWORD_QUERY; private String deluser_query = DEF_DELUSER_QUERY; private String adduser_query = DEF_ADDUSER_QUERY; private String updatepassword_query = DEF_UPDATEPASSWORD_QUERY; private String userlogin_query = DEF_USERLOGIN_QUERY; private String userdomaincount_query = DEF_USERS_DOMAIN_COUNT_QUERY; // It is better just to not call the query if it is not defined by the user // By default it is null then and not called. private String userlogout_query = null; private String userscount_query = DEF_USERS_COUNT_QUERY; private boolean userlogin_active = false; // private String userlogout_query = DEF_USERLOGOUT_QUERY; private String[] sasl_mechs = DEF_SASL_MECHS.split(","); private String[] nonsasl_mechs = DEF_NONSASL_MECHS.split(","); /** * Describe <code>addUser</code> method here. * * @param user * a <code>String</code> value * @param password * a <code>String</code> value * @exception UserExistsException * if an error occurs * @exception TigaseDBException * if an error occurs */ @Override public void addUser(BareJID user, final String password) throws UserExistsException, TigaseDBException { if (adduser_query == null) { return; } ResultSet rs = null; try { PreparedStatement add_user = data_repo.getPreparedStatement(user, adduser_query); synchronized (add_user) { add_user.setString(1, user.toString()); add_user.setString(2, password); boolean is_result = add_user.execute(); if (is_result) { rs = add_user.getResultSet(); } } } catch (SQLIntegrityConstraintViolationException e) { throw new UserExistsException( "Error while adding user to repository, user exists?", e); } catch (SQLException e) { throw new TigaseDBException("Problem accessing repository.", e); } finally { data_repo.release(null, rs); } } /** * Describe <code>digestAuth</code> method here. * * @param user * a <code>String</code> value * @param digest * a <code>String</code> value * @param id * a <code>String</code> value * @param alg * a <code>String</code> value * @return a <code>boolean</code> value * @exception UserNotFoundException * if an error occurs * @exception TigaseDBException * if an error occurs * @exception AuthorizationException * if an error occurs */ @Override @Deprecated public boolean digestAuth(BareJID user, final String digest, final String id, final String alg) throws UserNotFoundException, TigaseDBException, AuthorizationException { if (userlogin_active) { throw new AuthorizationException("Not supported."); } else { final String db_password = getPassword(user); try { final String digest_db_pass = Algorithms.hexDigest(id, db_password, alg); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Comparing passwords, given: {0}, db: {1}", new Object[] { digest, digest_db_pass }); } return digest.equals(digest_db_pass); } catch (NoSuchAlgorithmException e) { throw new AuthorizationException("No such algorithm.", e); } // end of try-catch } } /** * Method description * * * */ @Override public String getResourceUri() { return data_repo.getResourceUri(); } /** * <code>getUsersCount</code> method is thread safe. It uses local variable * for storing <code>Statement</code>. * * @return a <code>long</code> number of user accounts in database. */ @Override public long getUsersCount() { if (userscount_query == null) { return -1; } ResultSet rs = null; try { long users = -1; PreparedStatement users_count = data_repo.getPreparedStatement(null, userscount_query); synchronized (users_count) { // Load all user count from database rs = users_count.executeQuery(); if (rs.next()) { users = rs.getLong(1); } // end of while (rs.next()) } return users; } catch (SQLException e) { return -1; // throw new // TigaseDBException("Problem loading user list from repository", e); } finally { data_repo.release(null, rs); rs = null; } } /** * Method description * * * @param domain * * */ @Override public long getUsersCount(String domain) { if (userdomaincount_query == null) { return -1; } ResultSet rs = null; try { long users = -1; PreparedStatement users_domain_count = data_repo.getPreparedStatement(null, userdomaincount_query); synchronized (users_domain_count) { // Load all user count from database users_domain_count.setString(1, "%@" + domain); rs = users_domain_count.executeQuery(); if (rs.next()) { users = rs.getLong(1); } // end of while (rs.next()) } return users; } catch (SQLException e) { return -1; // throw new // TigaseDBException("Problem loading user list from repository", e); } finally { data_repo.release(null, rs); rs = null; } } /** * Describe <code>initRepository</code> method here. * * @param connection_str * a <code>String</code> value * @param params * @exception DBInitException * if an error occurs */ @Override public void initRepository(final String connection_str, Map<String, String> params) throws DBInitException { try { data_repo = RepositoryFactory.getDataRepository(null, connection_str, params); initdb_query = getParamWithDef(params, DEF_INITDB_KEY, DEF_INITDB_QUERY); if (initdb_query != null) { data_repo.initPreparedStatement(initdb_query, initdb_query); } adduser_query = getParamWithDef(params, DEF_ADDUSER_KEY, DEF_ADDUSER_QUERY); if ((adduser_query != null)) { data_repo.initPreparedStatement(adduser_query, adduser_query); } deluser_query = getParamWithDef(params, DEF_DELUSER_KEY, DEF_DELUSER_QUERY); if ((deluser_query != null)) { data_repo.initPreparedStatement(deluser_query, deluser_query); } getpassword_query = getParamWithDef(params, DEF_GETPASSWORD_KEY, DEF_GETPASSWORD_QUERY); if ((getpassword_query != null)) { data_repo.initPreparedStatement(getpassword_query, getpassword_query); } updatepassword_query = getParamWithDef(params, DEF_UPDATEPASSWORD_KEY, DEF_UPDATEPASSWORD_QUERY); if ((updatepassword_query != null)) { data_repo.initPreparedStatement(updatepassword_query, updatepassword_query); } userlogin_query = getParamWithDef(params, DEF_USERLOGIN_KEY, DEF_USERLOGIN_QUERY); if (userlogin_query != null) { data_repo.initPreparedStatement(userlogin_query, userlogin_query); userlogin_active = true; } userlogout_query = getParamWithDef(params, DEF_USERLOGOUT_KEY, DEF_USERLOGOUT_QUERY); if ((userlogout_query != null)) { data_repo.initPreparedStatement(userlogout_query, userlogout_query); } userscount_query = getParamWithDef(params, DEF_USERS_COUNT_KEY, DEF_USERS_COUNT_QUERY); if ((userscount_query != null)) { data_repo.initPreparedStatement(userscount_query, userscount_query); } userdomaincount_query = getParamWithDef(params, DEF_USERS_DOMAIN_COUNT_KEY, DEF_USERS_DOMAIN_COUNT_QUERY); if ((userdomaincount_query != null)) { data_repo.initPreparedStatement(userdomaincount_query, userdomaincount_query); } nonsasl_mechs = getParamWithDef(params, DEF_NONSASL_MECHS_KEY, DEF_NONSASL_MECHS).split(","); sasl_mechs = getParamWithDef(params, DEF_SASL_MECHS_KEY, DEF_SASL_MECHS).split(","); if ((params != null) && (params.get("init-db") != null)) { initDb(); } } catch (Exception e) { data_repo = null; throw new DBInitException( "Problem initializing jdbc connection: " + connection_str, e); } } /** * Method description * * * @param user * * @throws TigaseDBException * @throws UserNotFoundException */ @Override public void logout(BareJID user) throws UserNotFoundException, TigaseDBException { if (userlogout_query == null) { return; } try { PreparedStatement user_logout = data_repo.getPreparedStatement(user, userlogout_query); if (user_logout != null) { synchronized (user_logout) { user_logout.setString(1, user.toString()); user_logout.execute(); } } } catch (SQLException e) { throw new TigaseDBException("Problem accessing repository.", e); } } /** * Describe <code>otherAuth</code> method here. * * @param props * a <code>Map</code> value * @return a <code>boolean</code> value * @exception UserNotFoundException * if an error occurs * @exception TigaseDBException * if an error occurs * @exception AuthorizationException * if an error occurs */ @Override public boolean otherAuth(final Map<String, Object> props) throws UserNotFoundException, TigaseDBException, AuthorizationException { String proto = (String) props.get(PROTOCOL_KEY); if (proto.equals(PROTOCOL_VAL_SASL)) { String mech = (String) props.get(MACHANISM_KEY); if (mech.equals("PLAIN")) { try { if (saslPlainAuth(props)) { return true; } else { throw new AuthorizationException("Authentication failed."); } } catch (TigaseStringprepException ex) { throw new AuthorizationException("Stringprep failed for: " + props, ex); } } else { return saslAuth(props); } } // end of if (proto.equals(PROTOCOL_VAL_SASL)) if (proto.equals(PROTOCOL_VAL_NONSASL)) { String password = (String) props.get(PASSWORD_KEY); BareJID user_id = (BareJID) props.get(USER_ID_KEY); if (password != null) { return plainAuth(user_id, password); } String digest = (String) props.get(DIGEST_KEY); if (digest != null) { String digest_id = (String) props.get(DIGEST_ID_KEY); return digestAuth(user_id, digest, digest_id, "SHA"); } } // end of if (proto.equals(PROTOCOL_VAL_SASL)) throw new AuthorizationException("Protocol is not supported."); } /** * Describe <code>plainAuth</code> method here. * * @param user * a <code>String</code> value * @param password * a <code>String</code> value * @return a <code>boolean</code> value * * @throws AuthorizationException * @exception UserNotFoundException * if an error occurs * @exception TigaseDBException * if an error occurs */ @Override @Deprecated public boolean plainAuth(BareJID user, final String password) throws UserNotFoundException, TigaseDBException, AuthorizationException { if (userlogin_active) { return userLoginAuth(user, password); } else { String db_password = getPassword(user); return (password != null) && (db_password != null) && db_password.equals(password); } } // Implementation of tigase.db.AuthRepository /** * Describe <code>queryAuth</code> method here. * * @param authProps * a <code>Map</code> value */ @Override public void queryAuth(final Map<String, Object> authProps) { String protocol = (String) authProps.get(PROTOCOL_KEY); if (protocol.equals(PROTOCOL_VAL_NONSASL)) { authProps.put(RESULT_KEY, nonsasl_mechs); } // end of if (protocol.equals(PROTOCOL_VAL_NONSASL)) if (protocol.equals(PROTOCOL_VAL_SASL)) { authProps.put(RESULT_KEY, sasl_mechs); } // end of if (protocol.equals(PROTOCOL_VAL_NONSASL)) } /** * Describe <code>removeUser</code> method here. * * @param user * a <code>String</code> value * @exception UserNotFoundException * if an error occurs * @exception TigaseDBException * if an error occurs */ @Override public void removeUser(BareJID user) throws UserNotFoundException, TigaseDBException { if (deluser_query == null) { return; } try { PreparedStatement remove_user = data_repo.getPreparedStatement(user, deluser_query); synchronized (remove_user) { remove_user.setString(1, user.toString()); remove_user.execute(); } } catch (SQLException e) { throw new TigaseDBException("Problem accessing repository.", e); } } /** * Describe <code>updatePassword</code> method here. * * @param user * a <code>String</code> value * @param password * a <code>String</code> value * @exception TigaseDBException * if an error occurs * @throws UserNotFoundException */ @Override public void updatePassword(BareJID user, final String password) throws UserNotFoundException, TigaseDBException { if (updatepassword_query == null) { return; } try { PreparedStatement update_pass = data_repo.getPreparedStatement(user, updatepassword_query); synchronized (update_pass) { update_pass.setString(1, password); update_pass.setString(2, user.toString()); update_pass.execute(); } } catch (SQLException e) { throw new TigaseDBException("Problem accessing repository.", e); } } protected String getParamWithDef(Map<String, String> params, String key, String def) { if (params == null) { return def; } String result = params.get(key); if (result != null) { log.log(Level.CONFIG, "Custom query loaded for ''{0}'': ''{1}''", new Object[] { key, result }); } else { result = def; log.log(Level.CONFIG, "Default query loaded for ''{0}'': ''{1}''", new Object[] { key, def }); } if (result != null) { result = result.trim(); if (result.isEmpty() || result.equals(NO_QUERY)) { result = null; } } return result; } public String getPassword(BareJID user) throws UserNotFoundException, TigaseDBException { if (getpassword_query == null) { return null; } ResultSet rs = null; try { PreparedStatement get_pass = data_repo.getPreparedStatement(user, getpassword_query); synchronized (get_pass) { get_pass.setString(1, user.toString()); rs = get_pass.executeQuery(); if (rs.next()) { return rs.getString(1); } else { throw new UserNotFoundException("User does not exist: " + user); } // end of if (isnext) else } } catch (SQLException e) { throw new TigaseDBException("Problem with retrieving user password.", e); } finally { data_repo.release(null, rs); } } private void initDb() throws SQLException { if (initdb_query == null) { return; } PreparedStatement init_db = data_repo.getPreparedStatement(null, initdb_query); synchronized (init_db) { init_db.executeUpdate(); } } private boolean saslAuth(final Map<String, Object> props) throws AuthorizationException { try { SaslServer ss = (SaslServer) props.get("SaslServer"); if (ss == null) { Map<String, String> sasl_props = new TreeMap<String, String>(); sasl_props.put(Sasl.QOP, "auth"); ss = Sasl.createSaslServer((String) props.get(MACHANISM_KEY), "xmpp", (String) props.get(SERVER_NAME_KEY), sasl_props, new SaslCallbackHandler( props)); props.put("SaslServer", ss); } // end of if (ss == null) String data_str = (String) props.get(DATA_KEY); byte[] in_data = ((data_str != null) ? Base64.decode(data_str) : new byte[0]); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "response: {0}", new String(in_data)); } byte[] challenge = ss.evaluateResponse(in_data); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "challenge: {0}", ((challenge != null) ? new String( challenge) : "null")); } String challenge_str = (((challenge != null) && (challenge.length > 0)) ? Base64.encode(challenge) : null); props.put(RESULT_KEY, challenge_str); if (ss.isComplete()) { return true; } else { return false; } // end of if (ss.isComplete()) else } catch (SaslException e) { throw new AuthorizationException("Sasl exception.", e); } // end of try-catch } private boolean saslPlainAuth(final Map<String, Object> props) throws UserNotFoundException, TigaseDBException, AuthorizationException, TigaseStringprepException { String data_str = (String) props.get(DATA_KEY); String domain = (String) props.get(REALM_KEY); props.put(RESULT_KEY, null); byte[] in_data = ((data_str != null) ? Base64.decode(data_str) : new byte[0]); int auth_idx = 0; while ((in_data[auth_idx] != 0) && (auth_idx < in_data.length)) { ++auth_idx; } String authoriz = new String(in_data, 0, auth_idx); int user_idx = ++auth_idx; while ((in_data[user_idx] != 0) && (user_idx < in_data.length)) { ++user_idx; } String user_name = new String(in_data, auth_idx, user_idx - auth_idx); ++user_idx; BareJID jid = null; if (BareJID.parseJID(user_name)[0] == null) { jid = BareJID.bareJIDInstance(user_name, domain); } else { jid = BareJID.bareJIDInstance(user_name); } props.put(USER_ID_KEY, jid); String passwd = new String(in_data, user_idx, in_data.length - user_idx); return plainAuth(jid, passwd); } private boolean userLoginAuth(BareJID user, final String password) throws UserNotFoundException, TigaseDBException, AuthorizationException { if (userlogin_query == null) { return false; } ResultSet rs = null; String res_string = null; try { PreparedStatement user_login = data_repo.getPreparedStatement(user, userlogin_query); synchronized (user_login) { user_login.setString( 1, user.toString() ); user_login.setString( 2, password ); switch ( data_repo.getDatabaseType() ) { case sqlserver: user_login.executeUpdate(); rs = user_login.getGeneratedKeys(); break; default: rs = user_login.executeQuery(); break; } boolean auth_result_ok = false; if (rs.next()) { res_string = rs.getString(1); if (res_string != null) { BareJID result = BareJID.bareJIDInstance(res_string); auth_result_ok = user.equals(result); } if (auth_result_ok) { return true; } else { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Login failed, for user: ''{0}" + "''" + ", password: ''" + "{1}" + "''" + ", from DB got: " + "{2}", new Object[] { user, password, res_string }); } } } throw new UserNotFoundException("User does not exist: " + user + ", in database: " + getResourceUri()); } } catch (TigaseStringprepException ex) { throw new AuthorizationException("Stringprep failed for: " + res_string, ex); } catch (SQLException e) { throw new TigaseDBException("Problem accessing repository.", e); } finally { data_repo.release(null, rs); } // end of catch } private class SaslCallbackHandler implements CallbackHandler { private Map<String, Object> options = null; private SaslCallbackHandler(final Map<String, Object> options) { this.options = options; } // Implementation of javax.security.auth.callback.CallbackHandler /** * Describe <code>handle</code> method here. * * @param callbacks * a <code>Callback[]</code> value * @exception IOException * if an error occurs * @exception UnsupportedCallbackException * if an error occurs */ @Override public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException { BareJID jid = null; for (int i = 0; i < callbacks.length; i++) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Callback: {0}", callbacks[i].getClass().getSimpleName()); } if (callbacks[i] instanceof RealmCallback) { RealmCallback rc = (RealmCallback) callbacks[i]; String realm = (String) options.get(REALM_KEY); if (realm != null) { rc.setText(realm); } // end of if (realm == null) if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "RealmCallback: {0}", realm); } } else { if (callbacks[i] instanceof NameCallback) { NameCallback nc = (NameCallback) callbacks[i]; String user_name = nc.getName(); if (user_name == null) { user_name = nc.getDefaultName(); } // end of if (name == null) jid = BareJID.bareJIDInstanceNS(user_name, (String) options.get(REALM_KEY)); options.put(USER_ID_KEY, jid); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "NameCallback: {0}", user_name); } } else { if (callbacks[i] instanceof PasswordCallback) { PasswordCallback pc = (PasswordCallback) callbacks[i]; try { String passwd = getPassword(jid); pc.setPassword(passwd.toCharArray()); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "PasswordCallback: {0}", passwd); } } catch (Exception e) { throw new IOException("Password retrieving problem.", e); } // end of try-catch } else { if (callbacks[i] instanceof AuthorizeCallback) { AuthorizeCallback authCallback = ((AuthorizeCallback) callbacks[i]); String authenId = authCallback.getAuthenticationID(); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "AuthorizeCallback: authenId: {0}", authenId); } String authorId = authCallback.getAuthorizationID(); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "AuthorizeCallback: authorId: {0}", authorId); } if (authenId.equals(authorId)) { authCallback.setAuthorized(true); } // end of if (authenId.equals(authorId)) } else { throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); } } } } } } } } // TigaseCustomAuth // ~ Formatted in Sun Code Convention
package com.exedio.cope; import java.util.Date; import com.exedio.cope.testmodel.AttributeItem; import com.exedio.cope.testmodel.EmptyItem; public class LiteralConditionTest extends TestmodelTest { EmptyItem someItem; AttributeItem item1; AttributeItem item2; AttributeItem item3; AttributeItem item4; AttributeItem item5; Date date; private static int LONG_OFFSET = 4000; private void setDate(final AttributeItem item, final Date date) { item.setSomeDate(date); item.setSomeLongDate(offset(date, LONG_OFFSET)); } private Date offset(final Date date, final long offset) { return new Date(date.getTime()+offset); } public void setUp() throws Exception { super.setUp(); deleteOnTearDown(someItem = new EmptyItem()); deleteOnTearDown(item1 = new AttributeItem("string1", 1, 11l, 2.1, true, someItem, AttributeItem.SomeEnum.enumValue1)); deleteOnTearDown(item2 = new AttributeItem("string2", 2, 12l, 2.2, true, someItem, AttributeItem.SomeEnum.enumValue1)); deleteOnTearDown(item3 = new AttributeItem("string3", 3, 13l, 2.3, true, someItem, AttributeItem.SomeEnum.enumValue2)); deleteOnTearDown(item4 = new AttributeItem("string4", 4, 14l, 2.4, true, someItem, AttributeItem.SomeEnum.enumValue3)); deleteOnTearDown(item5 = new AttributeItem("string5", 5, 15l, 2.5, true, someItem, AttributeItem.SomeEnum.enumValue3)); date = new Date(1087365298214l); setDate(item1, offset(date, -2)); setDate(item2, offset(date, -1)); setDate(item3, date); setDate(item4, offset(date, 1)); setDate(item5, offset(date, 2)); } public void testLiteralConditions() { // test equals/hashCode assertEquals(item1.someString.less("a"), item1.someString.less("a")); assertNotEquals(item1.someString.less("a"), item1.someString.less("b")); assertNotEquals(item1.someString.less("a"), item1.someNotNullString.less("a")); assertNotEquals(item1.someString.less("a"), item1.someString.lessOrEqual("a")); // less assertContains(item1, item2, item1.TYPE.search(item1.someNotNullString.less("string3"))); assertContains(item1, item2, item1.TYPE.search(item1.someNotNullInteger.less(3))); assertContains(item1, item2, item1.TYPE.search(item1.someNotNullLong.less(13l))); assertContains(item1, item2, item1.TYPE.search(item1.someNotNullDouble.less(2.3))); assertContains(item1, item2, item1.TYPE.search(item1.someDate.less(date))); assertContains(item1, item2, item1.TYPE.search(item1.someLongDate.less(offset(date, LONG_OFFSET)))); assertContains(item1, item2, item1.TYPE.search(item1.someNotNullEnum.less(AttributeItem.SomeEnum.enumValue2))); // less or equal assertContains(item1, item2, item3, item1.TYPE.search(item1.someNotNullString.lessOrEqual("string3"))); assertContains(item1, item2, item3, item1.TYPE.search(item1.someNotNullInteger.lessOrEqual(3))); assertContains(item1, item2, item3, item1.TYPE.search(item1.someNotNullLong.lessOrEqual(13l))); assertContains(item1, item2, item3, item1.TYPE.search(item1.someNotNullDouble.lessOrEqual(2.3))); assertContains(item1, item2, item3, item1.TYPE.search(item1.someDate.lessOrEqual(date))); assertContains(item1, item2, item3, item1.TYPE.search(item1.someLongDate.lessOrEqual(offset(date, LONG_OFFSET)))); assertContains(item1, item2, item3, item1.TYPE.search(item1.someNotNullEnum.lessOrEqual(AttributeItem.SomeEnum.enumValue2))); // greater assertContains(item4, item5, item1.TYPE.search(item1.someNotNullString.greater("string3"))); assertContains(item4, item5, item1.TYPE.search(item1.someNotNullInteger.greater(3))); assertContains(item4, item5, item1.TYPE.search(item1.someNotNullLong.greater(13l))); assertContains(item4, item5, item1.TYPE.search(item1.someNotNullDouble.greater(2.3))); assertContains(item4, item5, item1.TYPE.search(item1.someDate.greater(date))); assertContains(item4, item5, item1.TYPE.search(item1.someLongDate.greater(offset(date, LONG_OFFSET)))); assertContains(item4, item5, item1.TYPE.search(item1.someNotNullEnum.greater(AttributeItem.SomeEnum.enumValue2))); // greater or equal assertContains(item3, item4, item5, item1.TYPE.search(item1.someNotNullString.greaterOrEqual("string3"))); assertContains(item3, item4, item5, item1.TYPE.search(item1.someNotNullInteger.greaterOrEqual(3))); assertContains(item3, item4, item5, item1.TYPE.search(item1.someNotNullLong.greaterOrEqual(13l))); assertContains(item3, item4, item5, item1.TYPE.search(item1.someNotNullDouble.greaterOrEqual(2.3))); assertContains(item3, item4, item5, item1.TYPE.search(item1.someDate.greaterOrEqual(date))); assertContains(item3, item4, item5, item1.TYPE.search(item1.someLongDate.greaterOrEqual(offset(date, LONG_OFFSET)))); assertContains(item3, item4, item5, item1.TYPE.search(item1.someNotNullEnum.greaterOrEqual(AttributeItem.SomeEnum.enumValue2))); } }
package tigase.server; import tigase.annotations.TODO; import tigase.net.ConnectionOpenListener; import tigase.net.ConnectionOpenThread; import tigase.net.ConnectionType; import tigase.net.SocketThread; import tigase.net.SocketType; import tigase.server.script.CommandIfc; import tigase.stats.StatisticsList; import tigase.util.DataTypes; import tigase.xmpp.JID; import tigase.xmpp.XMPPIOService; import tigase.xmpp.XMPPIOServiceListener; import java.io.IOException; import java.net.SocketException; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.script.Bindings; /** * Describe class ConnectionManager here. * * * Created: Sun Jan 22 22:52:58 2006 * * @param <IO> * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public abstract class ConnectionManager<IO extends XMPPIOService<?>> extends AbstractMessageReceiver implements XMPPIOServiceListener<IO> { private static final Logger log = Logger.getLogger(ConnectionManager.class.getName()); /** Field description */ public static final String NET_BUFFER_ST_PROP_KEY = "--net-buff-standard"; /** Field description */ public static final String NET_BUFFER_HT_PROP_KEY = "--net-buff-high-throughput"; protected static final String PORT_KEY = "port-no"; protected static final String PROP_KEY = "connections/"; protected static final String PORTS_PROP_KEY = PROP_KEY + "ports"; protected static final String PORT_TYPE_PROP_KEY = "type"; protected static final String PORT_SOCKET_PROP_KEY = "socket"; protected static final String PORT_IFC_PROP_KEY = "ifc"; protected static final String PORT_CLASS_PROP_KEY = "class"; protected static final String PORT_REMOTE_HOST_PROP_KEY = "remote-host"; protected static final String PORT_REMOTE_HOST_PROP_VAL = "localhost"; protected static final String TLS_PROP_KEY = PROP_KEY + "tls/"; protected static final String TLS_USE_PROP_KEY = TLS_PROP_KEY + "use"; protected static final boolean TLS_USE_PROP_VAL = true; protected static final String TLS_REQUIRED_PROP_KEY = TLS_PROP_KEY + "required"; protected static final boolean TLS_REQUIRED_PROP_VAL = false; protected static final String MAX_RECONNECTS_PROP_KEY = "max-reconnects"; protected static final String NET_BUFFER_PROP_KEY = "net-buffer"; protected static final int NET_BUFFER_ST_PROP_VAL = 2 * 1024; protected static final int NET_BUFFER_HT_PROP_VAL = 64 * 1024; /** Field description */ public static final String PORT_LOCAL_HOST_PROP_KEY = "local-host"; private static ConnectionOpenThread connectThread = ConnectionOpenThread.getInstance(); /** Field description */ public String[] PORT_IFC_PROP_VAL = { "*" }; private long bytesReceived = 0; private long bytesSent = 0; private int services_size = 0; private long socketOverflow = 0; private Thread watchdog = null; private long watchdogRuns = 0; private long watchdogStopped = 0; private long watchdogTests = 0; private LinkedList<Map<String, Object>> waitingTasks = new LinkedList<Map<String, Object>>(); private ConcurrentHashMap<String, IO> services = new ConcurrentHashMap<String, IO>(); private Set<ConnectionListenerImpl> pending_open = Collections .synchronizedSet(new HashSet<ConnectionListenerImpl>());; protected int net_buffer = NET_BUFFER_ST_PROP_VAL; private IOServiceStatisticsGetter ioStatsGetter = new IOServiceStatisticsGetter(); private boolean initializationCompleted = false; protected long connectionDelay = 2 * SECOND; /** * Method description * * * @param serv * * @return */ public abstract Queue<Packet> processSocketData(IO serv); /** * Method description * * * @param port_props */ public abstract void reconnectionFailed(Map<String, Object> port_props); protected abstract long getMaxInactiveTime(); protected abstract IO getXMPPIOServiceInstance(); /** * Method description * */ @Override public synchronized void everyMinute() { super.everyMinute(); doForAllServices(ioStatsGetter); } /** * Method description * * * @param params * * @return */ @Override public Map<String, Object> getDefaults(Map<String, Object> params) { log.log(Level.CONFIG, "{0} defaults: {1}", new Object[] { getName(), params.toString() }); Map<String, Object> props = super.getDefaults(params); props.put(TLS_USE_PROP_KEY, TLS_USE_PROP_VAL); int buffSize = NET_BUFFER_ST_PROP_VAL; if (isHighThroughput()) { buffSize = DataTypes.parseSizeInt((String) params.get(NET_BUFFER_HT_PROP_KEY), NET_BUFFER_HT_PROP_VAL); } else { buffSize = DataTypes.parseSizeInt((String) params.get(NET_BUFFER_ST_PROP_KEY), NET_BUFFER_ST_PROP_VAL); } props.put(NET_BUFFER_PROP_KEY, buffSize); int[] ports = null; String ports_str = (String) params.get("--" + getName() + "-ports"); if (ports_str != null) { String[] ports_stra = ports_str.split(","); ports = new int[ports_stra.length]; int k = 0; for (String p : ports_stra) { try { ports[k++] = Integer.parseInt(p); } catch (Exception e) { log.warning("Incorrect ports default settings: " + p); } } } int ports_size = 0; if (ports != null) { log.config("Port settings preset: " + Arrays.toString(ports)); for (int port : ports) { putDefPortParams(props, port, SocketType.plain); } // end of for (int i = 0; i < idx; i++) props.put(PORTS_PROP_KEY, ports); } else { int[] plains = getDefPlainPorts(); if (plains != null) { ports_size += plains.length; } // end of if (plains != null) int[] ssls = getDefSSLPorts(); if (ssls != null) { ports_size += ssls.length; } // end of if (ssls != null) if (ports_size > 0) { ports = new int[ports_size]; } // end of if (ports_size > 0) if (ports != null) { int idx = 0; if (plains != null) { idx = plains.length; for (int i = 0; i < idx; i++) { ports[i] = plains[i]; putDefPortParams(props, ports[i], SocketType.plain); } // end of for (int i = 0; i < idx; i++) } // end of if (plains != null) if (ssls != null) { for (int i = idx; i < idx + ssls.length; i++) { ports[i] = ssls[i - idx]; putDefPortParams(props, ports[i], SocketType.ssl); } // end of for (int i = 0; i < idx + ssls.length; i++) } // end of if (ssls != null) props.put(PORTS_PROP_KEY, ports); } // end of if (ports != null) } return props; } /** * Generates the component statistics. * * @param list * is a collection to put the component statistics in. */ @Override public void getStatistics(StatisticsList list) { super.getStatistics(list); list.add(getName(), "Open connections", services_size, Level.INFO); if (list.checkLevel(Level.FINEST) || services.size() < 1000) { int waitingToSendSize = 0; for (IO serv : services.values()) { waitingToSendSize += serv.waitingToSendSize(); } list.add(getName(), "Waiting to send", waitingToSendSize, Level.FINE); } list.add(getName(), "Bytes sent", bytesSent, Level.FINE); list.add(getName(), "Bytes received", bytesReceived, Level.FINE); list.add(getName(), "Socket overflow", socketOverflow, Level.FINE); list.add(getName(), "Watchdog runs", watchdogRuns, Level.FINER); list.add(getName(), "Watchdog tests", watchdogTests, Level.FINE); list.add(getName(), "Watchdog stopped", watchdogStopped, Level.FINE); } /** * This method can be overwritten in extending classes to get a different * packets distribution to different threads. For PubSub, probably better * packets distribution to different threads would be based on the sender * address rather then destination address. * * @param packet * @return */ @Override public int hashCodeForPacket(Packet packet) { if (packet.getStanzaTo() != null) { return packet.getStanzaTo().hashCode(); } if (packet.getTo() != null) { return packet.getTo().hashCode(); } return super.hashCodeForPacket(packet); } /** * Method description * * * @param binds */ @Override public void initBindings(Bindings binds) { super.initBindings(binds); binds.put(CommandIfc.SERVICES_MAP, services); } /** * Method description * */ @Override public void initializationCompleted() { super.initializationCompleted(); initializationCompleted = true; for (Map<String, Object> params : waitingTasks) { reconnectService(params, connectionDelay); } waitingTasks.clear(); } /** * Method description * * * @param serv * * @throws IOException */ @Override public void packetsReady(IO serv) throws IOException { // Under a high load data, especially lots of packets on a single // connection it may happen that one threads started processing // socketData and then another thread reads more packets which // may take over earlier data depending on a thread scheduler used. // synchronized (serv) { writePacketsToSocket(serv, processSocketData(serv)); } /** * Method description * * * @param packet */ @Override public void processPacket(Packet packet) { writePacketToSocket(packet); } /** * Method description * * * @return */ @Override public int processingInThreads() { return Runtime.getRuntime().availableProcessors() * 4; } @Override public int processingOutThreads() { return Runtime.getRuntime().availableProcessors() * 4; } /** * Method description * */ @Override public void release() { // delayedTasks.cancel(); releaseListeners(); super.release(); } /** * Method description * * * @param service */ @TODO(note = "Do something if service with the same unique ID is already started, " + "possibly kill the old one...") public void serviceStarted(final IO service) { // synchronized(services) { String id = getUniqueId(service); if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "[[{0}]] Connection started: {1}", new Object[] { getName(), service }); } IO serv = services.get(id); if (serv != null) { if (serv == service) { log.log(Level.WARNING, "{0}: That would explain a lot, adding the same service twice, ID: {1}", new Object[] { getName(), serv }); } else { // Is it at all possible to happen??? // let's log it for now.... log.log(Level.WARNING, "{0}: Attempt to add different service with the same ID: {1}", new Object[] { getName(), service }); // And stop the old service.... serv.stop(); } } services.put(id, service); ++services_size; } /** * * @param service * @return */ @Override public boolean serviceStopped(IO service) { // Hopefuly there is no exception at this point, but just in case... // This is a very fresh code after all try { ioStatsGetter.check(service); } catch (Exception e) { log.log(Level.INFO, "Nothing serious to worry about but please notify the developer.", e); } // synchronized(service) { String id = getUniqueId(service); if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "[[{0}]] Connection stopped: {1}", new Object[] { getName(), service }); } // id might be null if service is stopped in accept method due to // an exception during establishing TCP/IP connection // IO serv = (id != null ? services.get(id) : null); if (id != null) { boolean result = services.remove(id, service); if (result) { --services_size; } else { // Is it at all possible to happen??? // let's log it for now.... log.log(Level.WARNING, "[[{0}]] Attempt to stop incorrect service: {1}", new Object[] { getName(), service }); Thread.dumpStack(); } return result; } return false; } /** * Method description * * * @param name */ @Override public void setName(String name) { super.setName(name); watchdog = new Thread(new Watchdog(), "Watchdog - " + name); watchdog.setDaemon(true); watchdog.start(); } /** * Method description * * * @param props */ @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); if (props.get(NET_BUFFER_PROP_KEY) != null) { net_buffer = (Integer) props.get(NET_BUFFER_PROP_KEY); } if (props.size() == 1) { // If props.size() == 1, it means this is a single property update and // ConnectionManager does not support it yet. return; } releaseListeners(); int[] ports = (int[]) props.get(PORTS_PROP_KEY); if (ports != null) { for (int i = 0; i < ports.length; i++) { Map<String, Object> port_props = new LinkedHashMap<String, Object>(20); for (Map.Entry<String, Object> entry : props.entrySet()) { if (entry.getKey().startsWith(PROP_KEY + ports[i])) { int idx = entry.getKey().lastIndexOf('/'); String key = entry.getKey().substring(idx + 1); log.log(Level.CONFIG, "Adding port property key: {0}={1}", new Object[] { key, entry.getValue() }); port_props.put(key, entry.getValue()); } // end of if (entry.getKey().startsWith()) } // end of for () port_props.put(PORT_KEY, ports[i]); addWaitingTask(port_props); // reconnectService(port_props, startDelay); } // end of for (int i = 0; i < ports.length; i++) } // end of if (ports != null) } /** * Method description * * * @param ios * @param p * * @return */ public boolean writePacketToSocket(IO ios, Packet p) { if (ios != null) { if (log.isLoggable(Level.FINER) && !log.isLoggable(Level.FINEST)) { log.log(Level.FINER, "{0}, Processing packet: {1}, type: {2}", new Object[] { ios, p.getElemName(), p.getType() }); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] { ios, p }); } // synchronized (ios) { ios.addPacketToSend(p); if (ios.writeInProgress.tryLock()) { try { ios.processWaitingPackets(); SocketThread.addSocketService(ios); return true; } catch (Exception e) { log.log(Level.WARNING, ios + "Exception during writing packets: ", e); try { ios.stop(); } catch (Exception e1) { log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1); } // end of try-catch } finally { ios.writeInProgress.unlock(); } } } else { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Can''t find service for packet: <{0}> {1}, service id: {2}", new Object[] { p.getElemName(), p.getTo(), getServiceId(p) }); } } // end of if (ios != null) else return false; } /** * Method description * * * @param serv * @param packets */ public void writePacketsToSocket(IO serv, Queue<Packet> packets) { if (serv != null) { // synchronized (serv) { if ((packets != null) && (packets.size() > 0)) { Packet p = null; while ((p = packets.poll()) != null) { if (log.isLoggable(Level.FINER) && !log.isLoggable(Level.FINEST)) { log.log(Level.FINER, "{0}, Processing packet: {1}, type: {2}", new Object[] { serv, p.getElemName(), p.getType() }); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Writing packet: {1}", new Object[] { serv, p }); } serv.addPacketToSend(p); } // end of for () try { serv.processWaitingPackets(); SocketThread.addSocketService(serv); } catch (Exception e) { log.log(Level.WARNING, serv + "Exception during writing packets: ", e); try { serv.stop(); } catch (Exception e1) { log.log(Level.WARNING, serv + "Exception stopping XMPPIOService: ", e1); } // end of try-catch } // end of try-catch } } else { if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Can't find service for packets: [{0}] ", packets); } } // end of if (ios != null) else } protected void addWaitingTask(Map<String, Object> conn) { if (initializationCompleted) { reconnectService(conn, connectionDelay); } else { waitingTasks.add(conn); } } /** * Returns number of active network connections (IOServices). * * @return number of active network connections (IOServices). */ protected int countIOServices() { return services.size(); } /** * Perform a given action defined by ServiceChecker for all active IOService * objects (active network connections). * * @param checker * is a <code>ServiceChecker</code> instance defining an action to * perform for all IOService objects. */ protected void doForAllServices(ServiceChecker<IO> checker) { for (IO service : services.values()) { checker.check(service); } } protected int[] getDefPlainPorts() { return null; } protected int[] getDefSSLPorts() { return null; } protected Map<String, Object> getParamsForPort(int port) { return null; } protected String getServiceId(Packet packet) { return getServiceId(packet.getTo()); } protected String getServiceId(JID jid) { return jid.getResource(); } protected String getUniqueId(IO serv) { return serv.getUniqueId(); } protected IO getXMPPIOService(String serviceId) { return services.get(serviceId); } protected IO getXMPPIOService(Packet p) { return services.get(getServiceId(p)); } protected boolean isHighThroughput() { return false; } /** * * @param p * @return */ protected boolean writePacketToSocket(Packet p) { IO ios = getXMPPIOService(p); if (ios != null) { return writePacketToSocket(ios, p); } else { return false; } } protected boolean writePacketToSocket(Packet p, String serviceId) { IO ios = getXMPPIOService(serviceId); if (ios != null) { return writePacketToSocket(ios, p); } else { return false; } } protected void writeRawData(IO ios, String data) { try { ios.writeRawData(data); SocketThread.addSocketService(ios); } catch (Exception e) { log.log(Level.WARNING, ios + "Exception during writing data: " + data, e); try { ios.stop(); } catch (Exception e1) { log.log(Level.WARNING, ios + "Exception stopping XMPPIOService: ", e1); } // end of try-catch } } private void putDefPortParams(Map<String, Object> props, int port, SocketType sock) { log.log(Level.CONFIG, "Generating defaults for port: {0}", port); props.put(PROP_KEY + port + "/" + PORT_TYPE_PROP_KEY, ConnectionType.accept); props.put(PROP_KEY + port + "/" + PORT_SOCKET_PROP_KEY, sock); props.put(PROP_KEY + port + "/" + PORT_IFC_PROP_KEY, PORT_IFC_PROP_VAL); props.put(PROP_KEY + port + "/" + PORT_REMOTE_HOST_PROP_KEY, PORT_REMOTE_HOST_PROP_VAL); props.put(PROP_KEY + port + "/" + TLS_REQUIRED_PROP_KEY, TLS_REQUIRED_PROP_VAL); Map<String, Object> extra = getParamsForPort(port); if (extra != null) { for (Map.Entry<String, Object> entry : extra.entrySet()) { props.put(PROP_KEY + port + "/" + entry.getKey(), entry.getValue()); } // end of for () } // end of if (extra != null) } private void reconnectService(final Map<String, Object> port_props, long delay) { if (log.isLoggable(Level.FINER)) { String cid = "" + port_props.get("local-hostname") + "@" + port_props.get("remote-hostname"); log.log(Level.FINER, "Reconnecting service for: {0}, scheduling next try in {1}secs, cid: {2}", new Object[] { getName(), delay / 1000, cid }); } addTimerTask(new TimerTask() { @Override public void run() { String host = (String) port_props.get(PORT_REMOTE_HOST_PROP_KEY); if (host == null) { host = (String) port_props.get("remote-hostname"); } int port = (Integer) port_props.get(PORT_KEY); if (log.isLoggable(Level.FINE)) { log.log( Level.FINE, "Reconnecting service for component: {0}, to remote host: {1} on port: {2}", new Object[] { getName(), host, port }); } startService(port_props); } }, delay); } private void releaseListeners() { for (ConnectionListenerImpl cli : pending_open) { connectThread.removeConnectionOpenListener(cli); } pending_open.clear(); } private void startService(Map<String, Object> port_props) { if (port_props == null) { throw new NullPointerException("port_props cannot be null."); } ConnectionListenerImpl cli = new ConnectionListenerImpl(port_props); if (cli.getConnectionType() == ConnectionType.accept) { pending_open.add(cli); } connectThread.addConnectionOpenListener(cli); } private class ConnectionListenerImpl implements ConnectionOpenListener { private Map<String, Object> port_props = null; private ConnectionListenerImpl(Map<String, Object> port_props) { this.port_props = port_props; } /** * Method description * * * @param sc */ @Override public void accept(SocketChannel sc) { String cid = "" + port_props.get("local-hostname") + "@" + port_props.get("remote-hostname"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Accept called for service: {0}", cid); } IO serv = getXMPPIOServiceInstance(); serv.setIOServiceListener(ConnectionManager.this); serv.setSessionData(port_props); try { serv.accept(sc); if (getSocketType() == SocketType.ssl) { serv.startSSL(false); } // end of if (socket == SocketType.ssl) serviceStarted(serv); SocketThread.addSocketService(serv); } catch (SocketException e) { if (getConnectionType() == ConnectionType.connect) { // Accept side for component service is not ready yet? // Let's wait for a few secs and try again. if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Problem reconnecting the service: {0}, cid: {1}", new Object[] { serv, cid }); } boolean reconnect = false; Integer reconnects = (Integer) port_props.get(MAX_RECONNECTS_PROP_KEY); if (reconnects != null) { int recon = reconnects.intValue(); if (recon != 0) { port_props.put(MAX_RECONNECTS_PROP_KEY, (--recon)); reconnect = true; } // end of if (recon != 0) } if (reconnect) { reconnectService(port_props, connectionDelay); } else { reconnectionFailed(port_props); } } else { // Ignore } } catch (Exception e) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Can not accept connection cid: " + cid, e); } log.log(Level.WARNING, "Can not accept connection.", e); serv.stop(); } // end of try-catch } /** * Method description * * * @return */ @Override public ConnectionType getConnectionType() { String type = null; if (port_props.get(PORT_TYPE_PROP_KEY) == null) { log.warning(getName() + ": connection type is null: " + port_props.get(PORT_KEY).toString()); } else { type = port_props.get(PORT_TYPE_PROP_KEY).toString(); } return ConnectionType.valueOf(type); } /** * Method description * * * @return */ @Override public String[] getIfcs() { return (String[]) port_props.get(PORT_IFC_PROP_KEY); } /** * Method description * * * @return */ @Override public int getPort() { return (Integer) port_props.get(PORT_KEY); } /** * Method description * * * @return */ @Override public int getReceiveBufferSize() { return net_buffer; } /** * Method description * * * @return */ public SocketType getSocketType() { return SocketType.valueOf(port_props.get(PORT_SOCKET_PROP_KEY).toString()); } /** * Method description * * * @return */ @Override public int getTrafficClass() { if (isHighThroughput()) { return IPTOS_THROUGHPUT; } else { return DEF_TRAFFIC_CLASS; } } /** * Method description * * * @return */ @Override public String toString() { return port_props.toString(); } } private class IOServiceStatisticsGetter implements ServiceChecker<IO> { private StatisticsList list = new StatisticsList(Level.ALL); /** * Method description * * * @param service */ @Override public synchronized void check(IO service) { service.getStatistics(list, true); bytesReceived += list.getValue("socketio", "Bytes received", -1l); bytesSent += list.getValue("socketio", "Bytes sent", -1l); socketOverflow += list.getValue("socketio", "Buffers overflow", -1l); } } /** * Looks in all established connections and checks whether any of them is * dead.... * */ private class Watchdog implements Runnable { /** * Method description * */ @Override public void run() { while (true) { try { // Sleep... Thread.sleep(10 * MINUTE); ++watchdogRuns; // This variable used to provide statistics gets off on a busy // services as it is handled in methods called concurrently by // many threads. While accuracy of this variable is not critical // for the server functions, statistics should be as accurate as // possible to provide valuable metrics data. // So in the watchdog thread we re-synchronize this number services_size = services.size(); // Walk through all connections and check whether they are // really alive...., try to send space for each service which // is inactive for hour or more and close the service // on Exception doForAllServices(new ServiceChecker<IO>() { @Override public void check(final XMPPIOService service) { try { if (null != service) { long curr_time = System.currentTimeMillis(); long lastTransfer = service.getLastTransferTime(); if (curr_time - lastTransfer >= getMaxInactiveTime()) { // Stop the service is max keep-alive time is exceeded // for non-active connections. if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, "{0}: Max inactive time exceeded, stopping: {1}", new Object[] { getName(), service }); } ++watchdogStopped; service.stop(); } else { if (curr_time - lastTransfer >= (29 * MINUTE)) { // At least once an hour check if the connection is // still alive. service.writeRawData(" "); ++watchdogTests; } } } } catch (Exception e) { // Close the service.... try { if (service != null) { log.info(getName() + "Found dead connection, stopping: " + service); ++watchdogStopped; service.forceStop(); } } catch (Exception ignore) { // Do nothing here as we expect Exception to be thrown here... } } } }); } catch (InterruptedException e) { /* Do nothing here */ } } } } } // ConnectionManager
package tigase.server; import java.io.IOException; import java.net.SocketException; import java.nio.channels.SocketChannel; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListMap; import java.util.logging.Level; import java.util.logging.Logger; import tigase.annotations.TODO; import tigase.io.TLSUtil; import tigase.net.ConnectionOpenListener; import tigase.net.ConnectionOpenThread; import tigase.net.ConnectionType; import tigase.net.IOService; import tigase.net.SocketReadThread; import tigase.net.SocketType; import tigase.stats.StatRecord; import tigase.util.JIDUtils; import tigase.xmpp.XMPPIOService; import tigase.xmpp.XMPPIOServiceListener; import static tigase.io.SSLContextContainerIfc.*; /** * Describe class ConnectionManager here. * * * Created: Sun Jan 22 22:52:58 2006 * * @param <IO> * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public abstract class ConnectionManager<IO extends XMPPIOService> extends AbstractMessageReceiver implements XMPPIOServiceListener { private static final Logger log = Logger.getLogger("tigase.server.ConnectionManager"); protected static final String PORT_KEY = "port-no"; protected static final String PROP_KEY = "connections/"; protected static final String PORTS_PROP_KEY = PROP_KEY + "ports"; protected static final String PORT_TYPE_PROP_KEY = "type"; protected static final String PORT_SOCKET_PROP_KEY = "socket"; protected static final String PORT_IFC_PROP_KEY = "ifc"; private static final String[] PORT_IFC_PROP_VAL = {"*"}; protected static final String PORT_CLASS_PROP_KEY = "class"; protected static final String PORT_REMOTE_HOST_PROP_KEY = "remote-host"; protected static final String PORT_REMOTE_HOST_PROP_VAL = "localhost"; protected static final String TLS_PROP_KEY = PROP_KEY + "tls/"; protected static final String TLS_USE_PROP_KEY = TLS_PROP_KEY + "use"; protected static final boolean TLS_USE_PROP_VAL = true; protected static final String TLS_REQUIRED_PROP_KEY = TLS_PROP_KEY + "required"; protected static final boolean TLS_REQUIRED_PROP_VAL = false; protected static final String TLS_KEYS_STORE_PROP_KEY = TLS_PROP_KEY + JKS_KEYSTORE_FILE_KEY; protected static final String TLS_KEYS_STORE_PROP_VAL = JKS_KEYSTORE_FILE_VAL; protected static final String TLS_DEF_CERT_PROP_KEY = TLS_PROP_KEY + DEFAULT_DOMAIN_CERT_KEY; protected static final String TLS_DEF_CERT_PROP_VAL = DEFAULT_DOMAIN_CERT_VAL; protected static final String TLS_KEYS_STORE_PASSWD_PROP_KEY = TLS_PROP_KEY + JKS_KEYSTORE_PWD_KEY; protected static final String TLS_KEYS_STORE_PASSWD_PROP_VAL = JKS_KEYSTORE_PWD_VAL; protected static final String TLS_TRUSTS_STORE_PASSWD_PROP_KEY = TLS_PROP_KEY + TRUSTSTORE_PWD_KEY; protected static final String TLS_TRUSTS_STORE_PASSWD_PROP_VAL = TRUSTSTORE_PWD_VAL; protected static final String TLS_TRUSTS_STORE_PROP_KEY = TLS_PROP_KEY + TRUSTSTORE_FILE_KEY; protected static final String TLS_TRUSTS_STORE_PROP_VAL = TRUSTSTORE_FILE_VAL; protected static final String TLS_CONTAINER_CLASS_PROP_KEY = TLS_PROP_KEY + SSL_CONTAINER_CLASS_KEY; protected static final String TLS_CONTAINER_CLASS_PROP_VAL = SSL_CONTAINER_CLASS_VAL; protected static final String TLS_SERVER_CERTS_DIR_PROP_KEY = TLS_PROP_KEY + SERVER_CERTS_DIR_KEY; protected static final String TLS_SERVER_CERTS_DIR_PROP_VAL = SERVER_CERTS_DIR_VAL; protected static final String TLS_TRUSTED_CERTS_DIR_PROP_KEY = TLS_PROP_KEY + TRUSTED_CERTS_DIR_KEY; protected static final String TLS_TRUSTED_CERTS_DIR_PROP_VAL = TRUSTED_CERTS_DIR_VAL; protected static final String TLS_ALLOW_SELF_SIGNED_CERTS_PROP_KEY = TLS_PROP_KEY + ALLOW_SELF_SIGNED_CERTS_KEY; protected static final String TLS_ALLOW_SELF_SIGNED_CERTS_PROP_VAL = ALLOW_SELF_SIGNED_CERTS_VAL; protected static final String TLS_ALLOW_INVALID_CERTS_PROP_KEY = TLS_PROP_KEY + ALLOW_INVALID_CERTS_KEY; protected static final String TLS_ALLOW_INVALID_CERTS_PROP_VAL = ALLOW_INVALID_CERTS_VAL; protected static final String MAX_RECONNECTS_PROP_KEY = "max-reconnects"; private static ConnectionOpenThread connectThread = ConnectionOpenThread.getInstance(); private static SocketReadThread readThread = SocketReadThread.getInstance(); private Timer delayedTasks = null; private Thread watchdog = null; private long watchdogRuns = 0; private long watchdogTests = 0; private long watchdogStopped = 0; private LinkedList<Map<String, Object>> waitingTasks = new LinkedList<Map<String, Object>>(); private Map<String, IO> services = new ConcurrentSkipListMap<String, IO>(); private Set<ConnectionListenerImpl> pending_open = Collections.synchronizedSet(new HashSet<ConnectionListenerImpl>());; protected long connectionDelay = 2 * SECOND; private boolean initializationCompleted = false; // protected long startDelay = 5 * SECOND; @Override public void setName(String name) { super.setName(name); watchdog = new Thread(new Watchdog(), "Watchdog - " + name); watchdog.setDaemon(true); watchdog.start(); } @Override public void initializationCompleted() { initializationCompleted = true; for (Map<String, Object> params : waitingTasks) { reconnectService(params, connectionDelay); } waitingTasks.clear(); } protected void addWaitingTask(Map<String, Object> conn) { if (initializationCompleted) { reconnectService(conn, connectionDelay); } else { waitingTasks.add(conn); } } @Override public Map<String, Object> getDefaults(Map<String, Object> params) { Map<String, Object> props = super.getDefaults(params); props.put(TLS_USE_PROP_KEY, TLS_USE_PROP_VAL); props.put(TLS_DEF_CERT_PROP_KEY, TLS_DEF_CERT_PROP_VAL); props.put(TLS_KEYS_STORE_PROP_KEY, TLS_KEYS_STORE_PROP_VAL); props.put(TLS_KEYS_STORE_PASSWD_PROP_KEY, TLS_KEYS_STORE_PASSWD_PROP_VAL); props.put(TLS_TRUSTS_STORE_PROP_KEY, TLS_TRUSTS_STORE_PROP_VAL); props.put(TLS_TRUSTS_STORE_PASSWD_PROP_KEY, TLS_TRUSTS_STORE_PASSWD_PROP_VAL); props.put(TLS_SERVER_CERTS_DIR_PROP_KEY, TLS_SERVER_CERTS_DIR_PROP_VAL); props.put(TLS_TRUSTED_CERTS_DIR_PROP_KEY, TLS_TRUSTED_CERTS_DIR_PROP_VAL); props.put(TLS_ALLOW_SELF_SIGNED_CERTS_PROP_KEY, TLS_ALLOW_SELF_SIGNED_CERTS_PROP_VAL); props.put(TLS_ALLOW_INVALID_CERTS_PROP_KEY, TLS_ALLOW_INVALID_CERTS_PROP_VAL); if (params.get("--" + SSL_CONTAINER_CLASS_KEY) != null) { props.put(TLS_CONTAINER_CLASS_PROP_KEY, (String)params.get("--" + SSL_CONTAINER_CLASS_KEY)); } else { props.put(TLS_CONTAINER_CLASS_PROP_KEY, TLS_CONTAINER_CLASS_PROP_VAL); } int ports_size = 0; int[] ports = (int[])params.get(getName() + "/" + PORTS_PROP_KEY); if (ports != null) { for (int port: ports) { putDefPortParams(props, port, SocketType.plain); } // end of for (int i = 0; i < idx; i++) props.put(PORTS_PROP_KEY, ports); } else { int[] plains = getDefPlainPorts(); if (plains != null) { ports_size += plains.length; } // end of if (plains != null) int[] ssls = getDefSSLPorts(); if (ssls != null) { ports_size += ssls.length; } // end of if (ssls != null) if (ports_size > 0) { ports = new int[ports_size]; } // end of if (ports_size > 0) if (ports != null) { int idx = 0; if (plains != null) { idx = plains.length; for (int i = 0; i < idx; i++) { ports[i] = plains[i]; putDefPortParams(props, ports[i], SocketType.plain); } // end of for (int i = 0; i < idx; i++) } // end of if (plains != null) if (ssls != null) { for (int i = idx; i < idx + ssls.length; i++) { ports[i] = ssls[i-idx]; putDefPortParams(props, ports[i], SocketType.ssl); } // end of for (int i = 0; i < idx + ssls.length; i++) } // end of if (ssls != null) props.put(PORTS_PROP_KEY, ports); } // end of if (ports != null) } return props; } private void putDefPortParams(Map<String, Object> props, int port, SocketType sock) { props.put(PROP_KEY + port + "/" + PORT_TYPE_PROP_KEY, ConnectionType.accept); props.put(PROP_KEY + port + "/" + PORT_SOCKET_PROP_KEY, sock); props.put(PROP_KEY + port + "/" + PORT_IFC_PROP_KEY, PORT_IFC_PROP_VAL); props.put(PROP_KEY + port + "/" + PORT_REMOTE_HOST_PROP_KEY, PORT_REMOTE_HOST_PROP_VAL); props.put(PROP_KEY + port + "/" + TLS_REQUIRED_PROP_KEY, TLS_REQUIRED_PROP_VAL); Map<String, Object> extra = getParamsForPort(port); if (extra != null) { for (Map.Entry<String, Object> entry : extra.entrySet()) { props.put(PROP_KEY + port + "/" + entry.getKey(), entry.getValue()); } // end of for () } // end of if (extra != null) } private void releaseListeners() { for (ConnectionListenerImpl cli: pending_open) { connectThread.removeConnectionOpenListener(cli); } pending_open.clear(); } public void release() { delayedTasks.cancel(); releaseListeners(); super.release(); } public void start() { super.start(); delayedTasks = new Timer(getName() + " - delayed connections", true); } @Override public void setProperties(Map<String, Object> props) { super.setProperties(props); releaseListeners(); int[] ports = (int[])props.get(PORTS_PROP_KEY); if (ports != null) { for (int i = 0; i < ports.length; i++) { Map<String, Object> port_props = new LinkedHashMap<String, Object>(); for (Map.Entry<String, Object> entry : props.entrySet()) { if (entry.getKey().startsWith(PROP_KEY + ports[i])) { int idx = entry.getKey().lastIndexOf('/'); String key = entry.getKey().substring(idx + 1); log.config("Adding port property key: " + key + "=" + entry.getValue()); port_props.put(key, entry.getValue()); } // end of if (entry.getKey().startsWith()) } // end of for () port_props.put(PORT_KEY, ports[i]); addWaitingTask(port_props); //reconnectService(port_props, startDelay); } // end of for (int i = 0; i < ports.length; i++) } // end of if (ports != null) if ((Boolean)props.get(TLS_USE_PROP_KEY)) { Map<String, String> tls_params = new LinkedHashMap<String, String>(); tls_params.put(SSL_CONTAINER_CLASS_KEY, (String)props.get(TLS_CONTAINER_CLASS_PROP_KEY)); tls_params.put(DEFAULT_DOMAIN_CERT_KEY, (String)props.get(TLS_DEF_CERT_PROP_KEY)); tls_params.put(JKS_KEYSTORE_FILE_KEY, (String)props.get(TLS_KEYS_STORE_PROP_KEY)); tls_params.put(JKS_KEYSTORE_PWD_KEY, (String)props.get(TLS_KEYS_STORE_PASSWD_PROP_KEY)); tls_params.put(TRUSTSTORE_FILE_KEY, (String)props.get(TLS_TRUSTS_STORE_PROP_KEY)); tls_params.put(TRUSTSTORE_PWD_KEY, (String)props.get(TLS_TRUSTS_STORE_PASSWD_PROP_KEY)); tls_params.put(SERVER_CERTS_DIR_KEY, (String)props.get(TLS_SERVER_CERTS_DIR_PROP_KEY)); tls_params.put(TRUSTED_CERTS_DIR_KEY, (String)props.get(TLS_TRUSTED_CERTS_DIR_PROP_KEY)); tls_params.put(ALLOW_SELF_SIGNED_CERTS_KEY, (String)props.get(TLS_ALLOW_SELF_SIGNED_CERTS_PROP_KEY)); tls_params.put(ALLOW_INVALID_CERTS_KEY, (String)props.get(TLS_ALLOW_INVALID_CERTS_PROP_KEY)); TLSUtil.configureSSLContext(getName(), tls_params); } // end of if (use.equalsIgnoreCase()) } private void startService(Map<String, Object> port_props) { ConnectionListenerImpl cli = new ConnectionListenerImpl(port_props); if (cli.getConnectionType() == ConnectionType.accept) { pending_open.add(cli); } connectThread.addConnectionOpenListener(cli); } private void reconnectService(final Map<String, Object> port_props, long delay) { if (log.isLoggable(Level.FINER)) { log.finer("Reconnecting service for: " + getName() + ", scheduling next try in " + (delay / 1000) + "secs"); } delayedTasks.schedule(new TimerTask() { public void run() { String host = (String)port_props.get(PORT_REMOTE_HOST_PROP_KEY); if (host == null) { host = (String)port_props.get("remote-hostname"); } int port = (Integer)port_props.get(PORT_KEY); if (log.isLoggable(Level.FINE)) { log.fine("Reconnecting service for component: " + getName() + ", to remote host: " + host + " on port: " + port); } startService(port_props); } }, delay); } protected int[] getDefPlainPorts() { return null; } protected int[] getDefSSLPorts() { return null; } protected Map<String, Object> getParamsForPort(int port) { return null; } // Implementation of tigase.net.PacketListener /** * Describe <code>packetsReady</code> method here. * * @param s an <code>IOService</code> value * @throws IOException */ @SuppressWarnings({"unchecked"}) public void packetsReady(IOService s) throws IOException { if (log.isLoggable(Level.FINEST)) { log.finest("packetsReady called"); } IO serv = (IO)s; packetsReady(serv); } public void packetsReady(IO serv) throws IOException { writePacketsToSocket(serv, processSocketData(serv)); } public void writePacketsToSocket(IO serv, Queue<Packet> packets) { if (serv != null) { //synchronized (serv) { if (packets != null && packets.size() > 0) { Packet p = null; while ((p = packets.poll()) != null) { serv.addPacketToSend(p); } // end of for () try { serv.processWaitingPackets(); readThread.addSocketService(serv); } catch (Exception e) { log.log(Level.WARNING, "Exception during writing packets: ", e); try { serv.stop(); } catch (Exception e1) { log.log(Level.WARNING, "Exception stopping XMPPIOService: ", e1); } // end of try-catch } // end of try-catch } } else { if (log.isLoggable(Level.FINE)) { log.fine("Can't find service for packets: <" + packets.toString() + "> "); } } // end of if (ios != null) else } public boolean writePacketToSocket(IO ios, Packet p) { if (ios != null) { //synchronized (ios) { ios.addPacketToSend(p); try { ios.processWaitingPackets(); readThread.addSocketService(ios); return true; } catch (Exception e) { log.log(Level.WARNING, "Exception during writing packets: ", e); try { ios.stop(); } catch (Exception e1) { log.log(Level.WARNING, "Exception stopping XMPPIOService: ", e1); } // end of try-catch } // end of try-catch } else { if (log.isLoggable(Level.FINE)) { log.fine("Can't find service for packet: <" + p.getElemName() + "> " + p.getTo() + ", service id: " + getServiceId(p)); } } // end of if (ios != null) else return false; } protected void writeRawData(IO ios, String data) { //synchronized (ios) { try { ios.writeRawData(data); readThread.addSocketService(ios); } catch (Exception e) { log.log(Level.WARNING, "Exception during writing data: " + data, e); try { ios.stop(); } catch (Exception e1) { log.log(Level.WARNING, "Exception stopping XMPPIOService: ", e1); } // end of try-catch } } /** * * @param p * @return */ protected boolean writePacketToSocket(Packet p) { if (log.isLoggable(Level.FINER)) { log.finer("Processing packet: " + p.getElemName() + ", type: " + p.getType()); } if (log.isLoggable(Level.FINEST)) { log.finest("Writing packet to: " + p.getTo()); } IO ios = getXMPPIOService(p); if (ios != null) { return writePacketToSocket(ios, p); } else { return false; } } protected boolean writePacketToSocket(Packet p, String serviceId) { if (log.isLoggable(Level.FINER)) { log.finer("Processing packet: " + p.getElemName() + ", type: " + p.getType()); } if (log.isLoggable(Level.FINEST)) { log.finest("Writing packet to: " + p.getTo()); } IO ios = getXMPPIOService(serviceId); if (ios != null) { return writePacketToSocket(ios, p); } else { return false; } } protected IO getXMPPIOService(String serviceId) { return services.get(serviceId); } protected IO getXMPPIOService(Packet p) { return services.get(getServiceId(p)); } @Override public void processPacket(Packet packet) { writePacketToSocket(packet); } public abstract Queue<Packet> processSocketData(IO serv); @SuppressWarnings({"unchecked"}) @Override public void serviceStopped(IOService s) { IO ios = (IO)s; serviceStopped(ios); } public void serviceStopped(IO service) { //synchronized(service) { String id = getUniqueId(service); if (log.isLoggable(Level.FINER)) { log.finer("[[" + getName() + "]] Connection stopped: " + id); } // id might be null if service is stopped in accept method due to // an exception during establishing TCP/IP connection IO serv = (id != null ? services.get(id) : null); if (serv == service) { services.remove(id); } else { if (id != null) { // Is it at all possible to happen??? // let's log it for now.... log.warning("[[" + getName() + "]] Attempt to stop incorrect service: " + id); Thread.dumpStack(); } } } @TODO(note="Do something if service with the same unique ID is already started, possibly kill the old one...") public void serviceStarted(final IO service) { //synchronized(services) { String id = getUniqueId(service); if (log.isLoggable(Level.FINER)) { log.finer("[[" + getName() + "]] Connection started: " + id); } IO serv = services.get(id); if (serv != null) { if (serv == service) { log.warning(getName() + ": That would explain a lot, adding the same service twice, ID: " + id); } else { // Is it at all possible to happen??? // let's log it for now.... log.warning(getName() + ": Attempt to add different service with the same ID: " + id); // And stop the old service.... serv.stop(); } } services.put(id, service); } protected String getUniqueId(IO serv) { return serv.getUniqueId(); } protected String getServiceId(Packet packet) { return getServiceId(packet.getTo()); } protected String getServiceId(String jid) { return JIDUtils.getNodeResource(jid); } @SuppressWarnings({"unchecked"}) @Override public void streamClosed(XMPPIOService s) { IO serv = (IO)s; xmppStreamClosed(serv); } public abstract void xmppStreamClosed(IO serv); @SuppressWarnings({"unchecked"}) @Override public String streamOpened(XMPPIOService s, Map<String, String> attribs) { IO serv = (IO)s; return xmppStreamOpened(serv, attribs); } public abstract String xmppStreamOpened(IO s, Map<String, String> attribs); protected int countIOServices() { return services.size(); } @Override public List<StatRecord> getStatistics() { List<StatRecord> stats = super.getStatistics(); stats.add(new StatRecord(getName(), "Open connections", "int", services.size(), Level.FINE)); stats.add(new StatRecord(getName(), "Watchdog runs", "long", watchdogRuns, Level.FINE)); stats.add(new StatRecord(getName(), "Watchdog tests", "long", watchdogTests, Level.FINE)); stats.add(new StatRecord(getName(), "Watchdog stopped", "long", watchdogStopped, Level.FINE)); // StringBuilder sb = new StringBuilder("All connected: "); // for (IOService serv: services.values()) { // sb.append("\nService ID: " + getUniqueId(serv) // + ", local-hostname: " + serv.getSessionData().get("local-hostname") // + ", remote-hostname: " + serv.getSessionData().get("remote-hostname") // + ", is-connected: " + serv.isConnected() // + ", connection-type: " + serv.connectionType()); // log.finest(sb.toString()); return stats; } protected abstract IO getXMPPIOServiceInstance(); private class ConnectionListenerImpl implements ConnectionOpenListener { private Map<String, Object> port_props = null; private ConnectionListenerImpl(Map<String, Object> port_props) { this.port_props = port_props; } @Override public int getPort() { return (Integer)port_props.get(PORT_KEY); } @Override public String[] getIfcs() { return (String[])port_props.get(PORT_IFC_PROP_KEY); } @Override public ConnectionType getConnectionType() { String type = null; if (port_props.get(PORT_TYPE_PROP_KEY) == null) { log.warning(getName() + ": connection type is null: " + port_props.get(PORT_KEY).toString()); } else { type = port_props.get(PORT_TYPE_PROP_KEY).toString(); } return ConnectionType.valueOf(type); } public SocketType getSocketType() { return SocketType.valueOf(port_props.get(PORT_SOCKET_PROP_KEY).toString()); } @Override public void accept(SocketChannel sc) { IO serv = getXMPPIOServiceInstance(); serv.setSSLId(getName()); serv.setIOServiceListener(ConnectionManager.this); serv.setSessionData(port_props); try { serv.accept(sc); if (getSocketType() == SocketType.ssl) { serv.startSSL(false); } // end of if (socket == SocketType.ssl) serviceStarted(serv); readThread.addSocketService(serv); } catch (SocketException e) { // Accept side for component service is not ready yet? // Let's wait for a few secs and try again. log.log(Level.FINEST, "Problem reconnecting the service: ", e); Integer reconnects = (Integer)port_props.get(MAX_RECONNECTS_PROP_KEY); if (reconnects != null) { int recon = reconnects.intValue(); if (recon != 0) { port_props.put(MAX_RECONNECTS_PROP_KEY, (--recon)); reconnectService(port_props, connectionDelay); } // end of if (recon != 0) } else { //System.out.println(port_props.toString()); //e.printStackTrace(); //serv.stop(); } } catch (Exception e) { log.log(Level.WARNING, "Can not accept connection.", e); serv.stop(); } // end of try-catch } } protected void doForAllServices(ServiceChecker checker) { for (IO service: services.values()) { checker.check(service, getUniqueId(service)); } } protected abstract long getMaxInactiveTime(); /** * Looks in all established connections and checks whether any of them * is dead.... * */ private class Watchdog implements Runnable { @Override public void run() { while (true) { try { // Sleep for 1 minute Thread.sleep(10*MINUTE); ++watchdogRuns; // Walk through all connections and check whether they are // really alive...., try to send space for each service which // is inactive for hour or more and close the service // on Exception doForAllServices(new ServiceChecker() { @Override public void check(final XMPPIOService service, final String serviceId) { // for (IO service: services.values()) { // service = (XMPPIOService)serv; try { if (null != service) { long curr_time = System.currentTimeMillis(); long lastTransfer = service.getLastTransferTime(); if (curr_time - lastTransfer >= getMaxInactiveTime()) { // Stop the service is max keep-alive time is acceeded // for non-active connections. if (log.isLoggable(Level.INFO)) { log.info(getName() + ": Max inactive time exceeded, stopping: " + serviceId); } ++watchdogStopped; service.stop(); } else if (curr_time - lastTransfer >= (29*MINUTE)) { // At least once an hour check if the connection is // still alive. service.writeRawData(" "); ++watchdogTests; } } } catch (Exception e) { // Close the service.... try { if (service != null) { log.info(getName() + "Found dead connection, stopping: " + serviceId); ++watchdogStopped; service.stop(); } } catch (Exception ignore) { // Do nothing here as we expect Exception to be thrown here... } } } }); } catch (InterruptedException e) { /* Do nothing here */ } } } } } // ConnectionManager
package tigase.xmpp.impl; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Queue; import java.util.Map; import java.util.logging.Logger; import tigase.server.Packet; import tigase.util.JIDUtils; import tigase.xml.Element; import tigase.xmpp.Authorization; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.StanzaType; import tigase.xmpp.XMPPProcessor; import tigase.xmpp.XMPPProcessorIfc; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.XMPPException; import tigase.db.NonAuthUserRepository; import static tigase.xmpp.impl.Roster.SubscriptionType; /** * Class <code>JabberIqRoster</code> implements part of <em>RFC-3921</em> - * <em>XMPP Instant Messaging</em> specification describing roster management. * 7. Roster Management * * * Created: Tue Feb 21 17:42:53 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class JabberIqRoster extends XMPPProcessor implements XMPPProcessorIfc { /** * Private logger for class instancess. */ private static Logger log = Logger.getLogger("tigase.xmpp.impl.JabberIqRoster"); private static final String XMLNS = "jabber:iq:roster"; private static final String ID = XMLNS; private static final String[] ELEMENTS = {"query"}; private static final String[] XMLNSS = {XMLNS}; private static final Element[] DISCO_FEATURES = { new Element("feature", new String[] {"var"}, new String[] {XMLNS}) }; public Element[] supDiscoFeatures(final XMPPResourceConnection session) { return Arrays.copyOf(DISCO_FEATURES, DISCO_FEATURES.length); } public String id() { return ID; } public String[] supElements() { return Arrays.copyOf(ELEMENTS, ELEMENTS.length); } public String[] supNamespaces() { return Arrays.copyOf(XMLNSS, XMLNSS.length); } private void processSetRequest(final Packet packet, final XMPPResourceConnection session, final Queue<Packet> results) throws NotAuthorizedException { Element request = packet.getElement(); String buddy = JIDUtils.getNodeID(request.getAttribute("/iq/query/item", "jid")); Element item = request.findChild("/iq/query/item"); String subscription = item.getAttribute("subscription"); if (subscription != null && subscription.equals("remove")) { SubscriptionType sub = Roster.getBuddySubscription(session, buddy); if (sub != null && sub != SubscriptionType.none) { Element it = new Element("item"); it.setAttribute("jid", buddy); it.setAttribute("subscription", "remove"); Roster.updateBuddyChange(session, results, it); Element pres = new Element("presence"); pres.setAttribute("to", buddy); pres.setAttribute("from", session.getUserId()); pres.setAttribute("type", "unsubscribe"); results.offer(new Packet(pres)); pres = new Element("presence"); pres.setAttribute("to", buddy); pres.setAttribute("from", session.getUserId()); pres.setAttribute("type", "unsubscribed"); results.offer(new Packet(pres)); pres = new Element("presence"); pres.setAttribute("to", buddy); pres.setAttribute("from", session.getJID()); pres.setAttribute("type", "unavailable"); results.offer(new Packet(pres)); } // end of if (sub != null && sub != SubscriptionType.none) Roster.removeBuddy(session, buddy); results.offer(packet.okResult((String)null, 0)); } else { String name = request.getAttribute("/iq/query/item", "name"); if (name == null) { name = buddy; } // end of if (name == null) Roster.setBuddyName(session, buddy, name); if (Roster.getBuddySubscription(session, buddy) == null) { Roster.setBuddySubscription(session, SubscriptionType.none, buddy); } // end of if (getBuddySubscription(session, buddy) == null) List<Element> groups = item.getChildren(); if (groups != null && groups.size() > 0) { String[] gr = new String[groups.size()]; int cnt = 0; for (Element group : groups) { gr[cnt++] = (group.getCData() == null ? "" : group.getCData()); } // end of for (ElementData group : groups) session.setDataList(Roster.groupNode(buddy), Roster.GROUPS, gr); } else { session.removeData(Roster.groupNode(buddy), Roster.GROUPS); } // end of else results.offer(packet.okResult((String)null, 0)); Roster.updateBuddyChange(session, results, Roster.getBuddyItem(session, buddy)); } // end of else } private void processGetRequest(final Packet packet, final XMPPResourceConnection session, final Queue<Packet> results, final Map<String, Object> settings) throws NotAuthorizedException { Element query = new Element("query"); String[] buddies = Roster.getBuddies(session); if (buddies != null) { query.setXMLNS("jabber:iq:roster"); for (String buddy : buddies) { query.addChild(Roster.getBuddyItem(session, buddy)); } } List<Element> items = DynamicRoster.getRosterItems(session, settings); if (items != null) { query.addChildren(items); } if (query.getChildren() != null && query.getChildren().size() > 0) { results.offer(packet.okResult(query, 0)); } else { results.offer(packet.okResult((String)null, 1)); } // end of if (buddies != null) else } public void process(final Packet packet, final XMPPResourceConnection session, final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String, Object> settings) throws XMPPException { if (session == null) { return; } // end of if (session == null) try { if (packet.getElemFrom() != null && !session.getUserId().equals(JIDUtils.getNodeID(packet.getElemFrom()))) { // RFC says: ignore such request log.warning( "Roster request 'from' attribute doesn't match session userid: " + session.getUserId() + ", request: " + packet.getStringData()); return; } // end of if (packet.getElemFrom() != null // && !session.getUserId().equals(JIDUtils.getNodeID(packet.getElemFrom()))) StanzaType type = packet.getType(); switch (type) { case get: processGetRequest(packet, session, results, settings); break; case set: processSetRequest(packet, session, results); break; case result: // Ignore break; default: results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Request type is incorrect", false)); break; } // end of switch (type) } catch (NotAuthorizedException e) { log.warning( "Received roster request but user session is not authorized yet: " + packet.getStringData()); results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You must authorize session first.", true)); } // end of try-catch } } // JabberIqRoster
package ua.pp.msk.maven; import edu.emory.mathcs.backport.java.util.Arrays; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.logging.Log; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; /** * * @author Maksym Shkolnyi aka maskimko */ public class MavenHttpClient { private String url; private String userAgent = "Maven Dependency pushing plugin"; private List<NameValuePair> urlParams = new ArrayList<NameValuePair>(); private Log log; private String repository; private String username; private String password; public MavenHttpClient(String url) { this.url = url; } public String getUrl() { return url; } public void setUrl(String url) { if (url.contains("/nexus/service/local/artifact/maven/content")){ this.url = url; } else { this.url = url.concat("/nexus/service/local/artifact/maven/content"); } } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public void addUrlParameter(String key, String value) { urlParams.add(new BasicNameValuePair(key, value)); } public void addUrlParameters(Map<String, String> params) { for (Map.Entry<String, String> me : params.entrySet()) { addUrlParameter(me.getKey(), me.getValue()); } } public Log getLog() { return log; } public void setLog(Log log) { this.log = log; } public String getRepository() { return repository; } public void setRepository(String repository) { this.repository = repository; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private int execute(File file) { CloseableHttpClient client = HttpClientBuilder.create().build(); int status = -1; try { getLog().debug("Connecting to URL: " + url); HttpPost post = new HttpPost(url); post.setHeader("User-Agent", userAgent); if (username != null && username.length() != 0 && password != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); post.addHeader(new BasicScheme().authenticate(creds, post, null)); } if (file == null) { if (!urlParams.isEmpty()) { post.setEntity(new UrlEncodedFormEntity(urlParams)); } } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (!urlParams.isEmpty()) { for (NameValuePair nvp : urlParams) { builder.addPart(nvp.getName(), new StringBody(nvp.getValue(), ContentType.MULTIPART_FORM_DATA)); } } FileBody fb = new FileBody(file); //Not used because of form submission //builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()); builder.addPart("file", fb); HttpEntity sendEntity = builder.build(); post.setEntity(sendEntity); } CloseableHttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); status = statusLine.getStatusCode(); getLog().info("Response status code: " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); //Perhaps I need to parse html //String html = EntityUtils.toString(entity); } catch (AuthenticationException ex) { if (log != null) { getLog().error(ex.getMessage()); } } catch (UnsupportedEncodingException ex) { if (log != null) { getLog().error(ex.getMessage()); } } catch (IOException ex) { if (log != null) { getLog().error(ex.getMessage()); } } finally { try { client.close(); } catch (IOException ex) { if (log != null) { getLog().error("Cannot close http client: " + ex.getMessage()); } } } return status; } private int execute() { return execute(null); } public void promote(Artifact artifact) { File af = artifact.getFile(); String pathOf = artifact.getRepository().pathOf(artifact); if (af == null){ String pathOfArtifact = artifact.getRepository().pathOf(artifact); getLog().debug("Path of artifact is " + pathOfArtifact); af = Paths.get(pathOfArtifact).toFile(); if (af == null) { getLog().error("Artifact " + artifact.getArtifactId() + " has no file"); } return; } String groupId = artifact.getGroupId(); String artifactId = artifact.getArtifactId(); String version = artifact.getVersion(); if (repository == null || repository.length() == 0) { getLog().error("Repository cannot be null value"); //TODO throw exception here return; } else { addUrlParameter("r", repository); } addUrlParameter("hasPom", "false"); String fileName = af.getName(); getLog().debug("Processing artifact file " + fileName); String[] splitName = fileName.toLowerCase().split("\\."); getLog().debug("Split name: " + Arrays.toString(splitName)); String extension = splitName[splitName.length - 1].trim(); if (!extension.equals("jar") && !extension.equals("war") && !extension.equals("ear")) { getLog().error(extension + " is not supported. Currently only jar, war, ear file extensions are supported"); //TODO throw exception here return; } addUrlParameter("e", extension); addUrlParameter("g", groupId); addUrlParameter("a", artifactId); addUrlParameter("v", version); //Packaging should be addUrlParameter("p", extension); int ec = execute(af); if (ec >= 200 && ec < 300) { if (log != null) { getLog().info("Artifact has been promoted successfully"); } } else if (log != null) { getLog().error("Artifact promotion failed"); } } }
package xyz.rc24.bot.mangers; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; public class LogManager { /** * Redis for configuration use. */ private JedisPool pool; private Gson gson; public LogManager(JedisPool pool) { this.pool = pool; this.gson = new Gson(); } public enum LogType { MOD, SERVER } public class StorageFormat { @SerializedName("mod") public Long modLog; @SerializedName("server") public Long serverLog; } /** * Checks if a channel is enabled. * * @param type Type of log to look for * @param serverID Server ID to check with * @return Boolean of state */ public Boolean isLogEnabled(LogType type, Long serverID) { try (Jedis conn = pool.getResource()) { String storedJSON = conn.hget("logs", "" + serverID); StorageFormat format; if (storedJSON == null || storedJSON.isEmpty()) { // I guess no config was created previously. format = new StorageFormat(); } else { format = gson.fromJson(storedJSON, StorageFormat.class); } switch (type) { case MOD: return !(format.modLog == null); case SERVER: return !(format.serverLog == null); default: // Other types we don't (yet) know of return false; } } } /** * Gets the ID of the channel by type. * * @param serverID Server ID to look up with * @param type Type of log to look for * @return Long with ID of server-log */ public Long getLog(LogType type, Long serverID) { try (Jedis conn = pool.getResource()) { String storedJSON = conn.hget("logs", "" + serverID); StorageFormat format; if (storedJSON == null || storedJSON.isEmpty()) { // I guess no config was created previously. format = new StorageFormat(); } else { format = gson.fromJson(storedJSON, StorageFormat.class); } switch (type) { case MOD: return format.modLog; case SERVER: return format.serverLog; default: return 0L; } } } /** * Sets the ID of the channel by type. * * @param serverID Server ID to associate with * @param type Type of log to associate * @param channelID Channel ID to set */ public void setLog(Long serverID, LogType type, Long channelID) { try (Jedis conn = pool.getResource()) { String storedJSON = conn.hget("logs", "" + serverID); StorageFormat format; if (storedJSON == null || storedJSON.isEmpty()) { // I guess no config was created previously. format = new StorageFormat(); } else { format = gson.fromJson(storedJSON, StorageFormat.class); } switch (type) { case MOD: format.modLog = channelID; break; case SERVER: format.serverLog = channelID; break; } String JSONtoStore = gson.toJson(format); conn.hset("logs", "" + serverID, JSONtoStore); } } /** * "Disables" a log type for a server. * * @param serverID Server ID to associate with * @param type Type of log to associate */ public void disableLog(Long serverID, LogType type) { try (Jedis conn = pool.getResource()) { String storedJSON = conn.hget("logs", "" + serverID); StorageFormat format; if (storedJSON == null || storedJSON.isEmpty()) { // I guess no config was created previously. format = new StorageFormat(); } else { format = gson.fromJson(storedJSON, StorageFormat.class); } switch (type) { case MOD: format.modLog = null; break; case SERVER: format.serverLog = null; break; } String JSONtoStore = gson.toJson(format); conn.hset("logs", "" + serverID, JSONtoStore); } } }
package mondrian.rolap.aggmatcher; import mondrian.olap.MondrianProperties; import mondrian.olap.MondrianDef; import mondrian.olap.Util; import mondrian.rolap.RolapAggregator; import mondrian.rolap.RolapStar; import mondrian.resource.MondrianResource; import mondrian.spi.Dialect; import javax.sql.DataSource; import org.apache.log4j.Logger; import java.lang.ref.SoftReference; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.ResultSet; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Types; import java.sql.SQLException; import java.util.*; /** * Metadata gleaned from JDBC about the tables and columns in the star schema. * This class is used to scrape a database and store information about its * tables and columnIter. * * <p>The structure of this information is as follows: A database has tables. A * table has columnIter. A column has one or more usages. A usage might be a * column being used as a foreign key or as part of a measure. * * <p> Tables are created when calling code requests the set of available * tables. This call <code>getTables()</code> causes all tables to be loaded. * But a table's columnIter are not loaded until, on a table-by-table basis, * a request is made to get the set of columnIter associated with the table. * Since, the AggTableManager first attempts table name matches (recognition) * most tables do not match, so why load their columnIter. * Of course, as a result, there are a host of methods that can throw an * {@link SQLException}, rats. * * @author Richard M. Emberson * @version $Id$ */ public class JdbcSchema { private static final Logger LOGGER = Logger.getLogger(JdbcSchema.class); private static final MondrianResource mres = MondrianResource.instance(); /** * Returns the Logger. */ public Logger getLogger() { return LOGGER; } public interface Factory { JdbcSchema makeDB(DataSource dataSource); void clearDB(JdbcSchema db); void removeDB(JdbcSchema db); } private static final Map<DataSource, SoftReference<JdbcSchema>> dbMap = new HashMap<DataSource, SoftReference<JdbcSchema>>(); /** * How often between sweeping through the dbMap looking for nulls. */ private static final int SWEEP_COUNT = 10; private static int sweepDBCount = 0; public static class StdFactory implements Factory { StdFactory() { } public JdbcSchema makeDB(DataSource dataSource) { return new JdbcSchema(dataSource); } public void clearDB(JdbcSchema db) { // NoOp } public void removeDB(JdbcSchema db) { // NoOp } } private static Factory factory; private static void makeFactory() { if (factory == null) { String classname = MondrianProperties.instance().JdbcFactoryClass.get(); if (classname == null) { factory = new StdFactory(); } else { try { Class<?> clz = Class.forName(classname); factory = (Factory) clz.newInstance(); } catch (ClassNotFoundException ex) { throw mres.BadJdbcFactoryClassName.ex(classname); } catch (InstantiationException ex) { throw mres.BadJdbcFactoryInstantiation.ex(classname); } catch (IllegalAccessException ex) { throw mres.BadJdbcFactoryAccess.ex(classname); } } } } /** * Creates or retrieves an instance of the JdbcSchema for the given * DataSource. * * @param dataSource DataSource * @return instance of the JdbcSchema for the given DataSource */ public static synchronized JdbcSchema makeDB(DataSource dataSource) { makeFactory(); JdbcSchema db = null; SoftReference<JdbcSchema> ref = dbMap.get(dataSource); if (ref != null) { db = ref.get(); } if (db == null) { db = factory.makeDB(dataSource); dbMap.put(dataSource, new SoftReference<JdbcSchema>(db)); } sweepDB(); return db; } /** * Clears information in a JdbcSchema associated with a DataSource. * * @param dataSource DataSource */ public static synchronized void clearDB(DataSource dataSource) { makeFactory(); SoftReference<JdbcSchema> ref = dbMap.get(dataSource); if (ref != null) { JdbcSchema db = ref.get(); if (db != null) { factory.clearDB(db); db.clear(); } else { dbMap.remove(dataSource); } } sweepDB(); } /** * Removes a JdbcSchema associated with a DataSource. * * @param dataSource DataSource */ public static synchronized void removeDB(DataSource dataSource) { makeFactory(); SoftReference<JdbcSchema> ref = dbMap.remove(dataSource); if (ref != null) { JdbcSchema db = ref.get(); if (db != null) { factory.removeDB(db); db.remove(); } } sweepDB(); } /** * Every SWEEP_COUNT calls to this method, go through all elements of * the dbMap removing all that either have null values (null SoftReference) * or those with SoftReference with null content. */ private static void sweepDB() { if (sweepDBCount++ > SWEEP_COUNT) { Iterator<SoftReference<JdbcSchema>> it = dbMap.values().iterator(); while (it.hasNext()) { SoftReference<JdbcSchema> ref = it.next(); if ((ref == null) || (ref.get() == null)) { try { it.remove(); } catch (Exception ex) { // Should not happen, but might still like to // know that something's funky. LOGGER.warn(ex); } } } // reset sweepDBCount = 0; } } // Types of column usages. public static final int UNKNOWN_COLUMN_USAGE = 0x0001; public static final int FOREIGN_KEY_COLUMN_USAGE = 0x0002; public static final int MEASURE_COLUMN_USAGE = 0x0004; public static final int LEVEL_COLUMN_USAGE = 0x0008; public static final int FACT_COUNT_COLUMN_USAGE = 0x0010; public static final int IGNORE_COLUMN_USAGE = 0x0020; public static final String UNKNOWN_COLUMN_NAME = "UNKNOWN"; public static final String FOREIGN_KEY_COLUMN_NAME = "FOREIGN_KEY"; public static final String MEASURE_COLUMN_NAME = "MEASURE"; public static final String LEVEL_COLUMN_NAME = "LEVEL"; public static final String FACT_COUNT_COLUMN_NAME = "FACT_COUNT"; public static final String IGNORE_COLUMN_NAME = "IGNORE"; /** * Enumeration of ways that an aggregate table can use a column. */ enum UsageType { UNKNOWN, FOREIGN_KEY, MEASURE, LEVEL, FACT_COUNT, IGNORE } /** * Determine if the parameter represents a single column type, i.e., the * column only has one usage. * * @param columnType Column types * @return true if column has only one usage. */ public static boolean isUniqueColumnType(Set<UsageType> columnType) { return columnType.size() == 1; } /** * Maps from column type enum to column type name or list of names if the * parameter represents more than on usage. */ public static String convertColumnTypeToName(Set<UsageType> columnType) { if (columnType.size() == 1) { return columnType.iterator().next().name(); } // it's a multi-purpose column StringBuilder buf = new StringBuilder(); int k = 0; for (UsageType usage : columnType) { if (k++ > 0) { buf.append('|'); } buf.append(usage.name()); } return buf.toString(); } /** * Converts a {@link java.sql.Types} value to a * {@link mondrian.spi.Dialect.Datatype}. * * @param javaType JDBC type code, as per {@link java.sql.Types} * @return Datatype */ public static Dialect.Datatype getDatatype(int javaType) { switch (javaType) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: return Dialect.Datatype.Integer; case Types.FLOAT: case Types.REAL: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: return Dialect.Datatype.Numeric; case Types.BOOLEAN: return Dialect.Datatype.Boolean; case Types.DATE: return Dialect.Datatype.Date; case Types.TIME: return Dialect.Datatype.Time; case Types.TIMESTAMP: return Dialect.Datatype.Timestamp; case Types.CHAR: case Types.VARCHAR: default: return Dialect.Datatype.String; } } /** * Returns true if the parameter is a java.sql.Type text type. */ public static boolean isText(int javaType) { switch (javaType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return true; default: return false; } } enum TableUsageType { UNKNOWN, FACT, AGG } /** * A table in a database. */ public class Table { /** * A column in a table. */ public class Column { /** * A usage of a column. */ public class Usage { private final UsageType usageType; private String symbolicName; private RolapAggregator aggregator; // These instance variables are used to hold // stuff which is determines at one place and // then used somewhere else. Generally, a usage // is created before all of its "stuff" can be // determined, hence, usage is not a set of classes, // rather its one class with a bunch of instance // variables which may or may not be used. // measure stuff public RolapStar.Measure rMeasure; // hierarchy stuff public MondrianDef.Relation relation; public MondrianDef.Expression joinExp; public String levelColumnName; // level public RolapStar.Column rColumn; // for subtables public RolapStar.Table rTable; public String rightJoinConditionColumnName; /** * The prefix (possibly null) to use during aggregate table * generation (See AggGen). */ public String usagePrefix; /** * Creates a Usage. * * @param usageType Usage type */ Usage(UsageType usageType) { this.usageType = usageType; } /** * Returns the column with which this usage is associated. * * @return the usage's column. */ public Column getColumn() { return JdbcSchema.Table.Column.this; } /** * Returns the column usage type. */ public UsageType getUsageType() { return usageType; } /** * Sets the symbolic (logical) name associated with this usage. * For example, this might be the measure's name. * * @param symbolicName Symbolic name */ public void setSymbolicName(final String symbolicName) { this.symbolicName = symbolicName; } /** * Returns the usage's symbolic name. */ public String getSymbolicName() { return symbolicName; } /** * Sets the aggregator associated with this usage (if it is a * measure usage). * * @param aggregator Aggregator */ public void setAggregator(final RolapAggregator aggregator) { this.aggregator = aggregator; } /** * Returns the aggregator associated with this usage (if its a * measure usage, otherwise null). */ public RolapAggregator getAggregator() { return aggregator; } public String toString() { StringWriter sw = new StringWriter(64); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { if (getSymbolicName() != null) { pw.print("symbolicName="); pw.print(getSymbolicName()); } if (getAggregator() != null) { pw.print(", aggregator="); pw.print(getAggregator().getName()); } pw.print(", columnType="); pw.print(getUsageType().name()); } } /** This is the name of the column. */ private final String name; /** This is the java.sql.Type enum of the column in the database. */ private int type; /** * This is the java.sql.Type name of the column in the database. */ private String typeName; /** This is the size of the column in the database. */ private int columnSize; /** The number of fractional digits. */ private int decimalDigits; /** Radix (typically either 10 or 2). */ private int numPrecRadix; /** For char types the maximum number of bytes in the column. */ private int charOctetLength; /** * False means the column definitely does not allow NULL values. */ private boolean isNullable; public final MondrianDef.Column column; private final List<JdbcSchema.Table.Column.Usage> usages; /** * This contains the enums of all of the column's usages. */ private final Set<UsageType> usageTypes = Util.enumSetNoneOf(UsageType.class); private Column(final String name) { this.name = name; this.column = new MondrianDef.Column( JdbcSchema.Table.this.getName(), name); this.usages = new ArrayList<JdbcSchema.Table.Column.Usage>(); } /** * Returns the column's name in the database, not a symbolic name. */ public String getName() { return name; } /** * Sets the columnIter java.sql.Type enun of the column. * * @param type */ private void setType(final int type) { this.type = type; } /** * Returns the columnIter java.sql.Type enun of the column. */ public int getType() { return type; } /** * Sets the columnIter java.sql.Type name. * * @param typeName */ private void setTypeName(final String typeName) { this.typeName = typeName; } /** * Returns the columnIter java.sql.Type name. */ public String getTypeName() { return typeName; } /** * Returns this column's table. */ public Table getTable() { return JdbcSchema.Table.this; } /** * Return true if this column is numeric. */ public Dialect.Datatype getDatatype() { return JdbcSchema.getDatatype(getType()); } /** * Sets the size in bytes of the column in the database. * * @param columnSize */ private void setColumnSize(final int columnSize) { this.columnSize = columnSize; } /** * Returns the size in bytes of the column in the database. * */ public int getColumnSize() { return columnSize; } /** * Sets number of fractional digits. * * @param decimalDigits */ private void setDecimalDigits(final int decimalDigits) { this.decimalDigits = decimalDigits; } /** * Returns number of fractional digits. */ public int getDecimalDigits() { return decimalDigits; } /** * Sets Radix (typically either 10 or 2). * * @param numPrecRadix */ private void setNumPrecRadix(final int numPrecRadix) { this.numPrecRadix = numPrecRadix; } /** * Returns Radix (typically either 10 or 2). */ public int getNumPrecRadix() { return numPrecRadix; } /** * For char types the maximum number of bytes in the column. * * @param charOctetLength */ private void setCharOctetLength(final int charOctetLength) { this.charOctetLength = charOctetLength; } /** * For char types the maximum number of bytes in the column. */ public int getCharOctetLength() { return charOctetLength; } /** * False means the column definitely does not allow NULL values. * * @param isNullable */ private void setIsNullable(final boolean isNullable) { this.isNullable = isNullable; } /** * False means the column definitely does not allow NULL values. */ public boolean isNullable() { return isNullable; } /** * How many usages does this column have. A column has * between 0 and N usages. It has no usages if usages is some * administrative column. It has one usage if, for example, its * the fact_count column or a level column (for a collapsed * dimension aggregate). It might have 2 usages if its a foreign key * that is also used as a measure. If its a column used in N * measures, then usages will have N usages. */ public int numberOfUsages() { return usages.size(); } /** * Return true if the column has at least one usage. */ public boolean hasUsage() { return (usages.size() != 0); } /** * Return true if the column has at least one usage of the given * column type. */ public boolean hasUsage(UsageType columnType) { return usageTypes.contains(columnType); } /** * Returns an iterator over all usages. */ public List<Usage> getUsages() { return usages; } /** * Returns an iterator over all usages of the given column type. */ public Iterator<Usage> getUsages(UsageType usageType) { class ColumnTypeIterator implements Iterator<Usage> { private final Iterator<Usage> usageIter; private final UsageType usageType; private Usage nextUsage; ColumnTypeIterator( final List<Usage> usages, final UsageType columnType) { this.usageIter = usages.iterator(); this.usageType = columnType; } public boolean hasNext() { while (usageIter.hasNext()) { Usage usage = usageIter.next(); if (usage.getUsageType() == this.usageType) { nextUsage = usage; return true; } } nextUsage = null; return false; } public Usage next() { return nextUsage; } public void remove() { usageIter.remove(); } } return new ColumnTypeIterator(getUsages(), usageType); } /** * Create a new usage of a given column type. */ public Usage newUsage(UsageType usageType) { this.usageTypes.add(usageType); Usage usage = new Usage(usageType); usages.add(usage); return usage; } public String toString() { StringWriter sw = new StringWriter(256); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { pw.print(prefix); pw.print("name="); pw.print(getName()); pw.print(", typename="); pw.print(getTypeName()); pw.print(", size="); pw.print(getColumnSize()); switch (getType()) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: case Types.FLOAT: case Types.REAL: case Types.DOUBLE: break; case Types.NUMERIC: case Types.DECIMAL: pw.print(", decimalDigits="); pw.print(getDecimalDigits()); pw.print(", numPrecRadix="); pw.print(getNumPrecRadix()); break; case Types.CHAR: case Types.VARCHAR: pw.print(", charOctetLength="); pw.print(getCharOctetLength()); break; case Types.LONGVARCHAR: case Types.DATE: case Types.TIME: case Types.TIMESTAMP: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: default: break; } pw.print(", isNullable="); pw.print(isNullable()); if (hasUsage()) { pw.print(" Usages ["); for (Usage usage : getUsages()) { pw.print('('); usage.print(pw, prefix); pw.print(')'); } pw.println("]"); } } } /** Name of table. */ private final String name; /** Map from column name to column. */ private Map<String, Column> columnMap; /** Sum of all of the table's column's column sizes. */ private int totalColumnSize; /** * Whether the table is a fact, aggregate or other table type. * Note: this assumes that a table has only ONE usage. */ private TableUsageType tableUsageType; /** * Typical table types are: "TABLE", "VIEW", "SYSTEM TABLE", * "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * (Depends what comes out of JDBC.) */ private final String tableType; // mondriandef stuff public MondrianDef.Table table; private boolean allColumnsLoaded; private Table(final String name, String tableType) { this.name = name; this.tableUsageType = TableUsageType.UNKNOWN; this.tableType = tableType; } public void load() throws SQLException { loadColumns(); } /** * Returns the name of the table. */ public String getName() { return name; } /** * Returns the total size of a row (sum of the column sizes). */ public int getTotalColumnSize() { return totalColumnSize; } /** * Returns the number of rows in the table. */ public int getNumberOfRows() { return -1; } /** * Returns the collection of columns in this Table. */ public Collection<Column> getColumns() { return getColumnMap().values(); } /** * Returns an iterator over all column usages of a given type. */ public Iterator<JdbcSchema.Table.Column.Usage> getColumnUsages( final UsageType usageType) { class CTIterator implements Iterator<JdbcSchema.Table.Column.Usage> { private final Iterator<Column> columnIter; private final UsageType columnType; private Iterator<JdbcSchema.Table.Column.Usage> usageIter; private JdbcSchema.Table.Column.Usage nextObject; CTIterator(Collection<Column> columns, UsageType columnType) { this.columnIter = columns.iterator(); this.columnType = columnType; } public boolean hasNext() { while (true) { while ((usageIter == null) || ! usageIter.hasNext()) { if (! columnIter.hasNext()) { nextObject = null; return false; } Column c = columnIter.next(); usageIter = c.getUsages().iterator(); } JdbcSchema.Table.Column.Usage usage = usageIter.next(); if (usage.getUsageType() == columnType) { nextObject = usage; return true; } } } public JdbcSchema.Table.Column.Usage next() { return nextObject; } public void remove() { usageIter.remove(); } } return new CTIterator(getColumns(), usageType); } /** * Returns a column by its name. */ public Column getColumn(final String columnName) { return getColumnMap().get(columnName); } /** * Return true if this table contains a column with the given name. */ public boolean constainsColumn(final String columnName) { return getColumnMap().containsKey(columnName); } /** * Sets the table usage (fact, aggregate or other). * * @param tableUsageType */ public void setTableUsageType(final TableUsageType tableUsageType) { // if usageIter has already been set, then usageIter can NOT be // reset if ((this.tableUsageType != TableUsageType.UNKNOWN) && (this.tableUsageType != tableUsageType)) { throw mres.AttemptToChangeTableUsage.ex( getName(), this.tableUsageType.name(), tableUsageType.name()); } this.tableUsageType = tableUsageType; } /** * Returns the table's usage type. */ public TableUsageType getTableUsageType() { return tableUsageType; } /** * Returns the table's type. */ public String getTableType() { return tableType; } public String toString() { StringWriter sw = new StringWriter(256); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { pw.print(prefix); pw.println("Table:"); String subprefix = prefix + " "; String subsubprefix = subprefix + " "; pw.print(subprefix); pw.print("name="); pw.print(getName()); pw.print(", type="); pw.print(getTableType()); pw.print(", usage="); pw.println(getTableUsageType().name()); pw.print(subprefix); pw.print("totalColumnSize="); pw.println(getTotalColumnSize()); pw.print(subprefix); pw.println("Columns: ["); for (Column column : getColumnMap().values()) { column.print(pw, subsubprefix); pw.println(); } pw.print(subprefix); pw.println("]"); } /** * Returns all of the columnIter associated with a table and creates * Column objects with the column's name, type, type name and column * size. * * @throws SQLException */ private void loadColumns() throws SQLException { if (! allColumnsLoaded) { Connection conn = getDataSource().getConnection(); try { DatabaseMetaData dmd = conn.getMetaData(); String schema = JdbcSchema.this.getSchemaName(); String catalog = JdbcSchema.this.getCatalogName(); String tableName = getName(); String columnNamePattern = "%"; ResultSet rs = null; try { Map<String, Column> map = getColumnMap(); rs = dmd.getColumns( catalog, schema, tableName, columnNamePattern); while (rs.next()) { String name = rs.getString(4); int type = rs.getInt(5); String typeName = rs.getString(6); int columnSize = rs.getInt(7); int decimalDigits = rs.getInt(9); int numPrecRadix = rs.getInt(10); int charOctetLength = rs.getInt(16); String isNullable = rs.getString(18); Column column = new Column(name); column.setType(type); column.setTypeName(typeName); column.setColumnSize(columnSize); column.setDecimalDigits(decimalDigits); column.setNumPrecRadix(numPrecRadix); column.setCharOctetLength(charOctetLength); column.setIsNullable(!"NO".equals(isNullable)); map.put(name, column); totalColumnSize += column.getColumnSize(); } } finally { if (rs != null) { rs.close(); } } } finally { try { conn.close(); } catch (SQLException e) { //ignore } } allColumnsLoaded = true; } } private Map<String, Column> getColumnMap() { if (columnMap == null) { columnMap = new HashMap<String, Column>(); } return columnMap; } } private DataSource dataSource; private String schema; private String catalog; private boolean allTablesLoaded; /** * Tables by name. We use a sorted map so {@link #getTables()}'s output * is in deterministic order. */ private final SortedMap<String, Table> tables = new TreeMap<String, Table>(); JdbcSchema(final DataSource dataSource) { this.dataSource = dataSource; } /** * This forces the tables to be loaded. * * @throws SQLException */ public void load() throws SQLException { loadTables(); } protected void clear() { // keep the DataSource, clear/reset everything else allTablesLoaded = false; schema = null; catalog = null; tables.clear(); } protected void remove() { // set ALL instance variables to null clear(); dataSource = null; } /** * Used for testing allowing one to load tables and their columnIter * from more than one datasource */ void resetAllTablesLoaded() { allTablesLoaded = false; } public DataSource getDataSource() { return dataSource; } protected void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * Sets the database's schema name. * * @param schema Schema name */ public void setSchemaName(final String schema) { this.schema = schema; } /** * Returns the database's schema name. */ public String getSchemaName() { return schema; } /** * Sets the database's catalog name. */ public void setCatalogName(final String catalog) { this.catalog = catalog; } /** * Returns the database's catalog name. */ public String getCatalogName() { return catalog; } /** * Returns the database's tables. The collection is sorted by table name. */ public synchronized Collection<Table> getTables() { return getTablesMap().values(); } /** * Gets a table by name. */ public synchronized Table getTable(final String tableName) { return getTablesMap().get(tableName); } public String toString() { StringWriter sw = new StringWriter(256); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { pw.print(prefix); pw.println("JdbcSchema:"); String subprefix = prefix + " "; String subsubprefix = subprefix + " "; pw.print(subprefix); pw.println("Tables: ["); for (Table table : getTablesMap().values()) { table.print(pw, subsubprefix); } pw.print(subprefix); pw.println("]"); } /** * Gets all of the tables (and views) in the database. * If called a second time, this method is a no-op. * * @throws SQLException */ private void loadTables() throws SQLException { if (allTablesLoaded) { return; } Connection conn = null; try { conn = getDataSource().getConnection(); final DatabaseMetaData databaseMetaData = conn.getMetaData(); String[] tableTypes = { "TABLE", "VIEW" }; if (databaseMetaData.getDatabaseProductName().toUpperCase() .contains("VERTICA")) { for (String tableType : tableTypes) { loadTablesOfType(databaseMetaData, new String[]{tableType}); } } else { loadTablesOfType(databaseMetaData, tableTypes); } allTablesLoaded = true; } finally { if (conn != null) { conn.close(); } } } /** * Loads definition of tables of a given set of table types ("TABLE", "VIEW" * etc.) */ private void loadTablesOfType( DatabaseMetaData databaseMetaData, String[] tableTypes) throws SQLException { final String schema = getSchemaName(); final String catalog = getCatalogName(); final String tableName = "%"; ResultSet rs = null; try { rs = databaseMetaData.getTables( catalog, schema, tableName, tableTypes); if (rs == null) { getLogger().debug("ERROR: rs == null"); return; } while (rs.next()) { addTable(rs); } } finally { if (rs != null) { rs.close(); } } } /** * Makes a Table from an ResultSet: the table's name is the ResultSet third * entry. * * @param rs Result set * @throws SQLException */ protected void addTable(final ResultSet rs) throws SQLException { String name = rs.getString(3); String tableType = rs.getString(4); Table table = new Table(name, tableType); tables.put(table.getName(), table); } private SortedMap<String, Table> getTablesMap() { return tables; } public static synchronized void clearAllDBs() { factory = null; makeFactory(); } } // End JdbcSchema.java
package net.nanase.nanasetter.utils; import netscape.javascript.JSObject; import java.util.Optional; import java.util.function.Consumer; /** * JSObject * * @author Tomona Nanase * @since Nanasetter 0.1 */ public class JSOUtils { private final JSObject jsObject; /** * JSObject * * @param jsObject JSOUtils JSObject */ public JSOUtils(JSObject jsObject) { if (jsObject == null) throw new IllegalArgumentException(); this.jsObject = jsObject; } /** * Consumer * * @param name * @param consumer Consumer */ public void ifExists(String name, Consumer<Object> consumer) { if (name == null) throw new IllegalArgumentException(); if (consumer == null) throw new IllegalArgumentException(); if (this.hasMember(name)) consumer.accept(this.jsObject.getMember(name)); } /** * Consumer * * @param name * @param consumer Consumer */ public void ifExistsAsBoolean(String name, Consumer<Boolean> consumer) { if (name == null) throw new IllegalArgumentException(); if (consumer == null) throw new IllegalArgumentException(); if (!this.hasMember(name)) return; Object obj = this.jsObject.getMember(name); if (obj instanceof Boolean) consumer.accept((Boolean) obj); } /** * Consumer * * @param name * @param consumer Consumer */ public void ifExistsAsString(String name, Consumer<String> consumer) { if (name == null) throw new IllegalArgumentException(); if (consumer == null) throw new IllegalArgumentException(); if (!this.hasMember(name)) return; Object obj = this.jsObject.getMember(name); if (obj instanceof String) consumer.accept((String) obj); } /** * Consumer * * @param name * @param consumer Consumer */ public void ifExistsAsNumber(String name, Consumer<Number> consumer) { if (name == null) throw new IllegalArgumentException(); if (consumer == null) throw new IllegalArgumentException(); if (!this.hasMember(name)) return; Object obj = this.jsObject.getMember(name); if (obj instanceof Number) consumer.accept((Number) obj); } /** * * Optional.empty() * * @param name * @return Optional&lt;Boolean&gt; */ public Optional<Boolean> getBoolean(String name) { if (name == null) throw new IllegalArgumentException(); if (!this.hasMember(name)) return Optional.empty(); Object obj = this.jsObject.getMember(name); if (obj instanceof Boolean) return Optional.of((Boolean) obj); else return Optional.empty(); } /** * * Optional.empty() * * @param name * @return Optional&lt;String&gt; */ public Optional<String> getString(String name) { if (name == null) throw new IllegalArgumentException(); if (!this.hasMember(name)) return Optional.empty(); Object obj = this.jsObject.getMember(name); if (obj instanceof String) return Optional.of((String) obj); else return Optional.empty(); } /** * * Optional.empty() * * @param name * @return Optional&lt;Number&gt; */ public Optional<Number> getNumber(String name) { if (name == null) throw new IllegalArgumentException(); if (!this.hasMember(name)) return Optional.empty(); Object obj = this.jsObject.getMember(name); if (obj instanceof Number) return Optional.of((Number) obj); else return Optional.empty(); } /** * * * @param name * @return true false */ public boolean hasMember(String name) { if (name == null) throw new IllegalArgumentException(); try { //return !this.getTypeString(name).equals("undefined"); return (boolean) this.jsObject.eval("typeof this." + name + " !== 'undefined'"); } catch (netscape.javascript.JSException e) { return false; } } /** * JavaScript * * @param name * @return JavaScript */ public String getTypeString(String name) { if (name == null) throw new IllegalArgumentException(); return (String) this.jsObject.eval("typeof this." + name); } public String[] getMembersList() { return ((String)this.jsObject.eval("Object.keys(this).toString()")).split(","); //return ((String)this.jsObject.eval("Object.keys(this).join(',')")).split(","); } }
package com.arjunmn.chipcloud; import android.content.Context; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.support.constraint.ConstraintLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewGroupCompat; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; public class Chip extends ConstraintLayout implements View.OnClickListener { private int index = -1; private boolean selected = false; private ChipListener listener = null; private int selectedFontColor = -1; private int unselectedFontColor = -1; private TransitionDrawable crossfader; private int selectTransitionMS = 750; private int deselectTransitionMS = 500; private boolean isLocked = false; private ChipCloud.Mode mode; private Object chipData = null; private boolean removable = false; public void setChipData(Object object){ this.chipData = object; } public Object getChipData(){ return this.chipData; } public void setChipListener(ChipListener listener) { this.listener = listener; } public void setChipRemovable(boolean isRemovable){ this.removable = isRemovable; } public Chip(Context context) { super(context); init(); } public Chip(Context context, AttributeSet attrs) { super(context, attrs); init(); } public Chip(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void initChip(Context context, int index, String label, Typeface typeface, int textSizePx, boolean allCaps, int selectedColor, int selectedFontColor, int unselectedColor, int unselectedFontColor, ChipCloud.Mode mode, Object chipData, boolean removable) { this.index = index; this.selectedFontColor = selectedFontColor; this.unselectedFontColor = unselectedFontColor; this.mode = mode; Drawable selectedDrawable = ContextCompat.getDrawable(context, R.drawable.chip_selected); if (selectedColor == -1) { selectedDrawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(context, R.color.dark_grey), PorterDuff.Mode.MULTIPLY)); } else { selectedDrawable.setColorFilter(new PorterDuffColorFilter(selectedColor, PorterDuff.Mode.MULTIPLY)); } if (selectedFontColor == -1) { this.selectedFontColor = ContextCompat.getColor(context, R.color.white); } Drawable unselectedDrawable = ContextCompat.getDrawable(context, R.drawable.chip_selected); if (unselectedColor == -1) { unselectedDrawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(context, R.color.light_grey), PorterDuff.Mode.MULTIPLY)); } else { unselectedDrawable.setColorFilter(new PorterDuffColorFilter(unselectedColor, PorterDuff.Mode.MULTIPLY)); } if (unselectedFontColor == -1) { this.unselectedFontColor = ContextCompat.getColor(context, R.color.chip); } Drawable backgrounds[] = new Drawable[2]; backgrounds[0] = unselectedDrawable; backgrounds[1] = selectedDrawable; crossfader = new TransitionDrawable(backgrounds); //Bug reported on KitKat where padding was removed, so we read the padding values then set again after setting background int leftPad = getPaddingLeft(); int topPad = getPaddingTop(); int rightPad = getPaddingRight(); int bottomPad = getPaddingBottom(); setBackgroundCompat(crossfader); setPadding(leftPad, topPad, rightPad, bottomPad); setText(label); unselect(); if (typeface != null) { setTypeface(typeface); } setAllCaps(allCaps); if (textSizePx > 0) { setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizePx); } setChipData(chipData); setChipRemovable(removable); } public void setLocked(boolean isLocked) { this.isLocked = isLocked; } public void setSelectTransitionMS(int selectTransitionMS) { this.selectTransitionMS = selectTransitionMS; } public void setDeselectTransitionMS(int deselectTransitionMS) { this.deselectTransitionMS = deselectTransitionMS; } private void init() { setOnClickListener(this); } @Override public void onClick(View v) { if(v instanceof TextView){ Log.d("Chip OnClick TV", Integer.toString(v.getId())); } if(v instanceof ImageView){ Log.d("Chip OnClick IV", Integer.toString(v.getId())); } if(v instanceof Chip){ Log.d("Chip OnClick C", Integer.toString(v.getId())); } if(v.getId() == R.id.remove_chip){ Log.d("Chip OnClick ID", Integer.toString(v.getId())); listener.chipRemoved(index, chipData); return; } if (mode != ChipCloud.Mode.NONE) if (selected && !isLocked) { //set as unselected unselect(); if (listener != null) { listener.chipDeselected(index, chipData); } } else if (!selected) { //set as selected crossfader.startTransition(selectTransitionMS); setTextColor(selectedFontColor); if (listener != null) { listener.chipSelected(index, chipData); } } selected = !selected; } public void select() { selected = true; crossfader.startTransition(selectTransitionMS); setTextColor(selectedFontColor); if (listener != null) { listener.chipSelected(index, chipData); } } private void unselect() { if (selected) { crossfader.reverseTransition(deselectTransitionMS); } else { crossfader.resetTransition(); } setTextColor(unselectedFontColor); } @SuppressWarnings("deprecation") private void setBackgroundCompat(Drawable background) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) { setBackgroundDrawable(background); } else { setBackground(background); } } public void deselect() { unselect(); selected = false; } public static class ChipBuilder { private int index; private String label; private Typeface typeface; private int textSizePx; private boolean allCaps; private int selectedColor; private int selectedFontColor; private int unselectedColor; private int unselectedFontColor; private int chipHeight; private int selectTransitionMS = 750; private int deselectTransitionMS = 500; private ChipListener chipListener; private ChipCloud.Mode mode; private Object chipData; private boolean removable = false; public ChipBuilder removable(boolean isRemovable){ this.removable = isRemovable; return this; } public ChipBuilder chipData(Object data){ this.chipData = data; return this; } public ChipBuilder index(int index) { this.index = index; return this; } public ChipBuilder selectedColor(int selectedColor) { this.selectedColor = selectedColor; return this; } public ChipBuilder selectedFontColor(int selectedFontColor) { this.selectedFontColor = selectedFontColor; return this; } public ChipBuilder unselectedColor(int unselectedColor) { this.unselectedColor = unselectedColor; return this; } public ChipBuilder unselectedFontColor(int unselectedFontColor) { this.unselectedFontColor = unselectedFontColor; return this; } public ChipBuilder label(String label) { this.label = label; return this; } public ChipBuilder typeface(Typeface typeface) { this.typeface = typeface; return this; } public ChipBuilder allCaps(boolean allCaps) { this.allCaps = allCaps; return this; } public ChipBuilder textSize(int textSizePx) { this.textSizePx = textSizePx; return this; } public ChipBuilder chipHeight(int chipHeight) { this.chipHeight = chipHeight; return this; } public ChipBuilder chipListener(ChipListener chipListener) { this.chipListener = chipListener; return this; } public ChipBuilder mode(ChipCloud.Mode mode) { this.mode = mode; return this; } public ChipBuilder selectTransitionMS(int selectTransitionMS) { this.selectTransitionMS = selectTransitionMS; return this; } public ChipBuilder deselectTransitionMS(int deselectTransitionMS) { this.deselectTransitionMS = deselectTransitionMS; return this; } public Chip build(Context context) { final Chip chip = (Chip) LayoutInflater.from(context).inflate(R.layout.chip, null); ImageView iv = (ImageView) chip.findViewById(R.id.remove_chip); if(removable){ iv.setVisibility(VISIBLE); }else{ iv.setVisibility(GONE); } iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (chipListener != null) { //chipListener.chipSelected(index, chipData); chip.onClick(v); } } }); chip.initChip(context, index, label, typeface, textSizePx, allCaps, selectedColor, selectedFontColor, unselectedColor, unselectedFontColor, mode, chipData, removable); chip.setSelectTransitionMS(selectTransitionMS); chip.setDeselectTransitionMS(deselectTransitionMS); chip.setChipListener(chipListener); chip.setMinimumHeight(chipHeight); chip.setMaxHeight(chipHeight); // Hack to test if it works with CL chip.setChipData(chipData); chip.setChipRemovable(removable); return chip; } } public void setText(String text){ TextView tv = (TextView) this.findViewById(R.id.chip); tv.setText(text); } public void setAllCaps(boolean allCaps){ TextView tv = (TextView) this.findViewById(R.id.chip); tv.setAllCaps(allCaps); } public void setTypeface(Typeface typeface){ TextView tv = (TextView) this.findViewById(R.id.chip); tv.setTypeface(typeface); } public void setTextSize(int mode, int size){ TextView tv = (TextView) this.findViewById(R.id.chip); tv.setTextSize(mode, size); } public void setTextColor(int color){ TextView tv = (TextView) this.findViewById(R.id.chip); tv.setTextColor(color); } }
package liquibase; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.Writer; import java.text.DateFormat; import java.util.*; import liquibase.change.CheckSum; import liquibase.changelog.*; import liquibase.changelog.filter.*; import liquibase.changelog.visitor.*; import liquibase.database.Database; import liquibase.database.DatabaseConnection; import liquibase.database.DatabaseFactory; import liquibase.database.ObjectQuotingStrategy; import liquibase.database.core.OracleDatabase; import liquibase.diff.DiffGeneratorFactory; import liquibase.diff.DiffResult; import liquibase.diff.compare.CompareControl; import liquibase.diff.output.changelog.DiffToChangeLog; import liquibase.exception.DatabaseException; import liquibase.exception.LiquibaseException; import liquibase.exception.LockException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.Executor; import liquibase.executor.ExecutorService; import liquibase.executor.LoggingExecutor; import liquibase.lockservice.DatabaseChangeLogLock; import liquibase.lockservice.LockService; import liquibase.lockservice.LockServiceFactory; import liquibase.logging.LogFactory; import liquibase.logging.Logger; import liquibase.parser.ChangeLogParser; import liquibase.parser.ChangeLogParserFactory; import liquibase.resource.ResourceAccessor; import liquibase.serializer.ChangeLogSerializer; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.InvalidExampleException; import liquibase.snapshot.SnapshotControl; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.statement.core.RawSqlStatement; import liquibase.statement.core.UpdateStatement; import liquibase.structure.DatabaseObject; import liquibase.util.LiquibaseUtil; import liquibase.util.StreamUtil; import liquibase.util.StringUtils; import javax.xml.parsers.ParserConfigurationException; /** * Primary facade class for interacting with Liquibase. * The built in command line, Ant, Maven and other ways of running Liquibase are wrappers around methods in this class. */ public class Liquibase { private DatabaseChangeLog databaseChangeLog; private String changeLogFile; private ResourceAccessor resourceAccessor; protected Database database; private Logger log; private ChangeLogParameters changeLogParameters; private ChangeExecListener changeExecListener; private ChangeLogSyncListener changeLogSyncListener; private boolean ignoreClasspathPrefix = true; /** * Creates a Liquibase instance for a given DatabaseConnection. The Database instance used will be found with {@link DatabaseFactory#findCorrectDatabaseImplementation(liquibase.database.DatabaseConnection)} * * @See DatabaseConnection * @See Database * @see #Liquibase(String, liquibase.resource.ResourceAccessor, liquibase.database.Database) * @see ResourceAccessor */ public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, DatabaseConnection conn) throws LiquibaseException { this(changeLogFile, resourceAccessor, DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn)); } /** * Creates a Liquibase instance. The changeLogFile parameter must be a path that can be resolved by the passed ResourceAccessor. * If windows style path separators are used for the changeLogFile, they will be standardized to unix style for better cross-system compatib. * * @See DatabaseConnection * @See Database * @see ResourceAccessor */ public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database) throws LiquibaseException { log = LogFactory.getLogger(); if (changeLogFile != null) { this.changeLogFile = changeLogFile.replace('\\', '/'); //convert to standard / if using absolute path on windows } this.resourceAccessor = resourceAccessor; this.changeLogParameters = new ChangeLogParameters(database); this.database = database; } public Liquibase(DatabaseChangeLog changeLog, ResourceAccessor resourceAccessor, Database database) { log = LogFactory.getLogger(); this.databaseChangeLog = changeLog; this.changeLogFile = changeLog.getPhysicalFilePath(); if (this.changeLogFile != null) { changeLogFile = changeLogFile.replace('\\', '/'); //convert to standard / if using absolute path on windows } this.resourceAccessor = resourceAccessor; this.database = database; this.changeLogParameters = new ChangeLogParameters(database); } /** * Return the change log file used by this Liquibase instance. */ public String getChangeLogFile() { return changeLogFile; } /** * Return the log used by this Liquibase instance. */ public Logger getLog() { return log; } /** * Returns the ChangeLogParameters container used by this Liquibase instance. */ public ChangeLogParameters getChangeLogParameters() { return changeLogParameters; } /** * Returns the Database used by this Liquibase instance. */ public Database getDatabase() { return database; } /** * Return ResourceAccessor used by this Liquibase instance. * @deprecated use the newer-terminology version {@link #getResourceAccessor()} */ public ResourceAccessor getFileOpener() { return resourceAccessor; } /** * Return ResourceAccessor used by this Liquibase instance. */ public ResourceAccessor getResourceAccessor() { return resourceAccessor; } /** * Use this function to override the current date/time function used to insert dates into the database. * Especially useful when using an unsupported database. * * @deprecated Should call {@link Database#setCurrentDateTimeFunction(String)} directly */ public void setCurrentDateTimeFunction(String currentDateTimeFunction) { this.database.setCurrentDateTimeFunction(currentDateTimeFunction); } /** * Convience method for {@link #update(Contexts)} that constructs the Context object from the passed string. */ public void update(String contexts) throws LiquibaseException { this.update(new Contexts(contexts)); } /** * Executes Liquibase "update" logic which ensures that the configured {@link Database} is up to date according to the configured changelog file. * To run in "no context mode", pass a null or empty context object. */ public void update(Contexts contexts) throws LiquibaseException { update(contexts, new LabelExpression()); } public void update(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator changeLogIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); changeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY); try { lockService.releaseLock(); } catch (LockException e) { log.severe("Could not release lock", e); } resetServices(); } } public DatabaseChangeLog getDatabaseChangeLog() throws LiquibaseException { if (databaseChangeLog == null) { ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser(changeLogFile, resourceAccessor); databaseChangeLog = parser.parse(changeLogFile, changeLogParameters, resourceAccessor); } return databaseChangeLog; } protected UpdateVisitor createUpdateVisitor() { return new UpdateVisitor(database, changeExecListener); } protected ChangeLogIterator getStandardChangelogIterator(Contexts contexts, LabelExpression labelExpression, DatabaseChangeLog changeLog) throws DatabaseException { return new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); } public void update(String contexts, Writer output) throws LiquibaseException { this.update(new Contexts(contexts), output); } public void update(Contexts contexts, Writer output) throws LiquibaseException { update(contexts, new LabelExpression(), output); } public void update(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update Database Script"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { update(contexts, labelExpression); output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } finally { lockService.releaseLock(); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void update(int changesToApply, String contexts) throws LiquibaseException { update(changesToApply, new Contexts(contexts), new LabelExpression()); } public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(changesToApply)); logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { lockService.releaseLock(); resetServices(); } } public void update(int changesToApply, String contexts, Writer output) throws LiquibaseException { this.update(changesToApply, new Contexts(contexts), new LabelExpression(), output); } public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); LoggingExecutor loggingExecutor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); ExecutorService.getInstance().setExecutor(database, loggingExecutor); outputHeader("Update " + changesToApply + " Change Sets Database Script"); update(changesToApply, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } resetServices(); ExecutorService.getInstance().setExecutor(database, oldTemplate); } private void outputHeader(String message) throws DatabaseException { Executor executor = ExecutorService.getInstance().getExecutor(database); executor.comment("*********************************************************************"); executor.comment(message); executor.comment("*********************************************************************"); executor.comment("Change Log: " + changeLogFile); executor.comment("Ran at: " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date())); DatabaseConnection connection = getDatabase().getConnection(); if (connection != null) { executor.comment("Against: " + connection.getConnectionUserName() + "@" + connection.getURL()); } executor.comment("Liquibase version: " + LiquibaseUtil.getBuildVersion()); executor.comment("*********************************************************************" + StreamUtil.getLineSeparator()); if (database instanceof OracleDatabase) { executor.execute(new RawSqlStatement("SET DEFINE OFF;")); } } public void rollback(int changesToRollback, String contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, new Contexts(contexts), output); } public void rollback(int changesToRollback, Contexts contexts, Writer output) throws LiquibaseException { rollback(changesToRollback, contexts, new LabelExpression(), output); } public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback " + changesToRollback + " Change(s) Script"); rollback(changesToRollback, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(int changesToRollback, String contexts) throws LiquibaseException { rollback(changesToRollback, new Contexts(contexts), new LabelExpression()); } public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); ChangeLogIterator logIterator = new ChangeLogIterator(database.getRanChangeSetList(), changeLog, new AlreadyRanChangeSetFilter(database.getRanChangeSetList(), ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(changesToRollback)); logIterator.run(new RollbackVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { try { lockService.releaseLock(); } catch (LockException e) { log.severe("Error releasing lock", e); } resetServices(); } } public void rollback(String tagToRollBackTo, String contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, new Contexts(contexts), output); } public void rollback(String tagToRollBackTo, Contexts contexts, Writer output) throws LiquibaseException { rollback(tagToRollBackTo, contexts, new LabelExpression(), output); } public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback to '" + tagToRollBackTo + "' Script"); rollback(tagToRollBackTo, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(String tagToRollBackTo, String contexts) throws LiquibaseException { rollback(tagToRollBackTo, new Contexts(contexts)); } public void rollback(String tagToRollBackTo, Contexts contexts) throws LiquibaseException { rollback(tagToRollBackTo, contexts, new LabelExpression()); } public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new AfterTagChangeSetFilter(tagToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); logIterator.run(new RollbackVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { lockService.releaseLock(); } resetServices(); } public void rollback(Date dateToRollBackTo, String contexts, Writer output) throws LiquibaseException { rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression(), output); } public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database)); outputHeader("Rollback to " + dateToRollBackTo + " Script"); rollback(dateToRollBackTo, contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void rollback(Date dateToRollBackTo, String contexts) throws LiquibaseException { rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression()); } public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); changeLog.setIgnoreClasspathPrefix(ignoreClasspathPrefix); List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList(); ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog, new ExecutedAfterChangeSetFilter(dateToRollBackTo, ranChangeSetList), new AlreadyRanChangeSetFilter(ranChangeSetList, ignoreClasspathPrefix), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); logIterator.run(new RollbackVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { lockService.releaseLock(); } resetServices(); } public void changeLogSync(String contexts, Writer output) throws LiquibaseException { changeLogSync(new Contexts(contexts), new LabelExpression(), output); } public void changeLogSync(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to add all changesets to database history table"); changeLogSync(contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void changeLogSync(String contexts) throws LiquibaseException { changeLogSync(new Contexts(contexts), new LabelExpression()); } /** * @deprecated use version with LabelExpression */ public void changeLogSync(Contexts contexts) throws LiquibaseException { changeLogSync(contexts, new LabelExpression()); } public void changeLogSync(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); logIterator.run(new ChangeLogSyncVisitor(database, changeLogSyncListener), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { lockService.releaseLock(); resetServices(); } } public void markNextChangeSetRan(String contexts, Writer output) throws LiquibaseException { markNextChangeSetRan(new Contexts(contexts), new LabelExpression(), output); } public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to add all changesets to database history table"); markNextChangeSetRan(contexts, labelExpression); try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } public void markNextChangeSetRan(String contexts) throws LiquibaseException { markNextChangeSetRan(new Contexts(contexts), new LabelExpression()); } public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(1)); logIterator.run(new ChangeLogSyncVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { lockService.releaseLock(); resetServices(); } } public void futureRollbackSQL(String contexts, Writer output) throws LiquibaseException { futureRollbackSQL(null, contexts, output); } public void futureRollbackSQL(Integer count, String contexts, Writer output) throws LiquibaseException { futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output); } public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LoggingExecutor outputTemplate = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), output, database); Executor oldTemplate = ExecutorService.getInstance().getExecutor(database); ExecutorService.getInstance().setExecutor(database, outputTemplate); outputHeader("SQL to roll back currently unexecuted changes"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator; if (count == null) { logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); } else { ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new CountChangeSetFilter(count)); final ListVisitor listVisitor = new ListVisitor(); forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression)); logIterator = new ChangeLogIterator(changeLog, new NotRanChangeSetFilter(database.getRanChangeSetList()), new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database), new ChangeSetFilter() { @Override public ChangeSetFilterResult accepts(ChangeSet changeSet) { return new ChangeSetFilterResult(listVisitor.getSeenChangeSets().contains(changeSet), null, null); } }); } logIterator.run(new RollbackVisitor(database), new RuntimeEnvironment(database, contexts, labelExpression)); } finally { lockService.releaseLock(); ExecutorService.getInstance().setExecutor(database, oldTemplate); resetServices(); } try { output.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } protected void resetServices() { LockServiceFactory.getInstance().resetAll(); ChangeLogHistoryServiceFactory.getInstance().resetAll(); ExecutorService.getInstance().reset(); } /** * Drops all database objects owned by the current user. */ public final void dropAll() throws DatabaseException, LockException { dropAll(new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName())); } /** * Drops all database objects owned by the current user. */ public final void dropAll(CatalogAndSchema... schemas) throws DatabaseException { try { LockServiceFactory.getInstance().getLockService(database).waitForLock(); for (CatalogAndSchema schema : schemas) { log.info("Dropping Database Objects in schema: " + schema); checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); getDatabase().dropDatabaseObjects(schema); } } catch (DatabaseException e) { throw e; } catch (Exception e) { throw new DatabaseException(e); } finally { try { LockServiceFactory.getInstance().getLockService(database).releaseLock(); } catch (LockException e) { log.severe("Unable to release lock: " + e.getMessage()); } resetServices(); } } /** * 'Tags' the database for future rollback */ public void tag(String tagString) throws LiquibaseException { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); getDatabase().tag(tagString); } finally { lockService.releaseLock(); } } public void updateTestingRollback(String contexts) throws LiquibaseException { updateTestingRollback(new Contexts(contexts), new LabelExpression()); } public void updateTestingRollback(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); Date baseDate = new Date(); update(contexts, labelExpression); rollback(baseDate, contexts, labelExpression); update(contexts, labelExpression); } public void checkLiquibaseTables(boolean updateExistingNullChecksums, DatabaseChangeLog databaseChangeLog, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { ChangeLogHistoryService changeLogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(getDatabase()); changeLogHistoryService.init(); if (updateExistingNullChecksums) { changeLogHistoryService.upgradeChecksums(databaseChangeLog, contexts, labelExpression); } LockServiceFactory.getInstance().getLockService(getDatabase()).init(); } /** * Returns true if it is "save" to migrate the database. * Currently, "safe" is defined as running in an output-sql mode or against a database on localhost. * It is fine to run Liquibase against a "non-safe" database, the method is mainly used to determine if the user * should be prompted before continuing. */ public boolean isSafeToRunUpdate() throws DatabaseException { return getDatabase().isSafeToRunUpdate(); } /** * Display change log lock information. */ public DatabaseChangeLogLock[] listLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); return LockServiceFactory.getInstance().getLockService(database).listLocks(); } public void reportLocks(PrintStream out) throws LiquibaseException { DatabaseChangeLogLock[] locks = listLocks(); out.println("Database change log locks for " + getDatabase().getConnection().getConnectionUserName() + "@" + getDatabase().getConnection().getURL()); if (locks.length == 0) { out.println(" - No locks"); } for (DatabaseChangeLogLock lock : locks) { out.println(" - " + lock.getLockedBy() + " at " + DateFormat.getDateTimeInstance().format(lock.getLockGranted())); } } public void forceReleaseLocks() throws LiquibaseException { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); LockServiceFactory.getInstance().getLockService(database).forceReleaseLock(); } /** * @deprecated use version with LabelExpression */ public List<ChangeSet> listUnrunChangeSets(Contexts contexts) throws LiquibaseException { return listUnrunChangeSets(contexts, new LabelExpression()); } public List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labels); DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labels); changeLog.validate(database, contexts, labels); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labels, changeLog); ListVisitor visitor = new ListVisitor(); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labels)); return visitor.getSeenChangeSets(); } /** * @deprecated use version with LabelExpression */ public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts) throws LiquibaseException { return getChangeSetStatuses(contexts, new LabelExpression()); } /** * Returns the ChangeSetStatuses of all changesets in the change log file and history in the order they would be ran. */ public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(true, changeLog, contexts, labelExpression); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog); StatusVisitor visitor = new StatusVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getStatuses(); } public void reportStatus(boolean verbose, String contexts, Writer out) throws LiquibaseException { reportStatus(verbose, new Contexts(contexts), new LabelExpression(), out); } public void reportStatus(boolean verbose, Contexts contexts, Writer out) throws LiquibaseException { reportStatus(verbose, contexts, new LabelExpression(), out); } public void reportStatus(boolean verbose, Contexts contexts, LabelExpression labels, Writer out) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labels); try { List<ChangeSet> unrunChangeSets = listUnrunChangeSets(contexts, labels); if (unrunChangeSets.size() == 0) { out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(" is up to date"); out.append(StreamUtil.getLineSeparator()); } else { out.append(String.valueOf(unrunChangeSets.size())); out.append(" change sets have not been applied to "); out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(StreamUtil.getLineSeparator()); if (verbose) { for (ChangeSet changeSet : unrunChangeSets) { out.append(" ").append(changeSet.toString(false)).append(StreamUtil.getLineSeparator()); } } } out.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } public Collection<RanChangeSet> listUnexpectedChangeSets(String contexts) throws LiquibaseException { return listUnexpectedChangeSets(new Contexts(contexts), new LabelExpression()); } public Collection<RanChangeSet> listUnexpectedChangeSets(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); DatabaseChangeLog changeLog = getDatabaseChangeLog(); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ContextChangeSetFilter(contexts), new LabelChangeSetFilter(labelExpression), new DbmsChangeSetFilter(database)); ExpectedChangesVisitor visitor = new ExpectedChangesVisitor(database.getRanChangeSetList()); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); return visitor.getUnexpectedChangeSets(); } public void reportUnexpectedChangeSets(boolean verbose, String contexts, Writer out) throws LiquibaseException { reportUnexpectedChangeSets(verbose, new Contexts(contexts), new LabelExpression(), out); } public void reportUnexpectedChangeSets(boolean verbose, Contexts contexts, LabelExpression labelExpression, Writer out) throws LiquibaseException { changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); try { Collection<RanChangeSet> unexpectedChangeSets = listUnexpectedChangeSets(contexts, labelExpression); if (unexpectedChangeSets.size() == 0) { out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(" contains no unexpected changes!"); out.append(StreamUtil.getLineSeparator()); } else { out.append(String.valueOf(unexpectedChangeSets.size())); out.append(" unexpected changes were found in "); out.append(getDatabase().getConnection().getConnectionUserName()); out.append("@"); out.append(getDatabase().getConnection().getURL()); out.append(StreamUtil.getLineSeparator()); if (verbose) { for (RanChangeSet ranChangeSet : unexpectedChangeSets) { out.append(" ").append(ranChangeSet.toString()).append(StreamUtil.getLineSeparator()); } } } out.flush(); } catch (IOException e) { throw new LiquibaseException(e); } } /** * Sets checksums to null so they will be repopulated next run */ public void clearCheckSums() throws LiquibaseException { log.info("Clearing database change log checksums"); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { checkLiquibaseTables(false, null, new Contexts(), new LabelExpression()); UpdateStatement updateStatement = new UpdateStatement(getDatabase().getLiquibaseCatalogName(), getDatabase().getLiquibaseSchemaName(), getDatabase().getDatabaseChangeLogTableName()); updateStatement.addNewColumnValue("MD5SUM", null); ExecutorService.getInstance().getExecutor(database).execute(updateStatement); getDatabase().commit(); } finally { lockService.releaseLock(); } resetServices(); } public final CheckSum calculateCheckSum(final String changeSetIdentifier) throws LiquibaseException { if (changeSetIdentifier == null) { throw new LiquibaseException(new IllegalArgumentException("changeSetIdentifier")); } final List<String> parts = StringUtils.splitAndTrim(changeSetIdentifier, "::"); if (parts == null || parts.size() < 3) { throw new LiquibaseException(new IllegalArgumentException("Invalid changeSet identifier: " + changeSetIdentifier)); } return this.calculateCheckSum(parts.get(0), parts.get(1), parts.get(2)); } public CheckSum calculateCheckSum(final String filename, final String id, final String author) throws LiquibaseException { log.info(String.format("Calculating checksum for changeset %s::%s::%s", filename, id, author)); final ChangeLogParameters changeLogParameters = this.getChangeLogParameters(); final ResourceAccessor resourceAccessor = this.getResourceAccessor(); final DatabaseChangeLog changeLog = ChangeLogParserFactory.getInstance().getParser(this.changeLogFile, resourceAccessor).parse(this.changeLogFile, changeLogParameters, resourceAccessor); // TODO: validate? final ChangeSet changeSet = changeLog.getChangeSet(filename, author, id); if (changeSet == null) { throw new LiquibaseException(new IllegalArgumentException("No such changeSet: " + filename + "::" + id + "::" + author)); } return changeSet.generateCheckSum(); } public void generateDocumentation(String outputDirectory) throws LiquibaseException { // call without context generateDocumentation(outputDirectory, new Contexts(), new LabelExpression()); } public void generateDocumentation(String outputDirectory, String contexts) throws LiquibaseException { generateDocumentation(outputDirectory, new Contexts(contexts), new LabelExpression()); } public void generateDocumentation(String outputDirectory, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException { log.info("Generating Database Documentation"); changeLogParameters.setContexts(contexts); changeLogParameters.setLabels(labelExpression); LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); try { DatabaseChangeLog changeLog = getDatabaseChangeLog(); checkLiquibaseTables(false, changeLog, new Contexts(), new LabelExpression()); changeLog.validate(database, contexts, labelExpression); ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new DbmsChangeSetFilter(database)); DBDocVisitor visitor = new DBDocVisitor(database); logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression)); visitor.writeHTML(new File(outputDirectory), resourceAccessor); } catch (IOException e) { throw new LiquibaseException(e); } finally { lockService.releaseLock(); } // try { // if (!LockService.getExecutor(database).waitForLock()) { // return; // DBDocChangeLogHandler changeLogHandler = new DBDocChangeLogHandler(outputDirectory, this, changeLogFile,resourceAccessor); // runChangeLogs(changeLogHandler); // changeLogHandler.writeHTML(this); // } finally { // releaseLock(); } public DiffResult diff(Database referenceDatabase, Database targetDatabase, CompareControl compareControl) throws LiquibaseException { return DiffGeneratorFactory.getInstance().compare(referenceDatabase, targetDatabase, compareControl); } /** * Checks changelogs for bad MD5Sums and preconditions before attempting a migration */ public void validate() throws LiquibaseException { DatabaseChangeLog changeLog = getDatabaseChangeLog(); changeLog.validate(database); } public void setChangeLogParameter(String key, Object value) { this.changeLogParameters.set(key, value); } /** * Add safe database properties as changelog parameters.<br/> * Safe properties are the ones that doesn't have side effects in liquibase state and also don't change in during the liquibase execution * @param database Database which propeties are put in the changelog * @throws DatabaseException */ private void setDatabasePropertiesAsChangelogParameters(Database database) throws DatabaseException { setChangeLogParameter("database.autoIncrementClause", database.getAutoIncrementClause(null, null)); setChangeLogParameter("database.currentDateTimeFunction", database.getCurrentDateTimeFunction()); setChangeLogParameter("database.databaseChangeLogLockTableName", database.getDatabaseChangeLogLockTableName()); setChangeLogParameter("database.databaseChangeLogTableName", database.getDatabaseChangeLogTableName()); setChangeLogParameter("database.databaseMajorVersion", database.getDatabaseMajorVersion()); setChangeLogParameter("database.databaseMinorVersion", database.getDatabaseMinorVersion()); setChangeLogParameter("database.databaseProductName", database.getDatabaseProductName()); setChangeLogParameter("database.databaseProductVersion", database.getDatabaseProductVersion()); setChangeLogParameter("database.defaultCatalogName", database.getDefaultCatalogName()); setChangeLogParameter("database.defaultSchemaName", database.getDefaultSchemaName()); setChangeLogParameter("database.defaultSchemaNamePrefix", StringUtils.trimToNull(database.getDefaultSchemaName())==null?"":"."+database.getDefaultSchemaName()); setChangeLogParameter("database.lineComment", database.getLineComment()); setChangeLogParameter("database.liquibaseSchemaName", database.getLiquibaseSchemaName()); setChangeLogParameter("database.liquibaseTablespaceName", database.getLiquibaseTablespaceName()); setChangeLogParameter("database.typeName", database.getShortName()); setChangeLogParameter("database.isSafeToRunUpdate", database.isSafeToRunUpdate()); setChangeLogParameter("database.requiresPassword", database.requiresPassword()); setChangeLogParameter("database.requiresUsername", database.requiresUsername()); setChangeLogParameter("database.supportsForeignKeyDisable", database.supportsForeignKeyDisable()); setChangeLogParameter("database.supportsInitiallyDeferrableColumns", database.supportsInitiallyDeferrableColumns()); setChangeLogParameter("database.supportsRestrictForeignKeys", database.supportsRestrictForeignKeys()); setChangeLogParameter("database.supportsSchemas", database.supportsSchemas()); setChangeLogParameter("database.supportsSequences", database.supportsSequences()); setChangeLogParameter("database.supportsTablespaces", database.supportsTablespaces()); } private LockService getLockService() { return LockServiceFactory.getInstance().getLockService(database); } public void setChangeExecListener(ChangeExecListener listener) { this.changeExecListener = listener; } public void setChangeLogSyncListener(ChangeLogSyncListener changeLogSyncListener) { this.changeLogSyncListener = changeLogSyncListener; } public void setIgnoreClasspathPrefix(boolean ignoreClasspathPrefix) { this.ignoreClasspathPrefix = ignoreClasspathPrefix; } public boolean isIgnoreClasspathPrefix() { return ignoreClasspathPrefix; } public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException { generateChangeLog(catalogAndSchema, changeLogWriter, outputStream, null, snapshotTypes); } public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, ChangeLogSerializer changeLogSerializer, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException { Set<Class<? extends DatabaseObject>> finalCompareTypes = null; if (snapshotTypes != null && snapshotTypes.length > 0) { finalCompareTypes = new HashSet<Class<? extends DatabaseObject>>(Arrays.asList(snapshotTypes)); } SnapshotControl snapshotControl = new SnapshotControl(this.getDatabase(), snapshotTypes); CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[]{new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema)}, finalCompareTypes); // compareControl.addStatusListener(new OutDiffStatusListener()); DatabaseSnapshot originalDatabaseSnapshot = null; try { originalDatabaseSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), getDatabase(), snapshotControl); DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(originalDatabaseSnapshot, SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), null, snapshotControl), compareControl); changeLogWriter.setDiffResult(diffResult); if(changeLogSerializer != null) { changeLogWriter.print(outputStream, changeLogSerializer); } else { changeLogWriter.print(outputStream); } } catch (InvalidExampleException e) { throw new UnexpectedLiquibaseException(e); } } }
package org.jfree.data.time; import java.io.Serializable; /** * Represents a time period and an associated value. */ public class TimePeriodValue implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3390443360845711275L; /** The time period. */ private TimePeriod period; /** The value associated with the time period. */ private Number value; public TimePeriodValue(TimePeriod period, Number value) { if (period == null) { throw new IllegalArgumentException("Null 'period' argument."); } this.period = period; this.value = value; } public TimePeriodValue(TimePeriod period, double value) { this(period, new Double(value)); } /** * Returns the time period. * * @return The time period (never <code>null</code>). */ public TimePeriod getPeriod() { return this.period; } /** * Returns the value. * * @return The value (possibly <code>null</code>). * * @see #setValue(Number) */ public Number getValue() { return this.value; } /** * Sets the value for this data item. * * @param value the new value (<code>null</code> permitted). * * @see #getValue() */ public void setValue(Number value) { this.value = value; } /** * Tests this object for equality with the target object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof TimePeriodValue)) { return false; } TimePeriodValue timePeriodValue = (TimePeriodValue) obj; if (this.period != null ? !this.period.equals(timePeriodValue.period) : timePeriodValue.period != null) { return false; } if (this.value != null ? !this.value.equals(timePeriodValue.value) : timePeriodValue.value != null) { return false; } return true; } /** * Returns a hash code value for the object. * * @return The hashcode */ public int hashCode() { int result; result = (this.period != null ? this.period.hashCode() : 0); result = 29 * result + (this.value != null ? this.value.hashCode() : 0); return result; } /** * Clones the object. * <P> * Note: no need to clone the period or value since they are immutable * classes. * * @return A clone. */ public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { // won't get here... e.printStackTrace(); } return clone; } /** * Returns a string representing this instance, primarily for use in * debugging. * * @return A string. */ public String toString() { return "TimePeriodValue[" + getPeriod() + "," + getValue() + "]"; } }
package nl.mpi.arbil; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.channels.FileChannel; import java.util.HashSet; import java.util.Set; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.data.ArbilTreeHelper; import nl.mpi.arbil.data.DataNodeLoader; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.ApplicationVersionManager; import nl.mpi.arbil.util.BugCatcher; import nl.mpi.arbil.util.DefaultMimeHashQueue; import nl.mpi.arbil.util.MessageDialogHandler; import org.junit.After; /** * * @author Twan Goosen <twan.goosen@mpi.nl> */ public abstract class ArbilTest { private ArbilTreeHelper treeHelper; private SessionStorage sessionStorage; private MessageDialogHandler dialogHandler; private BugCatcher bugCatcher; private DefaultMimeHashQueue mimeHashQueue; private Set<URI> localTreeItems; private DataNodeLoader dataNodeLoader; @After public void cleanUp() { sessionStorage = null; treeHelper = null; localTreeItems = null; } protected void addToLocalTreeFromResource(String resourceClassPath) throws URISyntaxException, InterruptedException { addToLocalTreeFromURI(uriFromResource(resourceClassPath)); } protected void addToLocalTreeFromURI(URI uri) throws InterruptedException, URISyntaxException { if (localTreeItems == null) { localTreeItems = new HashSet<URI>(); } localTreeItems.add(uri); getTreeHelper().addLocation(uri); for (ArbilNode node : getTreeHelper().getLocalCorpusNodes()) { waitForNodeToLoad((ArbilDataNode) node); } } protected static void waitForNodeToLoad(ArbilDataNode node) { while (node.isLoading() || !node.isDataLoaded()) { try { Thread.sleep(100); node.waitTillLoaded(); } catch (InterruptedException ex) { } } try { Thread.sleep(100); } catch (InterruptedException ex) { } } protected URI uriFromResource(String resourceClassPath) throws URISyntaxException { return getClass().getResource(resourceClassPath).toURI(); } protected ArbilDataNode dataNodeFromUri(String uriString) throws URISyntaxException { return dataNodeFromUri(new URI(uriString)); } protected ArbilDataNode dataNodeFromUri(URI uri) { ArbilDataNode dataNode = getDataNodeLoader().getArbilDataNode(this, uri); waitForNodeToLoad(dataNode); return dataNode; } protected ArbilDataNode dataNodeFromResource(String resourceClassPath) throws URISyntaxException { return dataNodeFromUri(uriFromResource(resourceClassPath)); } protected URI copyOfResource(URI uri) throws FileNotFoundException, IOException { File in = new File(uri); File out = new File(in.getParentFile(), System.currentTimeMillis() + in.getName()); if (out.exists()) { if (!out.delete()) { throw new IOException("File already exists"); } } FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } out.deleteOnExit(); return out.toURI(); } protected void inject() throws Exception { ArbilTestInjector injector = new ArbilTestInjector(); injector.injectVersionManager(new ApplicationVersionManager(new ArbilVersion())); injector.injectBugCatcher(getBugCatcher()); injector.injectDialogHandler(getDialogHandler()); injector.injectSessionStorage(getSessionStorage()); injector.injectDataNodeLoader(getDataNodeLoader()); injector.injectTreeHelper(getTreeHelper()); } protected synchronized DataNodeLoader getDataNodeLoader() { if (dataNodeLoader == null) { dataNodeLoader = newDataNodeLoader(); } return dataNodeLoader; } private synchronized DataNodeLoader newDataNodeLoader() { ArbilDataNodeLoader loader = new ArbilDataNodeLoader(getBugCatcher(), getDialogHandler(), getSessionStorage(), getMimeHashQueue(), getTreeHelper()); getMimeHashQueue().setDataNodeLoader(loader); getTreeHelper().setDataNodeLoader(loader); return loader; } protected synchronized DefaultMimeHashQueue getMimeHashQueue() { if (mimeHashQueue == null) { mimeHashQueue = newMimeHashQueue(); } return mimeHashQueue; } protected DefaultMimeHashQueue newMimeHashQueue() { DefaultMimeHashQueue hashQueue = new DefaultMimeHashQueue(getSessionStorage()); hashQueue.setBugCatcher(getBugCatcher()); hashQueue.setMessageDialogHandler(getDialogHandler()); return hashQueue; } protected synchronized ArbilTreeHelper getTreeHelper() { if (treeHelper == null) { treeHelper = newTreeHelper(); treeHelper.init(); } return treeHelper; } protected synchronized SessionStorage getSessionStorage() { if (sessionStorage == null) { sessionStorage = newSessionStorage(); } return sessionStorage; } protected synchronized BugCatcher getBugCatcher() { if (bugCatcher == null) { bugCatcher = newBugCatcher(); } return bugCatcher; } protected synchronized MessageDialogHandler getDialogHandler() { if (dialogHandler == null) { dialogHandler = newDialogHandler(); } return dialogHandler; } protected ArbilTreeHelper newTreeHelper() { ArbilTreeHelper newTreeHelper = new ArbilTreeHelper(getSessionStorage(), getDialogHandler(), getBugCatcher()); newTreeHelper.init(); return newTreeHelper; } protected SessionStorage newSessionStorage() { return new MockSessionStorage() { @Override public boolean pathIsInsideCache(File fullTestFile) { return localTreeItems.contains(fullTestFile.toURI()); } }; } protected BugCatcher newBugCatcher() { return new MockBugCatcher(); } protected MessageDialogHandler newDialogHandler() { return new MockDialogHandler(); } static public boolean deleteDirectory(File path) { if (path.exists() && path.isDirectory()) { File[] files = path.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } } return (path.delete()); } }
package radlab.rain.workload.rubbos; import java.util.Arrays; import java.util.Calendar; import java.util.concurrent.atomic.AtomicInteger; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpStatus; import radlab.rain.util.HttpTransport; import radlab.rain.workload.rubbos.model.RubbosCategory; import radlab.rain.workload.rubbos.model.RubbosComment; import radlab.rain.workload.rubbos.model.RubbosStory; import radlab.rain.workload.rubbos.model.RubbosUser; /** * Collection of RUBBoS utilities. * * @author <a href="mailto:marco.guazzone@gmail.com">Marco Guazzone</a> */ public final class RubbosUtility { public static final int ANONYMOUS_USER_ID = 0; public static final int INVALID_CATEGORY_ID = -1; public static final int INVALID_COMMENT_ID = -1; public static final int INVALID_OPERATION_ID = -1; public static final int INVALID_STORY_ID = -1; public static final int INVALID_USER_ID = -1; public static final int MIN_RATING_VALUE = -1; public static final int MAX_RATING_VALUE = 1; private static final int MIN_USER_ID = 1; ///< Mininum value for user IDs private static final int MAX_COMMENT_SUBJECT_LENGTH = 100; ///< Maximum length for a comment's subject private static final int MAX_STORY_TITLE_LENGTH = 100; ///< Maximum length for a story's title private static AtomicInteger _userId; private Random _rng = null; private RubbosConfiguration _conf = null; private Pattern _pageRegex = Pattern.compile("^.*?[&?]page=(\\d+).*?(?:[&?]page=(\\d+).*?)?$"); private static int nextUserId() { return _userId.incrementAndGet(); } private static int lastUserId() { return _userId.get(); } private static synchronized void initUserId(int numPreloadUsers) { _userId = new AtomicInteger(MIN_USER_ID+numPreloadUsers-1); } public RubbosUtility() { } public RubbosUtility(Random rng, RubbosConfiguration conf) { this._rng = rng; this._conf = conf; initUserId(this._conf.getNumOfPreloadedUsers()); } public void setRandomGenerator(Random rng) { this._rng = rng; } public Random getRandomGenerator() { return this._rng; } public void setConfiguration(RubbosConfiguration conf) { this._conf = conf; initUserId(this._conf.getNumOfPreloadedUsers()); } public RubbosConfiguration getConfiguration() { return this._conf; } public boolean isAnonymousUser(RubbosUser user) { return this.isValidUser(user) && this.isAnonymousUser(user.id); } public boolean isAnonymousUser(int userId) { return ANONYMOUS_USER_ID == userId; } public boolean isRegisteredUser(RubbosUser user) { return this.isValidUser(user) && !this.isAnonymousUser(user.id); } public boolean isRegisteredUser(int userId) { return !this.isAnonymousUser(userId); } public boolean isValidUser(RubbosUser user) { return null != user && INVALID_USER_ID != user.id && (MIN_USER_ID <= user.id || this.isAnonymousUser(user.id)); } public boolean isValidCategory(RubbosCategory category) { return null != category && INVALID_CATEGORY_ID != category.id; } public boolean isValidStory(RubbosStory story) { return null != story && INVALID_STORY_ID != story.id; } public boolean isValidStory(int storyId) { return INVALID_STORY_ID != storyId; } public boolean isValidComment(RubbosComment comment) { return null != comment && INVALID_COMMENT_ID != comment.id; } public boolean checkHttpResponse(HttpTransport httpTransport, String response) { if (response == null || response.length() == 0 || HttpStatus.SC_OK != httpTransport.getStatusCode() /*|| -1 != response.indexOf("ERROR")*/) { return false; } return true; } public boolean checkRubbosResponse(String response) { if (response == null || response.length() == 0 || -1 != response.indexOf("ERROR")) { return false; } return true; } /** * Creates a new RUBBoS user object. * * @return an instance of RubbosUser. */ public RubbosUser newUser() { return this.getUser(nextUserId()); } /** * Generate a random RUBBoS user among the ones already preloaded. * * @return an instance of RubbosUser. */ public RubbosUser generateUser() { // Only generate a user among the ones that have been already preloaded in the DB int userId = this._rng.nextInt(this._conf.getNumOfPreloadedUsers())+MIN_USER_ID; return this.getUser(userId); } /** * Get the RUBBoS user associated to the given identifier. * * @param id The user identifier. * @return an instance of RubbosUser. */ public RubbosUser getUser(int id) { RubbosUser user = new RubbosUser(); user.id = id; user.firstname = "Great" + user.id; user.lastname = "User" + user.id; user.nickname = "user" + user.id; user.email = user.firstname + "." + user.lastname + "@rubbos.com"; user.password = "password" + user.id; user.rating = MIN_RATING_VALUE; user.access = 0; Calendar cal = Calendar.getInstance(); user.creationDate = cal.getTime(); return user; } public RubbosComment newComment() { StringBuffer subject = new StringBuffer(); StringBuffer body = new StringBuffer(); int size = this._rng.nextInt(MAX_COMMENT_SUBJECT_LENGTH) + 1; do { subject.append(this.generateWord(true)); } while ((subject != null) && (subject.length() < size)); subject.setLength(size); // Make sure the subject is exactly of 'size' chars size = this._rng.nextInt(this._conf.getMaxCommentLength()) + 1; do { body.append(this.generateWord(true)); } while ((body != null) && (body.length() < size)); body.setLength(size); // Make sure the body is exactly of 'size' chars RubbosComment comment = new RubbosComment(); comment.id = INVALID_COMMENT_ID; comment.writer = INVALID_USER_ID; comment.storyId = INVALID_STORY_ID; comment.parent = INVALID_COMMENT_ID; comment.childs = INVALID_COMMENT_ID; Calendar cal = Calendar.getInstance(); comment.rating = 0; comment.date = cal.getTime(); comment.subject = subject.toString(); comment.body = body.toString(); return comment; } public RubbosStory newStory() { StringBuffer title = new StringBuffer(); StringBuffer body = new StringBuffer(); int size = this._rng.nextInt(MAX_STORY_TITLE_LENGTH) + 1; do { title.append(this.generateWord(true)); } while ((title != null) && (title.length() < size)); title.setLength(size); // Make sure the title is exactly of 'size' chars size = this._rng.nextInt(this._conf.getMaxStoryLength()) + 1; do { body.append(this.generateWord(true)); } while ((body != null) && (body.length() < size)); body.setLength(size); // Make sure the body is exactly of 'size' chars RubbosStory story = new RubbosStory(); story.id = INVALID_STORY_ID; story.title = title.toString(); story.body = body.toString(); Calendar cal = Calendar.getInstance(); story.date = cal.getTime(); story.writer = INVALID_USER_ID; story.category = INVALID_CATEGORY_ID; return story; } /** * Parses the given HTML text to find a story identifier. * * @param html The HTML string where to look for the item identifier. * @return The found story identifier, or INVALID_STORY_ID if * no story identifier is found. If more than one story is found, returns * the one picked at random. * * This method is based on the edu.rice.rubbos.client.UserSession#extractStoryIdFromHTML. */ public int findStoryIdInHtml(String html) { if (html == null) { return INVALID_STORY_ID; } int[] pos = this.findRandomLastIndexInHtml(html, "storyId=", false); if (pos == null) { return INVALID_STORY_ID; } String str = html.substring(pos[0], pos[1]); return Integer.parseInt(str); } /** * Extract the story identifier from the review story page for an accept or reject. * If several entries are found, one of them is picked up randomly. * * @return the selected story identifier */ public Integer findAcceptRejectStoryIdInHtml(String html, String scriptName) { if (html == null) { return INVALID_STORY_ID; } int[] pos = this.findRandomLastIndexInHtml(html, scriptName, false); if (pos == null) { return INVALID_STORY_ID; } int storyId = INVALID_STORY_ID; int newLast = this.findLastIndexInHtml(html, "storyId=", pos[1]); if (newLast != pos[1]) { storyId = Integer.parseInt(html.substring(pos[1]+"storyId=".length()+1, newLast)); } return storyId; } /** * Parses the given HTML text to find an item identifier. * * @param html The HTML string where to look for the item identifier. * @return The found item identifier, or INVALID_ITEM_ID if * no item identifier is found. If more than one item is found, returns the * one picked at random. * * This method is based on the edu.rice.rubbos.client.UserSession#extractCategoryFromHTML. */ public RubbosCategory findCategoryInHtml(String html) { if (html == null) { return null; } // Randomly choose a category int[] pos = this.findRandomLastIndexInHtml(html, "category=", false); if (pos == null) { return null; } String str = html.substring(pos[0], pos[1]); int categoryId = Integer.parseInt(str); String categoryName = null; int newLast = this.findLastIndexInHtml(html, "categoryName=", pos[1]); if (newLast != pos[1]) { categoryName = html.substring(pos[1]+"categoryName=".length()+1, newLast); } RubbosCategory category = new RubbosCategory(); category.id = categoryId; category.name = categoryName; return category; } /** * Extract Post-Comment parameters from the last HTML reply. * * If several entries are found, one of them is picked up randomly. * * @return a map containing the found parameters */ public Map<String,String> findPostCommentParamsInHtml(String html, String scriptName) { if (html == null) { return null; } int[] pos = this.findRandomLastIndexInHtml(html, scriptName, false); if (pos == null) { return null; } // Now we have chosen a 'scriptName?...' we can extract the parameters String commentTable = null; int storyId = INVALID_STORY_ID; int parent = INVALID_COMMENT_ID; int newLast = this.findLastIndexInHtml(html, "comment_table=", pos[1]); if (newLast != pos[1]) { commentTable = html.substring(pos[1]+"comment_table=".length()+1, newLast); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "storyId=", pos[1]); if (newLast != pos[1]) { storyId = Integer.parseInt(html.substring(pos[1]+"storyId=".length()+1, newLast)); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "parent=", pos[1]); if (newLast != pos[1]) { parent = Integer.parseInt(html.substring(pos[1]+"parent=".length()+1, newLast)); } Map<String,String> result = new HashMap(3); result.put("comment_table", commentTable); result.put("storyId", Integer.toString(storyId)); result.put("parent", Integer.toString(parent)); return result; } /** * Extract View-Comment parameters from the last HTML reply. * * If several entries are found, one of them is picked up randomly. * * @return a map containing the found parameters */ public Map<String,String> findViewCommentParamsInHtml(String html, String scriptName) { if (html == null) { return null; } int[] pos = this.findRandomLastIndexInHtml(html, scriptName, false); if (pos == null) { return null; } // Now we have chosen a 'scriptName?...' we can extract the parameters String commentTable = null; int storyId = INVALID_STORY_ID; int commentId = INVALID_COMMENT_ID; int filter = 0; int display = 0; int newLast = this.findLastIndexInHtml(html, "comment_table=", pos[1]); if (newLast != pos[1]) { commentTable = html.substring(pos[1]+"comment_table=".length()+1, newLast); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "storyId=", pos[1]); if (newLast != pos[1]) { storyId = Integer.parseInt(html.substring(pos[1]+"storyId=".length()+1, newLast)); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "commentId=", pos[1]); if (newLast != pos[1]) { commentId = Integer.parseInt(html.substring(pos[1]+"commentId=".length()+1, newLast)); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "filter=", pos[1]); if (newLast != pos[1]) { filter = Integer.parseInt(html.substring(pos[1]+"filter=".length()+1, newLast)); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "display=", pos[1]); if (newLast != pos[1]) { filter = Integer.parseInt(html.substring(pos[1]+"display=".length()+1, newLast)); } Map<String,String> result = new HashMap(5); result.put("comment_table", commentTable); result.put("storyId", Integer.toString(storyId)); result.put("commentId", Integer.toString(commentId)); result.put("filter", Integer.toString(filter)); result.put("display", Integer.toString(display)); return result; } /** * Extract Moderate-Comment parameters from the last HTML reply. * * If several entries are found, one of them is picked up randomly. * * @return a map containing the found parameters */ public Map<String,String> findModerateCommentParamsInHtml(String html, String scriptName) { if (html == null) { return null; } int[] pos = this.findRandomLastIndexInHtml(html, scriptName, false); if (pos == null) { return null; } // Now we have chosen a 'scriptName?...' we can extract the parameters String commentTable = null; int commentId = INVALID_COMMENT_ID; int newLast = this.findLastIndexInHtml(html, "comment_table=", pos[1]); if (newLast != pos[1]) { commentTable = html.substring(pos[1]+"comment_table=".length()+1, newLast); } pos[1] = newLast; newLast = this.findLastIndexInHtml(html, "commentId=", pos[1]); if (newLast != pos[1]) { commentId = Integer.parseInt(html.substring(pos[1]+"commentId=".length()+1, newLast)); } pos[1] = newLast; Map<String,String> result = new HashMap(2); result.put("comment_table", commentTable); result.put("commentId", Integer.toString(commentId)); return result; } /** * Extract an int value corresponding to the given key * from the last HTML reply. Example : * <pre>int userId = extractIdFromHTML("&userId=")</pre> * * @param key the pattern to look for * @return the <code>int</code> value or -1 on error. */ public int findIntInHtml(String html, String key) { if (html == null) { return -1; } // Look for the key int keyIndex = html.indexOf(key); if (keyIndex == -1) { return -1; } int lastIndex = html.indexOf('\"', keyIndex+key.length()); lastIndex = minIndex(lastIndex, html.indexOf('?', keyIndex+key.length())); lastIndex = minIndex(lastIndex, html.indexOf('&', keyIndex+key.length())); lastIndex = minIndex(lastIndex, html.indexOf('>', keyIndex+key.length())); return Integer.parseInt(html.substring(keyIndex+key.length(), lastIndex)); } /** * Parses the given HTML text to find the page value. * * @param html The HTML string where to look for the item identifier. * @return The page value. * * This method is based on the edu.rice.rubbos.client.UserSession#extractPageFromHTML */ public int findPageInHtml(String html) { if (html == null) { return 0; } // int firstPageIdx = html.indexOf("&page="); // if (firstPageIdx == -1) // return 0; // int secondPageIdx = html.indexOf("&page=", firstPageIdx + 6); // 6 equals to &page= // int chosenIdx = 0; // if (secondPageIdx == -1) // chosenIdx = firstPageIdx; // First or last page => go to next or previous page // else // // Choose randomly a page (previous or next) // if (this._rng.nextInt(100000) < 50000) // chosenIdx = firstPageIdx; // else // chosenIdx = secondPageIdx; // int lastIdx = minIndex(Integer.MAX_VALUE, html.indexOf('\"', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('?', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('&', chosenIdx + 6)); // lastIdx = minIndex(lastIdx, html.indexOf('>', chosenIdx + 6)); // String str = html.substring(chosenIdx + 6, lastIdx); // return Integer.parseInt(str); ////Pattern p = Pattern.compile("^.*?[&?]page=([^\"?&]*).*(?:[&?]page=([^\"?&]*).*)?$"); //Pattern p = Pattern.compile("^.*?[&?]page=(\\d+).*?(?:[&?]page=(\\d+).*?)?$"); Matcher m = _pageRegex.matcher(html); if (m.matches()) { if (m.groupCount() == 2 && m.group(2) != null) { // Choose randomly a page (previous or next) if (this._rng.nextFloat() < 0.5) { return Integer.parseInt(m.group(1)); } return Integer.parseInt(m.group(2)); } // First or last page => go to next or previous page return (m.group(1) != null) ? Integer.parseInt(m.group(1)) : 0; } return 0; } /** * Compute the index of the end character of a key value. * * If the key is not found, the lastIndex value is returned unchanged. * * This method is based on the edu.rice.rubbos.client.UserSession#computeLastIndex. * * @param html the string where looking for * @param key the key to look for * @param lastIndex index to start the lookup in html * @return new lastIndex value */ public int findLastIndexInHtml(String html, String key, int lastIndex) { if (html == null) { return -1; } int keyIndex = html.indexOf(key, lastIndex); if (keyIndex != -1) { keyIndex += key.length(); lastIndex = html.indexOf('\"', keyIndex); lastIndex = minIndex(lastIndex, html.indexOf('?', keyIndex)); lastIndex = minIndex(lastIndex, html.indexOf('&', keyIndex)); lastIndex = minIndex(lastIndex, html.indexOf('>', keyIndex)); } return lastIndex; } /** * Compute the index of the end character of a key value. * * If the key is not found, the lastIndex value is returned unchanged. * * This method is based on the edu.rice.rubbos.client.UserSession#randomComputeLastIndex. * * @param html the string where looking for * @param key the key to look for * @param skipFirst true if the first occurence of key must be ignored * @return new lastIndex value */ public int[] findRandomLastIndexInHtml(String html, String key, boolean skipFirst) { if (html == null) { return null; } int count = 0; int keyIndex = html.indexOf(key); // 1. Count the number of times we find key while (keyIndex != -1) { ++count; keyIndex = html.indexOf(key, keyIndex+key.length()); } if ((count == 0) || (skipFirst && (count <= 1))) { return null; } // 2. Pickup randomly a key keyIndex = -key.length(); count = this._rng.nextInt(count)+1; if ((skipFirst) && (count == 1)) { ++count; // Force to skip the first element } while (count > 0) { keyIndex = html.indexOf(key, keyIndex+key.length()); --count; } keyIndex += key.length(); int lastIndex = minIndex(Integer.MAX_VALUE, html.indexOf('\"', keyIndex)); lastIndex = minIndex(lastIndex, html.indexOf('?', keyIndex)); lastIndex = minIndex(lastIndex, html.indexOf('&', keyIndex)); lastIndex = minIndex(lastIndex, html.indexOf('>', keyIndex)); int[] result = new int[2]; result[0] = keyIndex; result[1] = lastIndex; return result; } /** * Generates a random word. * * @param minLen The minimum length of the word. * @param maxLen The maximum length of the word. * @return The generated word. */ public String generateWord(boolean withPunctuation) { final int maxSize = this._conf.getDictionary().size(); String word = null; int pos = this._rng.nextInt(maxSize); int n = 0; for (String s : this._conf.getDictionary().keySet()) { if (n == pos) { word = s; break; } ++n; } if (word.indexOf(' ') != -1) { // Ignore everything after the first space word = word.substring(0, word.indexOf(' ')); } if (withPunctuation) { switch (this._rng.nextInt(10)) { case 0: word += ", "; break; case 1: word += ". "; break; case 2: word += " ? "; break; case 3: word += " ! "; break; case 4: word += ": "; break; case 5: word += " ; "; break; default: word += " "; break; } } return word; } /** * Internal method that returns the min between ix1 and ix2 if ix2 is not * equal to -1. * * @param ix1 The first index * @param ix2 The second index to compare with ix1 * @return ix2 if (ix2 < ix1 and ix2!=-1) else ix1 */ private static int minIndex(int ix1, int ix2) { if (ix2 == -1) { return ix1; } if (ix1 <= ix2) { return ix1; } return ix2; } }
package se.chalmers.watchme.database; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import se.chalmers.watchme.model.Movie; import se.chalmers.watchme.model.Tag; /** * Adapter to the Content Provider. * * To get a correct update in the database it seems like you need to create * a new DatabaseAdapter before every new method-call to this class. * Probably because it needs a fresh ContentResolver. * * @author lisastenberg * */ public class DatabaseAdapter { private Uri uri_movies = WatchMeContentProvider.CONTENT_URI_MOVIES; private Uri uri_tags = WatchMeContentProvider.CONTENT_URI_TAGS; private Uri uri_has_tag = WatchMeContentProvider.CONTENT_URI_HAS_TAG; private ContentResolver contentResolver; /** * Creates a new adapter. * * @param contentResolver the ContentResolver. */ public DatabaseAdapter(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * The total number of movies. * * @return The number of existing movies */ public int getMovieCount() { return this.getCount(uri_movies); } /** * The total number of tags. * * @return The number of existing tags */ public int getTagCount() { return this.getCount(uri_tags); } /** * Returns the specified Movie. * * @param id The id of the Movie. * @return null if there is no Movie with the specified id. */ public Movie getMovie(long id) { String selection = MoviesTable.COLUMN_MOVIE_ID + " = " + id; Cursor cursor = contentResolver.query(uri_movies, null, selection, null, null); if(cursor.moveToFirst()) { String title = cursor.getString(1); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(cursor.getString(4))); int rating = Integer.parseInt(cursor.getString(2)); String note = cursor.getString(3); Movie movie = new Movie(title, calendar, rating, note); movie.setId(id); movie.setApiID(Integer.parseInt(cursor.getString(5))); return movie; } return null; } /** * Inserts a Movie to the database and set the id of the Movie. * * @param movie Movie to be inserted. * @return the id of the added Movie. */ public long addMovie(Movie movie) { ContentValues values = new ContentValues(); values.put(MoviesTable.COLUMN_TITLE, movie.getTitle()); values.put(MoviesTable.COLUMN_RATING, movie.getRating()); values.put(MoviesTable.COLUMN_NOTE, movie.getNote()); values.put(MoviesTable.COLUMN_DATE, movie.getDate().getTimeInMillis()); values.put(MoviesTable.COLUMN_IMDB_ID, movie.getApiID()); values.put(MoviesTable.COLUMN_POSTER_LARGE, movie.getPosterURL(Movie.PosterSize.MID)); values.put(MoviesTable.COLUMN_POSTER_SMALL, movie.getPosterURL(Movie.PosterSize.THUMB)); Uri uri_movie_id = contentResolver.insert(uri_movies, values); movie.setId(Long.parseLong(uri_movie_id.getLastPathSegment())); return movie.getId(); } /** * Delete a Movie from the database. * * @param movie The movie to be removed. */ public void removeMovie(Movie movie) { String where = MoviesTable.COLUMN_MOVIE_ID + " = " + movie.getId(); contentResolver.delete(uri_movies, where, null); } /** * Return all Movies from the database. * @return all Movies from the database. */ public List<Movie> getAllMovies() { return getAllMovies(null); } /** * Return all Movies from the database in the specified order. * * @param orderBy The attribute to order by. * @return all Movies from the database in the specified order. */ public List<Movie> getAllMovies(String orderBy) { List<Movie> movies = new ArrayList<Movie>(); Cursor cursor = contentResolver.query(uri_movies, null, null, null, orderBy); while(cursor.moveToNext()) { long id = Long.parseLong(cursor.getString(0)); String title = cursor.getString(1); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(Long.parseLong(cursor.getString(4))); int rating = Integer.parseInt(cursor.getString(2)); String note = cursor.getString(3); Movie movie = new Movie(title, calendar, rating, note); movie.setId(id); movie.setApiID(Integer.parseInt(cursor.getString(5))); movies.add(movie); } return movies; } /** * Return a Cursor with all Movies in the Database. * * @return all Movies in the Database. */ public Cursor getAllMoviesCursor() { return contentResolver.query(uri_movies, null, null, null, null); } /** * Return a Cursor with all Movies in the Database in the specified order. * * @param orderBy The attribute to order by. * @return all Movies in the Database in the specified order. */ public Cursor getAllMoviesCursor(String orderBy) { return contentResolver.query(uri_movies, null, null, null, orderBy); } /** * Returns the specified Tag. * * @param id The id of the Tag. * @return null if there is no Tag with the specified id. */ public Tag getTag(long id) { String selection = TagsTable.COLUMN_TAG_ID + " = " + id; Cursor cursor = contentResolver.query(uri_tags, null, selection, null, null); if(cursor.moveToFirst()) { String name = cursor.getString(1); Tag tag = new Tag(name); tag.setId(id); return tag; } return null; } /** * Inserts a Tag to the database. * * @param tag The Tag to be inserted. * @return the id of the added Tag. */ private long addTag(Tag tag) { ContentValues values = new ContentValues(); values.put(TagsTable.COLUMN_NAME, tag.getName()); Uri uri_tag_id = contentResolver.insert(uri_tags, values); tag.setId(Long.parseLong(uri_tag_id.getLastPathSegment())); return tag.getId(); } /** * Deletes a Tag from the database. * * @param tag The Tag to be removed. */ public void removeTag(Tag tag) { String where = TagsTable.COLUMN_TAG_ID + " = " + tag.getId(); contentResolver.delete(uri_tags, where, null); } /** * Return all Tags in the database. * * @return all Tags in the database. */ public List<Tag> getAllTags() { List<Tag> tags = new ArrayList<Tag>(); Cursor cursor = contentResolver.query(uri_tags, null, null, null, null); while(cursor.moveToNext()) { long id = Long.parseLong(cursor.getString(0)); String name = cursor.getString(1); Tag tag = new Tag(name); tag.setId(id); tags.add(tag); } return tags; } /** * Return a Cursor with all Tags in the Database. * * @return all Tags in the Database. */ public Cursor getAllTagsCursor() { return contentResolver.query(uri_tags, null, null, null, null); } /** * Return a Cursor with all Tags in the Database in the specified order. * * @param orderBy The attribute to order by. * @return all Tags in the Database in the specified order. */ public Cursor getAllTagsCursor(String orderBy) { return contentResolver.query(uri_tags, null, null, null, orderBy); } /** * Attach a Tag to a Movie. * * @param movie The Movie. * @param tag The Tag to be attached. */ public void attachTag(Movie movie, Tag tag) { ContentValues values = new ContentValues(); values.put(MoviesTable.COLUMN_MOVIE_ID, movie.getId()); values.put(TagsTable.COLUMN_NAME, tag.getSlug()); contentResolver.insert(uri_has_tag, values); } /** * Attach Tags to a movie. * * @param movie The Movie. * @param tags A list of Tags with Tags to be attached. */ public void attachTags(Movie movie, List<Tag> tags) { for(Tag tag : tags) { attachTag(movie, tag); } } /** * Detach a Tag from a Movie. * * @param movie The Movie. * @param tag The Tag to be detached. */ public void detachTag(Movie movie, Tag tag) { String where = HasTagTable.COLUMN_MOVIE_ID + " = " + movie.getId() + " AND " + HasTagTable.COLUMN_TAG_ID + " = " + tag.getId(); contentResolver.delete(uri_has_tag, where, null); } /** * Return a Cursor containing all Tags attached to a Movie. * Cursor.getString(0) contains the id of the Tag. * Cursor.getString(1) contains the name of the Tag. * * @param movieId The id of the Movie. * @return all Tags attached to the Movie. */ public Cursor getAttachedTags(Long movieId) { String selection = MoviesTable.TABLE_MOVIES + "." + MoviesTable.COLUMN_MOVIE_ID + " = " + movieId; String[] projection = { TagsTable.TABLE_TAGS + "." + TagsTable.COLUMN_TAG_ID, TagsTable.TABLE_TAGS + "." + TagsTable.COLUMN_NAME }; return contentResolver.query(uri_has_tag, projection, selection, null, null); } /** * Return a Cursor containing all Tags attached to a Movie. * Cursor.getString(0) contains the id of the Tag. * Cursor.getString(1) contains the name of the Tag. * * @param movie The Movie. * @return all Tags attached to the Movie. */ public Cursor getAttachedTags(Movie movie) { return getAttachedTags(movie.getId()); } /** * Return a Cursor containing all Movies attached to a Tag. * Cursor.getString(0) contains the id. * Cursor.getString(1) contains the title. * Cursor.getString(2) contains the rating. * Cursor.getString(3) contains the note. * Cursor.getString(4) contains the timeInMillis. * Cursor.getString(5) contains the IMDb-id * Cursor.getString(6) contains the large poster. * Cursor.getString(7) contains the small poster. * * @param tagId The id of the Tag. * @return all Movies attached to the Tag. */ public Cursor getAttachedMovies(long tagId) { String selection = HasTagTable.TABLE_HAS_TAG + "." + HasTagTable.COLUMN_TAG_ID + " = " + tagId; Cursor cursor = contentResolver.query(uri_has_tag, null, selection, null, null); return cursor; } /** * Return a Cursor containing all Movies attached to a Tag. * Cursor.getString(0) contains the id. * Cursor.getString(1) contains the title. * Cursor.getString(2) contains the rating. * Cursor.getString(3) contains the note. * Cursor.getString(4) contains the timeInMillis. * Cursor.getString(5) contains the IMDb-id * Cursor.getString(6) contains the large poster. * Cursor.getString(7) contains the small poster. * * @param tag The tag. * @return all Movies attached to the Tag. */ public Cursor getAttachedMovies(Tag tag) { return getAttachedMovies(tag.getId()); } /** * Get the number of rows for a specified database table. * * @param table The table in the database * @return The total number of rows */ private int getCount(Uri table) { return contentResolver.query(table, null, null, null, null).getCount(); } }
package dyvil.tools.repl.context; import dyvil.collection.List; import dyvil.collection.Map; import dyvil.collection.mutable.ArrayList; import dyvil.collection.mutable.IdentityHashMap; import dyvil.reflect.Modifiers; import dyvil.tools.compiler.DyvilCompiler; import dyvil.tools.compiler.ast.annotation.AnnotationList; import dyvil.tools.compiler.ast.classes.ClassBody; import dyvil.tools.compiler.ast.classes.CodeClass; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.constructor.IConstructor; import dyvil.tools.compiler.ast.constructor.IInitializer; import dyvil.tools.compiler.ast.consumer.IMemberConsumer; import dyvil.tools.compiler.ast.consumer.IValueConsumer; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.context.IDefaultContext; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.field.IDataMember; import dyvil.tools.compiler.ast.field.IField; import dyvil.tools.compiler.ast.field.IProperty; import dyvil.tools.compiler.ast.header.AbstractHeader; import dyvil.tools.compiler.ast.header.ICompilable; import dyvil.tools.compiler.ast.imports.ImportDeclaration; import dyvil.tools.compiler.ast.member.IClassMember; import dyvil.tools.compiler.ast.member.IMember; import dyvil.tools.compiler.ast.method.IMethod; import dyvil.tools.compiler.ast.method.MatchList; import dyvil.tools.compiler.ast.modifiers.BaseModifiers; import dyvil.tools.compiler.ast.modifiers.ModifierList; import dyvil.tools.compiler.ast.modifiers.ModifierSet; import dyvil.tools.compiler.ast.operator.IOperator; import dyvil.tools.compiler.ast.parameter.IArguments; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.alias.ITypeAlias; import dyvil.tools.compiler.ast.type.builtin.Types; import dyvil.tools.compiler.util.Markers; import dyvil.tools.compiler.util.Util; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.marker.Marker; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; import dyvil.tools.repl.DyvilREPL; public class REPLContext extends AbstractHeader implements IDefaultContext, IValueConsumer, IMemberConsumer<REPLVariable> { private static final String CLASS_PACKAGE = "repl_classes"; public static final String CLASS_PREFIX = "Result_"; protected final DyvilREPL repl; // Persistent members private final Map<Name, IField> fields = new IdentityHashMap<>(); private final Map<Name, IProperty> properties = new IdentityHashMap<>(); private final List<IMethod> methods = new ArrayList<>(); private final Map<Name, IClass> classes = new IdentityHashMap<>(); // Updated for every input private int resultIndex; private int classIndex; protected String currentCode; private CodeClass currentClass; // Cleared for every input protected final MarkerList markers = new MarkerList(Markers.INSTANCE); protected final List<ICompilable> innerClassList = new ArrayList<>(); protected final List<IMember> members = new ArrayList<>(); public REPLContext(DyvilREPL repl) { super(Name.fromRaw("REPL")); this.repl = repl; } // Getters public Map<Name, IField> getFields() { return this.fields; } public Map<Name, IProperty> getProperties() { return this.properties; } public List<IMethod> getMethods() { return this.methods; } public Map<Name, IClass> getClasses() { return this.classes; } // Evaluation public void startEvaluation(String code) { final String className = CLASS_PREFIX + this.classIndex++; this.currentClass = new CodeClass(this, Name.fromRaw(className)); this.currentClass.setBody(new ClassBody(this.currentClass)); this.currentCode = code; } public MarkerList getMarkers() { return this.markers; } protected boolean hasErrors() { return this.markers.getErrors() > 0; } public void endEvaluation() { final IContext context = this.getContext(); this.currentClass.resolveTypes(this.markers, context); this.currentClass.resolve(this.markers, context); this.currentClass.checkTypes(this.markers, context); this.currentClass.check(this.markers, context); if (this.markers.getErrors() > 0) { this.printErrors(); this.cleanup(); return; } for (int i = this.getCompilationContext().config.getConstantFolding() - 1; i >= 0; i { this.currentClass.foldConstants(); } this.currentClass.cleanup(this, this.currentClass); final Class<?> theClass = this.compileAndLoad(); for (IMember member : this.members) { this.processMember(member, theClass); } this.printErrors(); this.cleanup(); } private Class<?> compileAndLoad() { final REPLClassLoader classLoader = this.repl.getClassLoader(); final List<Class<?>> classes = new ArrayList<>(this.innerClassList.size() + 1); // Compile all inner class for (ICompilable innerClass : this.innerClassList) { classLoader.register(innerClass); } classLoader.register(this.currentClass); for (ICompilable innerClass : this.innerClassList) { classLoader.initialize(innerClass); } return classLoader.initialize(this.currentClass); } private void processMember(IMember member, Class<?> theClass) { switch (member.getKind()) { case FIELD: if (Types.isVoid(member.getType())) { // Don't register the variable return; } if (member instanceof REPLVariable) { final REPLVariable replVariable = (REPLVariable) member; replVariable.setRuntimeClass(theClass); replVariable.updateValue(this.repl); } this.fields.put(member.getName(), (IField) member); break; case METHOD: this.processMethod((IMethod) member); break; case PROPERTY: this.properties.put(member.getName(), (IProperty) member); break; case CLASS: this.classes.put(member.getName(), (IClass) member); break; } this.repl.getOutput().println(member); } private void processMethod(IMethod method) { int methods = this.methods.size(); for (int i = 0; i < methods; i++) { if (this.methods.get(i).checkOverride(method, null)) { this.methods.set(i, method); return; } } this.methods.add(method); } public void cleanup() { this.innerClassList.clear(); this.markers.clear(); this.members.clear(); } private void printErrors() { if (this.markers.isEmpty()) { return; } boolean colors = this.getCompilationContext().config.useAnsiColors(); StringBuilder buf = new StringBuilder(); this.markers.sort(); for (Marker marker : this.markers) { marker.log(this.currentCode, buf, colors); } this.repl.getOutput().println(buf.toString()); } private void initMember(IClassMember member) { member.setEnclosingClass(this.currentClass); // Ensure public & static final ModifierSet modifiers = member.getModifiers(); if ((modifiers.toFlags() & Modifiers.VISIBILITY_MODIFIERS) == 0) { modifiers.addIntModifier(Modifiers.PUBLIC); } modifiers.addIntModifier(Modifiers.STATIC); } @Override public void setValue(IValue value) { final ModifierList modifierList = new ModifierList(); modifierList.addModifier(BaseModifiers.FINAL); final Name name = Name.fromRaw("res" + this.resultIndex++); final REPLVariable field = new REPLVariable(this, value.getPosition(), name, Types.UNKNOWN, modifierList, null); field.setValue(value); this.initMember(field); this.currentClass.getBody().addDataMember(field); this.members.add(field); } @Override public void addOperator(IOperator operator) { super.addOperator(operator); this.repl.getOutput().println("Defined " + operator); } @Override public void addImport(ImportDeclaration component) { component.resolveTypes(this.markers, this); component.resolve(this.markers, this); if (this.hasErrors()) { return; } super.addImport(component); this.repl.getOutput().println("Imported " + component.getImport()); } @Override public void addTypeAlias(ITypeAlias typeAlias) { typeAlias.resolveTypes(this.markers, this); typeAlias.resolve(this.markers, this); typeAlias.checkTypes(this.markers, this); typeAlias.check(this.markers, this); if (this.hasErrors()) { return; } typeAlias.foldConstants(); typeAlias.cleanup(this, this.currentClass); super.addTypeAlias(typeAlias); this.repl.getOutput().println(typeAlias); } @Override public void addClass(IClass iclass) { this.initMember(iclass); this.currentClass.getBody().addClass(iclass); this.members.add(iclass); } @Override public void addCompilable(ICompilable compilable) { this.innerClassList.add(compilable); } @Override public REPLVariable createDataMember(ICodePosition position, Name name, IType type, ModifierSet modifiers, AnnotationList annotations) { return new REPLVariable(this, position, name, type, modifiers, annotations); } @Override public void addDataMember(REPLVariable field) { this.initMember(field); this.currentClass.getBody().addDataMember(field); this.members.add(field); } @Override public void addProperty(IProperty property) { this.initMember(property); this.currentClass.getBody().addProperty(property); this.members.add(property); } @Override public void addMethod(IMethod method) { this.initMember(method); this.currentClass.getBody().addMethod(method); this.members.add(method); } @Override public void addInitializer(IInitializer initializer) { } @Override public void addConstructor(IConstructor constructor) { } // region IContext overrides @Override public DyvilCompiler getCompilationContext() { return this.repl.getCompiler(); } @Override public IClass resolveClass(Name name) { return this.classes.get(name); } @Override public IDataMember resolveField(Name name) { return this.fields.get(name); } @Override public void getMethodMatches(MatchList<IMethod> list, IValue receiver, Name name, IArguments arguments) { for (IMethod method : this.methods) { method.checkMatch(list, receiver, name, arguments); } if (name == null) { return; } final Name removeEq = Util.removeEq(name); IProperty property = this.properties.get(removeEq); if (property != null) { property.checkMatch(list, receiver, name, arguments); } final IField field = this.fields.get(removeEq); if (field != null) { property = field.getProperty(); if (property != null) { property.checkMatch(list, receiver, name, arguments); } } } @Override public void getImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType) { for (IMethod method : this.methods) { method.checkImplicitMatch(list, value, targetType); } } @Override public IType getReturnType() { return null; } @Override public byte checkException(IType type) { return TRUE; } @Override public IClass getThisClass() { return this.currentClass; } // endregion @Override public Name getName() { return this.currentClass.getName(); } @Override public String getFullName() { return this.currentClass.getFullName(); } @Override public String getFullName(Name subClass) { return CLASS_PACKAGE + '.' + subClass.qualified; } @Override public String getInternalName() { return this.currentClass.getInternalName(); } @Override public String getInternalName(Name subClass) { return CLASS_PACKAGE + '/' + subClass.qualified; } }
package servidor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class ServidorTransmision extends Thread { private Socket conexionClienteTCP; private String videoSolicitado; private BufferedReader entradaDatos; private PrintWriter salidaDatos; private int puertoUDPCliente; private TrasmisionVideo broadcaster; public static final int FRAMESVIDEO1 = 1805; public static final int FRAMESVIDEO2 = 2714; public ServidorTransmision(Socket conexionClienteTCP){ this.conexionClienteTCP = conexionClienteTCP; crearIOStream(); } @Override public void run(){ atender(); } public void atender(){ try { obtenerNombreVideo(); obtenerPuertoUDPCLiente(); crearBroadcaster(); this.broadcaster.transmitir(); } catch (IOException e){ System.err.println(e.toString()); } } private void obtenerNombreVideo()throws IOException{ String solicitud = entradaDatos.readLine(); if(solicitud.contains("GET")){ if (solicitud.contains("video1")){ this.videoSolicitado = "video1"; salidaDatos.println("OK "+FRAMESVIDEO1); } else if (solicitud.contains("video2")){ this.videoSolicitado = "video2"; salidaDatos.println("OK "+FRAMESVIDEO2); } else { salidaDatos.println("ERR"); } } else { salidaDatos.println("ERR"); } } private void obtenerPuertoUDPCLiente() throws IOException{ String mensaje = entradaDatos.readLine(); if (mensaje.contains("PORT")) { this.puertoUDPCliente = Integer.parseInt(mensaje.substring(5)); salidaDatos.println("OK"); } else { salidaDatos.println("ERR"); } } private void crearBroadcaster(){ this.broadcaster = new TrasmisionVideo(puertoUDPCliente,videoSolicitado,conexionClienteTCP.getInetAddress() ,(videoSolicitado.equals("video1")?FRAMESVIDEO1:FRAMESVIDEO2)); } private void crearIOStream(){ try { this.entradaDatos = new BufferedReader(new InputStreamReader(this.conexionClienteTCP.getInputStream())); this.salidaDatos = new PrintWriter(this.conexionClienteTCP.getOutputStream(),true); } catch (IOException e){ //TerminalLogger.TLog("Error al crear buffers."+e.toString(),TerminalLogger.ERR); } } }
package ch.digitalfondue.synckv; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.View; import org.jgroups.protocols.*; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.protocols.pbcast.NAKACK2; import org.jgroups.protocols.pbcast.STABLE; import org.jgroups.stack.Protocol; import org.jgroups.util.Util; import java.nio.charset.StandardCharsets; public class SyncKVTest { public static void main(String[] args) throws Exception { // switched to TCP_NIO2 and MPING // TODO: custom encryption provider for loading the encryption key from memory and not from a keystore Protocol[] prot_stack = { new TCP_NIO2(), new MPING(), new MERGE3(), new FD_SOCK(), new FD_ALL(), new VERIFY_SUSPECT(), new BARRIER(), new NAKACK2(), new UNICAST3(), new STABLE(), new GMS(), new UFC(), new MFC(), new FRAG2()}; JChannel channel = new JChannel(prot_stack).name("SyncKV"); channel.setReceiver(new ReceiverAdapter() { public void viewAccepted(View new_view) { System.out.println("view: " + new_view); } public void receive(Message msg) { System.out.println("<< " + msg.getObject() + " [" + msg.getSrc() + "]"); } }); channel.connect("SyncKV"); SyncKV syncKV = new SyncKV(null, null, channel); SyncKVTable table = syncKV.getTable("test"); table.put("my_key", "my value 1".getBytes(StandardCharsets.UTF_8)); byte[] res1 = table.get("my_key"); System.err.println("res1 is " + new String(res1, StandardCharsets.UTF_8)); table.put("my_key", "my value 2".getBytes(StandardCharsets.UTF_8)); byte[] res2 = table.get("my_key"); System.err.println("res2 is " + new String(res2, StandardCharsets.UTF_8)); for (; ; ) { String line = Util.readStringFromStdin(": "); channel.send(null, line); } } }
package com.github.enanomapper; import java.io.InputStream; import java.io.StringReader; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; public class SlimmerTest { @Test public void testLoading() throws OWLOntologyCreationException { InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertNotSame(0, ontology.getAxiomCount()); } @Test public void testParsingUp() throws Exception { String test = "+U:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(3, ontology.getClassesInSignature().size()); } @Test public void testParsingSingle() throws Exception { String test = "+:http://www.ifomis.org/bfo/1.1/snap#DependentContinuant"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(1, ontology.getClassesInSignature().size()); } @Test public void testParsingDown() throws Exception { String test = "+D:http://www.ifomis.org/bfo/1.1/snap#MaterialEntity"; Configuration conf = new Configuration(); conf.read(new StringReader(test)); Set<Instruction> irisToSave = conf.getTreePartsToSave(); Assert.assertEquals(1, conf.getTreePartsToSave().size()); InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bfo-1.1.owl"); Slimmer slimmer = new Slimmer(stream); slimmer.removeAllExcept(irisToSave); OWLOntology ontology = slimmer.getOntology(); Assert.assertNotNull(ontology); Assert.assertEquals(4, ontology.getClassesInSignature().size()); } }
package com.jts.fortress.rbac; import com.jts.fortress.arbac.OrgUnitTestData; import com.jts.fortress.pwpolicy.MyAnnotation; import com.jts.fortress.util.AlphabeticalOrder; import com.jts.fortress.util.attr.VUtil; import com.jts.fortress.util.time.Constraint; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; /** * Description of the Class * M * * @author Shawn McKinney * @created January 28, 2010 */ public class UserTestData extends TestCase { public final static String[][] USERS_TU0 = { { "oamTestAdminUser", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnameone", /* CN_COL */ "lnameone", /* SN_COL */ "oamTestAdminUser@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV0", /* ORG_COL */ "100", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; /** * Test Case TU1: */ final static String[][] USERS_TU1 = { { "oamUser1", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnameone", /* CN_COL */ "lnameone", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser2", /* USERID_COL */ "password2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnametwo", /* CN_COL */ "lnametwo", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser3", /* USERID_COL */ "password3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnamethree", /* CN_COL */ "lnametree", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser4", /* USERID_COL */ "password4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnamefour", /* CN_COL */ "lnamefour", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnamefive", /* CN_COL */ "lnamefive", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnamesix", /* CN_COL */ "lnamesix", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser7", /* USERID_COL */ "password7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnameseven", /* CN_COL */ "lnameseven", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnameeight", /* CN_COL */ "lnameeight", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnamenine", /* CN_COL */ "lnamenine", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU1", /* DESC_COL */ "fnameten", /* CN_COL */ "lnameten", /* SN_COL */ "oamUser1@jts.com", /* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20090101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20500101", /* BLOCKDATE_COL */ "20500115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "10", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; /** * Test Case TU1 updated: */ public final static String[][] USERS_TU1_UPD = { { "oamUser1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser1UPD@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser2UPD@jts.com",/* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser3UPD@jts.com",/* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser4UPD@jts.com",/* EMAIL_COL */ "501-111-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser5", /* USERID_COL */ "passw0rd5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser5UPD@jts.com",/* EMAIL_COL */ "501-111-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser6", /* USERID_COL */ "passw0rd6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser6UPD@jts.com",/* EMAIL_COL */ "501-111-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser7", /* USERID_COL */ "passw0rd7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser7UPD@jts.com",/* EMAIL_COL */ "501-111-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser8", /* USERID_COL */ "passw0rd8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser8UPD@jts.com",/* EMAIL_COL */ "501-111-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser9", /* USERID_COL */ "passw0rd9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser9UPD@jts.com",/* EMAIL_COL */ "501-111-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamUser10", /* USERID_COL */ "passw0rd10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "oamUser10UPD@jts.com",/* EMAIL_COL */ "501-111-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; /** * Test Case TU2: */ final static String[][] USERS_TU2 = { { "oamTU2User1", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest2UR1@jts.com", /* EMAIL_COL */ "501-222-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User2", /* USERID_COL */ "password2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest2UR2@jts.com", /* EMAIL_COL */ "501-222-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User3", /* USERID_COL */ "password3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest2UR3@jts.com", /* EMAIL_COL */ "501-222-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User4", /* USERID_COL */ "password4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest2UR4@jts.com", /* EMAIL_COL */ "501-222-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest2UR5@jts.com", /* EMAIL_COL */ "501-222-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest2UR6@jts.com", /* EMAIL_COL */ "501-222-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User7", /* USERID_COL */ "password7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest2UR7@jts.com", /* EMAIL_COL */ "501-222-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest2UR8@jts.com", /* EMAIL_COL */ "501-222-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest2UR9@jts.com", /* EMAIL_COL */ "501-222-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest2UR10@jts.com",/* EMAIL_COL */ "501-222-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; /** * Test Case TU2: */ final static String[][] USERS_TU2_RST = { { "oamTU2User1", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest2UR1@jts.com", /* EMAIL_COL */ "501-222-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User2", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest2UR2@jts.com", /* EMAIL_COL */ "501-222-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User3", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest2UR3@jts.com", /* EMAIL_COL */ "501-222-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User4", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest2UR4@jts.com", /* EMAIL_COL */ "501-222-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User5", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest2UR5@jts.com", /* EMAIL_COL */ "501-222-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User6", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest2UR6@jts.com", /* EMAIL_COL */ "501-222-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User7", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest2UR7@jts.com", /* EMAIL_COL */ "501-222-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User8", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest2UR8@jts.com", /* EMAIL_COL */ "501-222-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User9", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest2UR9@jts.com", /* EMAIL_COL */ "501-222-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User10", /* USERID_COL */ "newpasswd", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest2UR10@jts.com",/* EMAIL_COL */ "501-222-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; public final static String[][] USERS_TU2_CHG = { { "oamTU2User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest2UR1@jts.com", /* EMAIL_COL */ "501-222-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest2UR2@jts.com", /* EMAIL_COL */ "501-222-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest2UR3@jts.com", /* EMAIL_COL */ "501-222-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest2UR4@jts.com", /* EMAIL_COL */ "501-222-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User5", /* USERID_COL */ "passw0rd5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest2UR5@jts.com", /* EMAIL_COL */ "501-222-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User6", /* USERID_COL */ "passw0rd6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest2UR6@jts.com", /* EMAIL_COL */ "501-222-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User7", /* USERID_COL */ "passw0rd7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest2UR7@jts.com", /* EMAIL_COL */ "501-222-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User8", /* USERID_COL */ "passw0rd8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest2UR8@jts.com", /* EMAIL_COL */ "501-222-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User9", /* USERID_COL */ "passw0rd9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest2UR9@jts.com", /* EMAIL_COL */ "501-222-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU2User10", /* USERID_COL */ "passw0rd1-", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU2", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest2UR10@jts.com",/* EMAIL_COL */ "501-222-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; // Test Case TU3: public final static String[][] USERS_TU3 = { { "oamTU3User1", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest3UR1@jts.com", /* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User2", /* USERID_COL */ "password2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest3UR2@jts.com", /* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User3", /* USERID_COL */ "password3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest3UR3@jts.com", /* EMAIL_COL */ "501-555-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User4", /* USERID_COL */ "password4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest3UR4@jts.com", /* EMAIL_COL */ "501-555-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest3UR5@jts.com", /* EMAIL_COL */ "501-555-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest3UR6@jts.com", /* EMAIL_COL */ "501-555-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User7", /* USERID_COL */ "password7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest3UR7@jts.com", /* EMAIL_COL */ "501-555-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest3UR8@jts.com", /* EMAIL_COL */ "501-555-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest3UR9@jts.com", /* EMAIL_COL */ "501-555-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU3User10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU3", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest3UR10@jts.com",/* EMAIL_COL */ "501-555-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; // Test Case TU4: public final static String[][] USERS_TU4 = { { "oamTU4User1", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest4UR1@jts.com", /* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User2", /* USERID_COL */ "password2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest4UR2@jts.com", /* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User3", /* USERID_COL */ "password3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest4UR3@jts.com", /* EMAIL_COL */ "501-555-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User4", /* USERID_COL */ "password4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest4UR4@jts.com", /* EMAIL_COL */ "501-555-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest4UR5@jts.com", /* EMAIL_COL */ "501-555-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest4UR6@jts.com", /* EMAIL_COL */ "501-555-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User7", /* USERID_COL */ "password7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest4UR7@jts.com", /* EMAIL_COL */ "501-555-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest4UR8@jts.com", /* EMAIL_COL */ "501-555-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest4UR9@jts.com", /* EMAIL_COL */ "501-555-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU4User10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU4", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest4UR10@jts.com",/* EMAIL_COL */ "501-555-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; // Test Case TU5: @MyAnnotation(name = "USERS_TU5", value = "USR TU5") final public static String[][] USERS_TU5 = { { "oamTU5User1", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest5UR1@jts.com", /* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User2", /* USERID_COL */ "password2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest5UR2@jts.com", /* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User3", /* USERID_COL */ "password3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest5UR3@jts.com", /* EMAIL_COL */ "501-555-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User4", /* USERID_COL */ "password4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest5UR4@jts.com", /* EMAIL_COL */ "501-555-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest5UR5@jts.com", /* EMAIL_COL */ "501-555-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest5UR6@jts.com", /* EMAIL_COL */ "501-555-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User7", /* USERID_COL */ "password7minlength", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest5UR7@jts.com", /* EMAIL_COL */ "501-555-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest5UR8@jts.com", /* EMAIL_COL */ "501-555-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest5UR9@jts.com", /* EMAIL_COL */ "501-555-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest5UR10@jts.com",/* EMAIL_COL */ "501-555-1010", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User11", /* USERID_COL */ "password11", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userEleven", /* CN_COL */ "lastEleven", /* SN_COL */ "mimsTest5UR11@jts.com",/* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User12", /* USERID_COL */ "password12", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwelve", /* CN_COL */ "lastTwelve", /* SN_COL */ "mimsTest5UR12@jts.com",/* EMAIL_COL */ "501-555-1212", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User13", /* USERID_COL */ "password13", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userThirteen", /* CN_COL */ "lastThirteen", /* SN_COL */ "mimsTest5UR13@jts.com",/* EMAIL_COL */ "501-555-1313", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User14", /* USERID_COL */ "password14", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userFourteen", /* CN_COL */ "lastFourteen", /* SN_COL */ "mimsTest5UR14@jts.com",/* EMAIL_COL */ "501-555-1414", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User15", /* USERID_COL */ "password15", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userFifteen", /* CN_COL */ "lastFifteen", /* SN_COL */ "mimsTest5UR15@jts.com",/* EMAIL_COL */ "501-555-1515", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User16", /* USERID_COL */ "password16", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userSixteen", /* CN_COL */ "lastSixteen", /* SN_COL */ "mimsTest5UR16@jts.com",/* EMAIL_COL */ "501-555-1616", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User17", /* USERID_COL */ "password17", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userSeventeen", /* CN_COL */ "lastSeventeen", /* SN_COL */ "mimsTest5UR17@jts.com",/* EMAIL_COL */ "501-555-1717", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User18", /* USERID_COL */ "password18", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userEighteen", /* CN_COL */ "lastEighteen", /* SN_COL */ "mimsTest5UR18@jts.com",/* EMAIL_COL */ "501-555-1818", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User19", /* USERID_COL */ "password19", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userNineteen", /* CN_COL */ "lastNineteen", /* SN_COL */ "mimsTest5UR19@jts.com",/* EMAIL_COL */ "501-555-1919", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User20", /* USERID_COL */ "password20", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwenty", /* CN_COL */ "lastTwenty", /* SN_COL */ "mimsTest5UR20@jts.com",/* EMAIL_COL */ "501-555-2020", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User21", /* USERID_COL */ "password21", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwentyone", /* CN_COL */ "lastTwentyone", /* SN_COL */ "mimsTest5UR21@jts.com",/* EMAIL_COL */ "501-555-2121", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User22", /* USERID_COL */ "password22", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwentytwo", /* CN_COL */ "lastTwentytwo", /* SN_COL */ "mimsTest5UR22@jts.com",/* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User23", /* USERID_COL */ "password23", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwentythree", /* CN_COL */ "lastTwentythree", /* SN_COL */ "mimsTest5UR23@jts.com",/* EMAIL_COL */ "501-555-2323", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User24", /* USERID_COL */ "password24", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwentyfour", /* CN_COL */ "lastTwentyfour", /* SN_COL */ "mimsTest5UR24@jts.com",/* EMAIL_COL */ "501-555-2424", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User25", /* USERID_COL */ "password25", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwentyfive", /* CN_COL */ "lastTwentyfive", /* SN_COL */ "mimsTest5UR25@jts.com",/* EMAIL_COL */ "501-555-2525", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User26", /* USERID_COL */ "password26", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwentysix", /* CN_COL */ "lastTwentysix", /* SN_COL */ "mimsTest5UR26@jts.com",/* EMAIL_COL */ "501-555-2626", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU5: @MyAnnotation(name = "USERS_TU5_UPD", value = "USR TU5_UPD") final public static String[][] USERS_TU5_UPD = { { "oamTU5User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest5UR1@jts.com", /* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest5UR2@jts.com", /* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest5UR3@jts.com", /* EMAIL_COL */ "501-555-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest5UR4@jts.com", /* EMAIL_COL */ "501-555-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest5UR5@jts.com", /* EMAIL_COL */ "501-555-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest5UR6@jts.com", /* EMAIL_COL */ "501-555-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User7", /* USERID_COL */ "password7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest5UR7@jts.com", /* EMAIL_COL */ "501-555-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest5UR8@jts.com", /* EMAIL_COL */ "501-555-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest5UR9@jts.com", /* EMAIL_COL */ "501-555-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU5User10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU5", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest5UR10@jts.com",/* EMAIL_COL */ "501-555-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; // Test Case TU6, these are system users setup in Fortress properties to disallow deletion: @MyAnnotation(name = "USERS_TU6_SYS", value = "USR TU6_SYS") final public static String[][] USERS_TU6 = { { "oamTU6User1", /* USERID_COL */ "password1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU6", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest6UR1@jts.com", /* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU6User2", /* USERID_COL */ "password2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU6", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest6UR2@jts.com", /* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU6User3", /* USERID_COL */ "password3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU6", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest6UR3@jts.com", /* EMAIL_COL */ "501-555-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU6User4", /* USERID_COL */ "password4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU6", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest6UR4@jts.com", /* EMAIL_COL */ "501-555-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU6User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU6", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest6UR5@jts.com", /* EMAIL_COL */ "501-555-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU7: @MyAnnotation(name = "USERS_TU7_HIER", value = "USR TU7_HIER") final public static String[][] USERS_TU7_HIER = { { "oamTU7User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userOne", /* CN_COL */ "lastOne", /* SN_COL */ "mimsTest7UR1@jts.com", /* EMAIL_COL */ "501-555-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userTwo", /* CN_COL */ "lastTwo", /* SN_COL */ "mimsTest7UR2@jts.com", /* EMAIL_COL */ "501-555-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV2", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userThree", /* CN_COL */ "lastThree", /* SN_COL */ "mimsTest7UR3@jts.com", /* EMAIL_COL */ "501-555-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV3", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userFour", /* CN_COL */ "lastFour", /* SN_COL */ "mimsTest7UR4@jts.com", /* EMAIL_COL */ "501-555-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV4", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User5", /* USERID_COL */ "password5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userFive", /* CN_COL */ "lastFive", /* SN_COL */ "mimsTest7UR5@jts.com", /* EMAIL_COL */ "501-555-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV5", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User6", /* USERID_COL */ "password6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userSix", /* CN_COL */ "lastSix", /* SN_COL */ "mimsTest7UR6@jts.com", /* EMAIL_COL */ "501-555-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV6", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User7", /* USERID_COL */ "password7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userSeven", /* CN_COL */ "lastSeven", /* SN_COL */ "mimsTest7UR7@jts.com", /* EMAIL_COL */ "501-555-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV7", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User8", /* USERID_COL */ "password8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userEight", /* CN_COL */ "lastEight", /* SN_COL */ "mimsTest7UR8@jts.com", /* EMAIL_COL */ "501-555-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV8", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User9", /* USERID_COL */ "password9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userNine", /* CN_COL */ "lastNine", /* SN_COL */ "mimsTest7UR9@jts.com", /* EMAIL_COL */ "501-555-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV9", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU7User10", /* USERID_COL */ "password10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU7", /* DESC_COL */ "userTen", /* CN_COL */ "lastTen", /* SN_COL */ "mimsTest7UR10@jts.com",/* EMAIL_COL */ "501-555-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20100101", /* BDATE_COL */ "21000101", /* EDATE_COL */ "none", /* BLOCKDATE_COL */ "none", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV10", /* ORG_COL */ "30", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; // Test Case TU8: @MyAnnotation(name = "USERS_TU8_SSD", value = "USR TU8_SSD") final static String[][] USERS_TU8_SSD = { { "oamTU8User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU8", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU8@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU8User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU8", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU8@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU8User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU8", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU8@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU8User4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU8", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU4TU8@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU8: @MyAnnotation(name = "USERS_TU9_SSD_HIER", value = "USR TU9_SSD_HIER") final static String[][] USERS_TU9_SSD_HIER = { { "oamTU9User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU9", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU9@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU9User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU9", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU9@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU9User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU9", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU8@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU10: @MyAnnotation(name = "USERS_TU10_SSD_HIER", value = "USR TU10_SSD_HIER") final static String[][] USERS_TU10_SSD_HIER = { { "oamTU10User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU10", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU10@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU10User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU10", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU10@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU10User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU10", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU10@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU11: @MyAnnotation(name = "USERS_TU11_SSD_HIER", value = "USR TU11_SSD_HIER") final static String[][] USERS_TU11_SSD_HIER = { { "oamTU11User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU11", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU11@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU11User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU11", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU11@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU11User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU11", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU11@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU12: @MyAnnotation(name = "USERS_TU12_DSD", value = "USR TU12_DSD") final static String[][] USERS_TU12_DSD = { { "oamTU12User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU12", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU12@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU12User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU12", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU12@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU12User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU12", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU12@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU12User4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU12", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU4TU12@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU13: @MyAnnotation(name = "USERS_TU13_DSD_HIER", value = "USR TU13_DSD_HIER") final static String[][] USERS_TU13_DSD_HIER = { { "oamTU13User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU13", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU13@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU13User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU13", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU13@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU13User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU13", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU13@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU14: @MyAnnotation(name = "USERS_TU14_DSD_HIER", value = "USR TU14_DSD_HIER") final static String[][] USERS_TU14_DSD_HIER = { { "oamTU14User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU14", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU14@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU14User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU14", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU14@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU14User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU14", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU14@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU15: @MyAnnotation(name = "USERS_TU15_DSD_HIER", value = "USR TU15_DSD_HIER") final static String[][] USERS_TU15_DSD_HIER = { { "oamTU15User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU15", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU15@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU15User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU15", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU15@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU15User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU15", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU15@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU16: @MyAnnotation(name = "USERS_TU16_ARBAC", value = "USR TU16_ARBAC") public final static String[][] USERS_TU16_ARBAC = { { "oamTU16User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU16@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU16@jts.com", /* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU16@jts.com", /* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU4TU16@jts.com", /* EMAIL_COL */ "501-111-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User5", /* USERID_COL */ "passw0rd5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU5TU16@jts.com", /* EMAIL_COL */ "501-111-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User6", /* USERID_COL */ "passw0rd6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU6TU16@jts.com", /* EMAIL_COL */ "501-111-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User7", /* USERID_COL */ "passw0rd7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU7TU16@jts.com", /* EMAIL_COL */ "501-111-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User8", /* USERID_COL */ "passw0rd8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU8TU16@jts.com", /* EMAIL_COL */ "501-111-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User9", /* USERID_COL */ "passw0rd9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU9TU16@jts.com", /* EMAIL_COL */ "501-111-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16User10", /* USERID_COL */ "passw0rd10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU10TU16@jts.com",/* EMAIL_COL */ "501-111-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU16B: @MyAnnotation(name = "USERS_TU16B_ARBAC", value = "USR TU16B_ARBAC") public final static String[][] USERS_TU16B_ARBAC = { { "oamTU16BUser1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU16B@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU2TU16B@jts.com",/* EMAIL_COL */ "501-111-2222", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg2", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU3TU16B@jts.com",/* EMAIL_COL */ "501-111-3333", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg3", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU4TU16B@jts.com",/* EMAIL_COL */ "501-111-4444", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg4", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser5", /* USERID_COL */ "passw0rd5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU5TU16B@jts.com",/* EMAIL_COL */ "501-111-5555", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg5", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser6", /* USERID_COL */ "passw0rd6", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU6TU16B@jts.com",/* EMAIL_COL */ "501-111-6666", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg6", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser7", /* USERID_COL */ "passw0rd7", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU7TU16B@jts.com",/* EMAIL_COL */ "501-111-7777", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg7", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser8", /* USERID_COL */ "passw0rd8", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU8TU16B@jts.com",/* EMAIL_COL */ "501-111-8888", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg8", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser9", /* USERID_COL */ "passw0rd9", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU9TU16B@jts.com",/* EMAIL_COL */ "501-111-9999", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg9", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU16BUser10", /* USERID_COL */ "passw0rd10", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU16B", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU10TU16B@jts.com",/* EMAIL_COL */ "501-111-0000", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "oamT1UOrg10", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU17A: @MyAnnotation(name = "USERS_TU17A_ARBAC", value = "USR TU17A_ARBAC") public final static String[][] USERS_TU17A_ARBAC = { { "oamTU17AUser1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17A", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17A@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17AUser2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17A", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17A@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17AUser3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17A", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17A@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17AUser4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17A", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17A@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17AUser5", /* USERID_COL */ "passw0rd5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17A", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17A@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU17U: @MyAnnotation(name = "USERS_TU17U_ARBAC", value = "USR TU17U_ARBAC") public final static String[][] USERS_TU17U_ARBAC = { { "oamTU17UUser1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17U", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17U@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ OrgUnitTestData.getName(OrgUnitTestData.ORGS_USR_TO5[0]), "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17UUser2", /* USERID_COL */ "passw0rd2", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17U", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17U@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ OrgUnitTestData.getName(OrgUnitTestData.ORGS_USR_TO5[1]), "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17UUser3", /* USERID_COL */ "passw0rd3", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17U", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17U@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ OrgUnitTestData.getName(OrgUnitTestData.ORGS_USR_TO5[2]), "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17UUser4", /* USERID_COL */ "passw0rd4", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17U", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17U@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ OrgUnitTestData.getName(OrgUnitTestData.ORGS_USR_TO5[3]), "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU17UUser5", /* USERID_COL */ "passw0rd5", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU17U", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU1TU17U@jts.com",/* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ OrgUnitTestData.getName(OrgUnitTestData.ORGS_USR_TO5[4]), "15", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU18U: @MyAnnotation(name = "USERS_TU18U_TR6_DESC", value = "USR TU18U TR6 DESC") public final static String[][] USERS_TU18U_TR6_DESC = { { "oamTU18User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR1TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6A1", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User2", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR2TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User3", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR3TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User4", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR4TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6C1B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B1A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User5", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR5TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6C2B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B1A1,oamT6B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User6", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR6TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6C3B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B2A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User7", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR7TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6C4B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B2A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User8", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR8TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D1C1B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B1A1,oamT6C1B1A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User9", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR9TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D2C1B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B1A1,oamT6B2A1,oamT6C1B1A1,oamT6C2B1A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User10", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR10TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D3C2B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B1A1,oamT6B2A1,oamT6C2B1A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User11", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR11TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D4C2B1A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B1A1,oamT6B2A1,oamT6C2B1A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User12", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR12TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D5C3B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B2A1,oamT6C3B2A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User13", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR13TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D6C3B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B2A1,oamT6C3B2A1,oamT6C4B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User14", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR14TU18U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D7C4B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B2A1,oamT6C4B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU18User15", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU18U TR6_DESC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU15TU18U@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT6D8C4B2A1", /* ASSGND_ROLES_COL */ "oamT6A1,oamT6B2A1,oamT6C4B2A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU18U: @MyAnnotation(name = "USERS_TU19U_TR7_ASC", value = "USR TU19U TR7 ASC") public final static String[][] USERS_TU19U_TR7_ASC = { { "oamTU19User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR1TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7A1", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User2", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR2TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User3", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR3TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User4", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR4TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7C1B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B1A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User5", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR5TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7C2B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B1A1,oamT7B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User6", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR6TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7C3B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B2A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User7", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR7TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7C4B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B2A1", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User8", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR8TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D1C1B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B1A1,oamT7C1B1A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User9", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR9TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D2C1B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B1A1,oamT7B2A1,oamT7C1B1A1,oamT7C2B1A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User10", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR10TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D3C2B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B1A1,oamT7B2A1,oamT7C2B1A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User11", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR11TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D4C2B1A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B1A1,oamT7B2A1,oamT7C2B1A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User12", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR12TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D5C3B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B2A1,oamT7C3B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User13", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR13TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D6C3B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B2A1,oamT7C3B2A1,oamT7C4B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User14", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR14TU19U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D7C4B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B2A1,oamT7C4B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU19User15", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU19U TR7_ASC", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "mimsU15TU19U@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "oamT7D8C4B2A1", /* ASSGND_ROLES_COL */ "oamT7A1,oamT7B2A1,oamT7C4B2A1",/* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; // Test Case TU20U: @MyAnnotation(name = "USERS_TU20U_TR5B", value = "USR TU20U TR5B HIER") public final static String[][] USERS_TU20U_TR5B = { { "oamTU20User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR1TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "" , /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User2", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR2TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User3", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR3TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User4", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR4TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User5", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR5TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User6", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR6TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User7", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR7TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User8", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR8TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User9", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR9TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Maumelle,AR,72113,9 Vantage Point,2 floor,MBR", /* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, { "oamTU20User10", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU20U TR5_HIER", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "USR10TU20U@jtstools.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "0", /* TIMEOUT_COL */ "", /* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ }, }; // Test Case TU12: @MyAnnotation(name = "USERS_TU21_DSD_BRUNO", value = "USR TU21_DSD_BRUNO") final static String[][] USERS_TU21_DSD_BRUNO = { { "oamTU21User1", /* USERID_COL */ "passw0rd1", /* PASSWORD_COL */ "Test1", /* PW POLICY ATTR */ "Test Case TU21", /* DESC_COL */ "fnameoneupd", /* CN_COL */ "lnameoneupd", /* SN_COL */ "jtsU1TU21@jts.com", /* EMAIL_COL */ "501-111-1111", /* PHONE_COL */ "0000", /* BTIME_COL */ "0000", /* ETIME_COL */ "20091001", /* BDATE_COL */ "21000101", /* EDATE_COL */ "20300101", /* BLOCKDATE_COL */ "20300115", /* ELOCKDATE_COL */ "1234567", /* DAYMASK_COL */ "DEV1", /* ORG_COL */ "15", /* TIMEOUT_COL */ "oamT17DSD1,oamT17DSD3",/* ASSGND_ROLES_COL */ "", /* AUTHZ_ROLES_COL */ "Twentynine Palms,CA,92252,Hiway 62",/* ADDRESS_COL */ "888-888-8888,777-777-7777",/* PHONES_COL */ "555-555-5555,444-444-4444",/* MOBILES_COL */ } }; /** * The Fortress test data for junit uses 2-dimensional arrays. */ private final static int USERID_COL = 0; private final static int PASSWORD_COL = 1; private final static int PW_POLICY_COL = 2; private final static int DESC_COL = 3; private final static int CN_COL = 4; private final static int SN_COL = 5; private final static int EMAIL_COL = 6; private final static int PHONE_COL = 7; private final static int BTIME_COL = 8; private final static int ETIME_COL = 9; private final static int BDATE_COL = 10; private final static int EDATE_COL = 11; private final static int BLOCKDATE_COL = 12; private final static int ELOCKDATE_COL = 13; private final static int DAYMASK_COL = 14; private final static int ORG_COL = 15; private final static int TIMEOUT_COL = 16; private final static int ASSGND_ROLES_COL = 17; private final static int AUTHZ_ROLES_COL = 18; private final static int ADDRESS_COL = 19; private final static int PHONES_COL = 20; private final static int MOBILES_COL = 21; /** * @param user * @param usr */ public static void assertEquals(User user, String[] usr) { assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user userId", getUserId(usr).toUpperCase(), user.getUserId().toUpperCase()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user desc", getDescription(usr), user.getDescription()); //assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user pw policy", getPwPolicy(usr), user.getPwPolicy()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user name", (getFName(usr) + " " + getLName(usr)), user.getName()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user cn", (getFName(usr) + " " + getLName(usr)), user.getCn()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user sn", getLName(usr), user.getSn()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user ou", getOu(usr), user.getOu()); assertTrue(UserTestData.class.getName() + ".assertEquals failed compare user address", getAddress(usr).equals(user.getAddress())); //assertAddress(usr, user.getAddress()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user phones", getPhones(usr), user.getPhones()); assertEquals(UserTestData.class.getName() + ".assertEquals failed compare user mobiles", getMobiles(usr), user.getMobiles()); Constraint validConstraint = getUserConstraint(usr); TestUtils.assertTemporal(UserTestData.class.getName() + ".assertEquals", validConstraint, user); } public static void assertAddress(String[] usr, Address address) { Address expectedAddress = getAddress(usr); assertTrue(UserTestData.class.getName() + ".assertEquals failed compare user address", expectedAddress.equals(address)); } /** * @param usr * @return */ public static String getUserId(String[] usr) { return usr[USERID_COL]; } /** * @param usr * @return */ public static char[] getPassword(String[] usr) { return usr[PASSWORD_COL].toCharArray(); } /** * @param usr * @return */ public static String getPwPolicy(String[] usr) { return usr[PW_POLICY_COL]; } /** * @param usr * @return */ public static String getDescription(String[] usr) { return usr[DESC_COL]; } /** * @param usr * @return */ public static String getOu(String[] usr) { return usr[ORG_COL]; } /** * @param usr * @return */ public static String getFName(String[] usr) { return usr[CN_COL]; } /** * @param usr * @return */ public static String getLName(String[] usr) { return usr[SN_COL]; } /** * @param usr * @return */ public static String getBeginTime(String[] usr) { return usr[BTIME_COL]; } /** * @param usr * @return */ public static String getEndTime(String[] usr) { return usr[ETIME_COL]; } /** * @param usr * @return */ public static String getBeginDate(String[] usr) { return usr[BDATE_COL]; } /** * @param usr * @return */ public static String getEndDate(String[] usr) { return usr[EDATE_COL]; } /** * @param usr * @return */ public static String getBeginLockDate(String[] usr) { return usr[BLOCKDATE_COL]; } /** * @param usr * @return */ public static String getEndLockDate(String[] usr) { return usr[ELOCKDATE_COL]; } /** * @param usr * @return */ public static String getDayMask(String[] usr) { return usr[DAYMASK_COL]; } /** * @param usr * @return */ public static int getTimeOut(String[] usr) { return Integer.parseInt(usr[TIMEOUT_COL]); } /** * @param usr * @return */ public static User getUser(String[] usr) { User user = (User) getUserConstraint(usr); user.setUserId(getUserId(usr)); user.setPassword(getPassword(usr)); user.setPwPolicy(getPwPolicy(usr)); user.setDescription(getDescription(usr)); user.setName(getFName(usr) + " " + getLName(usr)); user.setCn(user.getName()); user.setSn(getLName(usr)); user.setOu(getOu(usr)); user.setAddress(getAddress(usr)); user.setPhones(getPhones(usr)); user.setMobiles(getMobiles(usr)); return user; } /** * @param usr * @return */ private static com.jts.fortress.util.time.Constraint getUserConstraint(String[] usr) { User user = new User(); user.setBeginDate(getBeginDate(usr)); user.setEndDate(getEndDate(usr)); user.setBeginLockDate(getBeginLockDate(usr)); user.setEndLockDate(getEndLockDate(usr)); user.setBeginTime(getBeginTime(usr)); user.setEndTime(getEndTime(usr)); user.setDayMask(getDayMask(usr)); user.setTimeout(getTimeOut(usr)); return user; } /** * @param szInput * @return */ public static Set<String> getAssignedRoles(String[] szInput) { return getSets(szInput, ASSGND_ROLES_COL); } /** * @param szInput * @return */ public static Set<String> getAuthorizedRoles(String[] szInput) { return getSets(szInput, AUTHZ_ROLES_COL); } /** * @param szInput * @return */ public static List<String> getPhones(String[] szInput) { return getList(szInput, PHONES_COL); } /** * @param szInput * @return */ public static List<String> getMobiles(String[] szInput) { return getList(szInput, MOBILES_COL); } /** * @param szInput * @return */ public static Address getAddress(String[] szInput) { return getAddress(szInput, ADDRESS_COL); } /** * @param szInput * @param col * @return */ private static Address getAddress(String[] szInput, int col) { Address address = null; try { if (VUtil.isNotNullOrEmpty(szInput[col])) { address = new Address(); StringTokenizer charSetTkn = new StringTokenizer(szInput[col], ","); if (charSetTkn.countTokens() > 0) { int count = 0; while (charSetTkn.hasMoreTokens()) { String value = charSetTkn.nextToken(); switch(count++) { case 0: address.setCity(value); break; case 1: address.setState(value); break; case 2: address.setPostalCode(value); break; default: address.setAddress(value); break; } } } } } catch (java.lang.ArrayIndexOutOfBoundsException ae) { // ignore } return address; } /** * @param szInput * @param col * @return */ private static Set<String> getSets(String[] szInput, int col) { Set<String> vSets = new TreeSet<String>(new AlphabeticalOrder()); try { if (VUtil.isNotNullOrEmpty(szInput[col])) { StringTokenizer charSetTkn = new StringTokenizer(szInput[col], ","); if (charSetTkn.countTokens() > 0) { while (charSetTkn.hasMoreTokens()) { String value = charSetTkn.nextToken(); vSets.add(value); } } } } catch (java.lang.ArrayIndexOutOfBoundsException ae) { // ignore } return vSets; } /** * @param szInput * @param col * @return */ private static List<String> getList(String[] szInput, int col) { List<String> vList = new ArrayList<String>(); try { if (VUtil.isNotNullOrEmpty(szInput[col])) { StringTokenizer charSetTkn = new StringTokenizer(szInput[col], ","); if (charSetTkn.countTokens() > 0) { while (charSetTkn.hasMoreTokens()) { String value = charSetTkn.nextToken(); vList.add(value); } } } } catch (java.lang.ArrayIndexOutOfBoundsException ae) { // ignore } return vList; } /** * Not currently used but will be in future for performance testing: */ final static int USER_MULTIPLIER = 10; }
package unit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import bio.terra.cli.serialization.userfacing.UFStatus; import bio.terra.cli.serialization.userfacing.UFWorkspace; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import harness.TestCommand; import harness.TestUser; import harness.baseclasses.ClearContextUnit; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; /** Tests for the `terra workspace` commands. */ @Tag("unit") public class Workspace extends ClearContextUnit { @Test @DisplayName("status, describe, workspace list reflect workspace create") void statusDescribeListReflectCreate() throws IOException { // select a test user and login TestUser testUser = TestUser.chooseTestUserWithSpendAccess(); testUser.login(); // `terra workspace create --format=json` UFWorkspace createWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create"); // check the created workspace has an id and a google project assertNotNull(createWorkspace.id, "create workspace returned a workspace id"); assertNotNull(createWorkspace.googleProjectId, "create workspace created a gcp project"); assertThat( "workspace email matches test user", createWorkspace.userEmail, equalToIgnoringCase(testUser.email)); // `terra status --format=json` UFStatus status = TestCommand.runAndParseCommandExpectSuccess(UFStatus.class, "status"); // check the current status reflects the new workspace assertThat( "workspace server matches current server", createWorkspace.serverName, equalToIgnoringCase(status.server.name)); assertEquals(createWorkspace.id, status.workspace.id, "workspace id matches current status"); assertEquals( createWorkspace.googleProjectId, status.workspace.googleProjectId, "workspace gcp project matches current status"); // `terra workspace describe --format=json` UFWorkspace describeWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "describe"); // check the new workspace is returned by describe assertEquals(createWorkspace.id, describeWorkspace.id, "workspace id matches that in describe"); assertEquals( createWorkspace.googleProjectId, describeWorkspace.googleProjectId, "workspace gcp project matches that in describe"); // check the new workspace is included in the list List<UFWorkspace> matchingWorkspaces = listWorkspacesWithId(createWorkspace.id); assertEquals(1, matchingWorkspaces.size(), "new workspace is included exactly once in list"); assertEquals( createWorkspace.id, matchingWorkspaces.get(0).id, "workspace id matches that in list"); assertEquals( createWorkspace.googleProjectId, matchingWorkspaces.get(0).googleProjectId, "workspace gcp project matches that in list"); // `terra workspace delete` TestCommand.runCommandExpectSuccess("workspace", "delete", "--quiet"); } @Test @DisplayName("status, describe, workspace list reflect workspace delete") void statusDescribeListReflectDelete() throws IOException { // select a test user and login TestUser testUser = TestUser.chooseTestUserWithSpendAccess(); testUser.login(); // `terra workspace create --format=json` UFWorkspace createWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create"); // `terra workspace delete --format=json` TestCommand.runCommandExpectSuccess("workspace", "delete", "--quiet"); // `terra status --format=json` UFStatus status = TestCommand.runAndParseCommandExpectSuccess(UFStatus.class, "status"); // check the current status reflects the deleted workspace assertNull(status.workspace, "status has no workspace after delete"); // `terra workspace describe --format=json` TestCommand.runCommandExpectExitCode(1, "workspace", "describe"); // check the deleted workspace is not included in the list List<UFWorkspace> matchingWorkspaces = listWorkspacesWithId(createWorkspace.id); assertEquals(0, matchingWorkspaces.size(), "deleted workspace is not included in list"); } @Test @DisplayName("status, describe, workspace list reflect workspace update") void statusDescribeListReflectUpdate() throws IOException { // select a test user and login TestUser testUser = TestUser.chooseTestUserWithSpendAccess(); testUser.login(); // `terra workspace create --format=json --name=$name --description=$description` String name = "statusDescribeListReflectUpdate"; String description = "status list reflect update"; UFWorkspace createWorkspace = TestCommand.runAndParseCommandExpectSuccess( UFWorkspace.class, "workspace", "create", "--name=" + name, "--description=" + description); // check the created workspace name and description are set assertNotNull(createWorkspace.name, "create workspace name is defined"); assertNotNull(createWorkspace.description, "create workspace description is defined"); // `terra workspace create --format=json --name=$newName --description=$newDescription` String newName = "NEW_statusDescribeListReflectUpdate"; String newDescription = "NEW status describe list reflect update"; TestCommand.runCommandExpectSuccess( "workspace", "update", "--format=json", "--name=" + newName, "--description=" + newDescription); // `terra status --format=json` UFStatus status = TestCommand.runAndParseCommandExpectSuccess(UFStatus.class, "status"); // check the current status reflects the update assertEquals(newName, status.workspace.name, "status matches updated workspace name"); assertEquals( newDescription, status.workspace.description, "status matches updated workspace description"); // `terra workspace describe --format=json` UFWorkspace describeWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "describe"); // check the workspace describe reflects the update assertEquals(newName, describeWorkspace.name, "describe matches updated workspace name"); assertEquals( newDescription, describeWorkspace.description, "describe matches updated workspace description"); // check the workspace list reflects the update List<UFWorkspace> matchingWorkspaces = listWorkspacesWithId(createWorkspace.id); assertEquals( 1, matchingWorkspaces.size(), "updated workspace is included exactly once in list"); assertEquals( newName, matchingWorkspaces.get(0).name, "updated workspace name matches that in list"); assertEquals( newDescription, matchingWorkspaces.get(0).description, "updated workspace description matches that in list"); // `terra workspace delete` TestCommand.runCommandExpectSuccess("workspace", "delete", "--quiet"); } @Test @DisplayName("status, describe reflect workspace set") void statusDescribeReflectsSet() throws IOException { // select a test user and login TestUser testUser = TestUser.chooseTestUserWithSpendAccess(); testUser.login(); // `terra workspace create --format=json` (workspace 1) UFWorkspace createWorkspace1 = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create"); // `terra workspace create --format=json` (workspace 2) UFWorkspace createWorkspace2 = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create"); // set current workspace = workspace 1 UFWorkspace setWorkspace1 = TestCommand.runAndParseCommandExpectSuccess( UFWorkspace.class, "workspace", "set", "--id=" + createWorkspace1.id); assertEquals(createWorkspace1.id, setWorkspace1.id, "set returned the expected workspace (1)"); // `terra status --format=json` UFStatus status = TestCommand.runAndParseCommandExpectSuccess(UFStatus.class, "status"); // check the current status reflects the workspace set assertEquals(createWorkspace1.id, status.workspace.id, "status matches set workspace id (1)"); // `terra workspace describe --format=json` UFWorkspace describeWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "describe"); // check the workspace describe reflects the workspace set assertEquals( createWorkspace1.id, describeWorkspace.id, "describe matches set workspace id (1)"); // set current workspace = workspace 2 UFWorkspace setWorkspace2 = TestCommand.runAndParseCommandExpectSuccess( UFWorkspace.class, "workspace", "set", "--id=" + createWorkspace2.id); assertEquals(createWorkspace2.id, setWorkspace2.id, "set returned the expected workspace (2)"); // `terra status --format=json` status = TestCommand.runAndParseCommandExpectSuccess(UFStatus.class, "status"); // check the current status reflects the workspace set assertEquals(createWorkspace2.id, status.workspace.id, "status matches set workspace id (2)"); // `terra workspace describe --format=json` describeWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "describe"); // check the workspace describe reflects the workspace set assertEquals( createWorkspace2.id, describeWorkspace.id, "describe matches set workspace id (2)"); // `terra workspace delete` (workspace 2) TestCommand.runCommandExpectSuccess("workspace", "delete", "--quiet"); // `terra workspace set` (workspace 1) TestCommand.runCommandExpectSuccess("workspace", "set", "--id=" + createWorkspace1.id); // `terra workspace delete` (workspace 1) TestCommand.runCommandExpectSuccess("workspace", "delete", "--quiet"); } @Test @DisplayName("workspace create fails without spend profile access") void createFailsWithoutSpendAccess() throws IOException { // select a test user and login TestUser testUser = TestUser.chooseTestUserWithoutSpendAccess(); testUser.login(); final String workspaceName = "bad-profile-6789"; // `terra workspace create` String stdErr = TestCommand.runCommandExpectExitCode(1, "workspace", "create", "--name=" + workspaceName); assertThat( "error message includes spend profile unauthorized", stdErr, CoreMatchers.containsString( "Accessing the spend profile failed. Ask an administrator to grant you access.")); // workspace was deleted List<UFWorkspace> listWorkspaces = TestCommand.runAndParseCommandExpectSuccess( new TypeReference<>() {}, "workspace", "list", "--limit=100"); assertFalse(listWorkspaces.stream().anyMatch(w -> workspaceName.equals(w.name))); } @Test @DisplayName("workspace describe reflects the number of resources") void describeReflectsNumResources() throws IOException { // select a test user and login TestUser testUser = TestUser.chooseTestUserWithSpendAccess(); testUser.login(); // `terra workspace create` UFWorkspace createdWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "create"); assertEquals(0, createdWorkspace.numResources, "new workspace has 0 resources"); // `terra resource create gcs-bucket --name=$name --bucket-name=$bucketName` String bucketResourceName = "describeReflectsNumResourcesGCS"; String bucketName = UUID.randomUUID().toString(); TestCommand.runCommandExpectSuccess( "resource", "create", "gcs-bucket", "--name=" + bucketResourceName, "--bucket-name=" + bucketName); // `terra workspace describe` UFWorkspace describeWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "describe"); assertEquals( 1, describeWorkspace.numResources, "worksapce has 1 resource after creating bucket"); // `terra resource create bq-dataset --name=$name --dataset-id=$datasetId` String datasetResourceName = "describeReflectsNumResourcesBQ"; String datasetId = "bq1"; TestCommand.runCommandExpectSuccess( "resource", "create", "bq-dataset", "--name=" + datasetResourceName, "--dataset-id=" + datasetId); // `terra workspace describe` describeWorkspace = TestCommand.runAndParseCommandExpectSuccess(UFWorkspace.class, "workspace", "describe"); assertEquals( 2, describeWorkspace.numResources, "worksapce has 2 resources after creating dataset"); // `terra workspace delete` TestCommand.runCommandExpectSuccess("workspace", "delete", "--quiet"); } /** * Helper method to call `terra workspace list` and filter the results on the specified workspace * id. Use a high limit to ensure that leaked workspaces in the list don't cause the one we care * about to page out. */ static List<UFWorkspace> listWorkspacesWithId(UUID workspaceId) throws JsonProcessingException { // `terra workspace list --format=json --limit=500` List<UFWorkspace> listWorkspaces = TestCommand.runAndParseCommandExpectSuccess( new TypeReference<>() {}, "workspace", "list", "--limit=500"); return listWorkspaces.stream() .filter(workspace -> workspace.id.equals(workspaceId)) .collect(Collectors.toList()); } }
package concurrency; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Test; public class NonBlockingCounterTest { private static final int THREAD_NUMBER = 10; @Test public void testName() throws Exception { List<Future<Integer>> tasks = new ArrayList<Future<Integer>>(); ExecutorService executor = createExecutor(tasks); executor.shutdown(); waitUntilProcessingFinishes(executor); List<Integer> results = assembleResults(tasks); checkIfEqual(tasks, results); } private ExecutorService createExecutor(List<Future<Integer>> tasks) { final NonBlockingCounter counter = new NonBlockingCounter(); ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUMBER); for (int i = 0; i < 500; i++) { Callable<Integer> worker = () -> { int number = counter.increment(); return number; }; Future<Integer> submit = executor.submit(worker); tasks.add(submit); } return executor; } private void waitUntilProcessingFinishes(ExecutorService executor) { while (!executor.isTerminated()) { } } private List<Integer> assembleResults(List<Future<Integer>> list) { List<Integer> results = new CopyOnWriteArrayList<Integer>(); for (Future<Integer> future : list) { try { results.add(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } return results; } private void checkIfEqual(List<Future<Integer>> list1, List<Integer> list2) { if (list1.size() != list2.size()) { throw new RuntimeException("Too many entries: " + list1.size() + " != " + list2.size()); } } }
package cz.muni.fi.jboss.migration; import cz.muni.fi.jboss.migration.conf.AS7Config; import cz.muni.fi.jboss.migration.conf.Configuration; import cz.muni.fi.jboss.migration.utils.AS7CliUtils; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Ondrej Zizka, ozizka at redhat.com */ @RunWith(Arquillian.class) public class ArqTest { private static Configuration createTestConfig01() { Configuration conf = new Configuration(); conf.getGlobal().getAS5Config().setDir("testdata/as5configs/01_510all"); conf.getGlobal().getAS5Config().setProfileName("all"); conf.getGlobal().getAS7Config().setDir("target/jboss-as-7.1.1.Final"); conf.getGlobal().getAS7Config().setConfigPath("standalone/configuration/standalone.xml"); return conf; } /** * Test of doMigration method, of class MigratorEngine. */ @Test @RunAsClient public void testDoMigration( /*@ArquillianResource ManagementClient client*/ ) throws Exception { System.out.println( "doMigration" ); Configuration conf = createTestConfig01(); AS7Config as7Config = conf.getGlobal().getAS7Config(); // Set the Mgmt host & port from the client; //as7Config.setHost( client.getMgmtAddress() ); //as7Config.setManagementPort( client.getMgmtPort() ); /* This fails for some reason: java.lang.RuntimeException: Provider for type class org.jboss.as.arquillian.container.ManagementClient returned a null value: org.jboss.as.arquillian.container.ManagementClientProvider@4aee4b87 at org.jboss.arquillian.test.impl.enricher.resource.ArquillianResourceTestEnricher.lookup(ArquillianResourceTestEnricher.java:115) at org.jboss.arquillian.test.impl.enricher.resource.ArquillianResourceTestEnricher.resolve(ArquillianResourceTestEnricher.java:91) Let's resort to default values. */ //ModelControllerClient as7client = client.getControllerClient(); ModelControllerClient as7client = ModelControllerClient.Factory.create(as7Config.getHost(), as7Config.getManagementPort()); // Then query for the server path. String as7Dir = AS7CliUtils.queryServerHomeDir( as7client ); conf.getGlobal().getAS7Config().setDir( as7Dir ); MigratorApp.validateConfiguration( conf ); //MigratorApp.migrate( conf ); MigratorEngine migrator = new MigratorEngine(conf); migrator.doMigration(); } }// class
package net.imagej.ops; import net.imagej.ops.Ops.ASCII; import net.imagej.ops.Ops.Equation; import net.imagej.ops.Ops.CreateImg; import org.junit.Test; /** * Tests that the ops of the global namespace have corresponding type-safe Java * method signatures declared in the {@link OpService} class. * * @author Curtis Rueden */ public class GlobalNamespaceTest extends AbstractNamespaceTest { /** Tests for {@link CreateImg} method convergence. */ @Test public void testCreateImg() { assertComplete(null, OpService.class, CreateImg.NAME); } /** Tests for {@link ASCII} method convergence. */ @Test public void testASCII() { assertComplete(null, OpService.class, ASCII.NAME); } /** Tests for {@link Equation} method convergence. */ @Test public void testEquation() { assertComplete(null, OpService.class, Equation.NAME); } }
package appstore; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class TestThisWillFailAbunch { @Test public void aFailingTest() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest2() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest3() { assertTrue("I expected this to pass!", false); } //@Ignore @Test public void aFailingTest4() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aNewFailingTest31() { assertTrue("I expected this to pass!", true); } @Test public void aNotherNewFailingTest4() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest5() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest6() { assertTrue("I expected this to pass!", false); } @Test public void aPassingTest3() { assertTrue("Success!", true); } @Test public void aPassingTest4() { assertTrue("Success!", true); } private void doSomething() { interesting(); } private void interesting() { RubeGoldburgMachine machine = new RubeGoldburgMachine(); machine.processPayment(); } private class RubeGoldburgMachine { void processPayment() { throw new IllegalStateException("bad payment code"); } } }
package com.google.sps.data; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Test; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; /** * This class tests the functions from the TextAnalyser class. * * The format of a test name is: * 1) conditions * 2) what is the subject being tested (the input) * 3) expected results (the output) * These concepts are separated by _ e.g. conditions_input_output **/ @RunWith(JUnit4.class) public final class TextAnalyserTest { @Test public void analyse_positiveText_positiveSentimentScore() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Today is a special day. It is your birthday, so enjoy it!"); assertTrue("Sentiment score is not positive.", textAnalyser.getSentimentScore() > 0.0F); } @Test public void analyse_negativeText_negativeSentimentScore() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("I don't like this."); assertTrue("Sentiment score is not negative.", textAnalyser.getSentimentScore() < 0.0F); } @Test public void analyse_positiveText_positiveMood() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Happy Birthday!"); assertEquals("thrilled", textAnalyser.getMood()); } @Test public void analyse_negativeText_negativeMood() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Smoking, well, there is no healthy amount of smoking." + "Healthy here meant never having smoked."); assertEquals("depressed", textAnalyser.getMood()); } @Test public void analyse_textWithEvents_eventsPresent() { TextAnalyser textAnalyser = new TextAnalyser("Today is my Birthday. Today you got a job promotion."); Set<String> expected = new LinkedHashSet<>(); Set<String> actual = textAnalyser.getEvents(); expected.add("birthday"); expected.add("promotion"); assertEquals(expected, actual); } @Test public void analyse_textWithGreetings_greetingPresent() { TextAnalyser textAnalyser = new TextAnalyser("Good morning, sunshine! Happy holidays to everyone!"); Set<String> expected = new LinkedHashSet<>(); Set<String> actual = textAnalyser.getGreetings(); expected.add("good morning"); expected.add("happy holiday"); assertEquals(expected, actual); } @Test public void analyse_textWithLocation_locationPresent() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("I am going to Paris this weekend."); assertTrue("There is no city displayed.", textAnalyser.getEntities().contains("paris")); } @Test public void analyse_textWithName_namePresent() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Hello, Mark!"); assertTrue("There is no name displayed", textAnalyser.getEntities().contains("mark")); } @Test public void analyse_textWithEventEntity_eventPresent() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("My wedding is coming soon!"); assertTrue("There is no event displayed.", textAnalyser.getEntities().contains("wedding")); } @Test public void analyse_textWithAdjectives_adjectivesPresent() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("This is a beautiful day! Be nice to everyone!"); assertTrue("The text should identify adjectives.", textAnalyser.getAdjectives().contains("beautiful")); } @Test public void analyse_textWithNoAdjectives_emptySet() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("The birthday party is in the garden."); assertEquals(Collections.emptySet(), textAnalyser.getAdjectives()); } @Test public void toLowerCase_KeyWords_lowerCaseKeyWords() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Hello, Mark! My Birthday is coming very soon and I want to" + " invite you to my Party! It is in Paris. It is not expensive." + " We will have so much fun! All of our friends will also come to the party"); Set<String> expected = new LinkedHashSet<>(); Set<String> actual = textAnalyser.getKeyWords(); for(String keyWord : actual) { expected.add(keyWord.toLowerCase()); } assertEquals(expected, actual); } @Test public void analyse_textContainingKeyWords_notEmptySet() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Happy Birthday! We will go to Paris!"); assertFalse(textAnalyser.getKeyWords().isEmpty()); } @Test public void analyse_textWithEnoughWordsToGetCategory_theCategory() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("A computer is a machine that can be instructed to carry" + " out sequences of arithmetic or logical operations automatically" + " via computer programming. Modern computers have the ability to" + " follow generalized sets of operations, called programs."); assertTrue("Couldn't get the correct category.", textAnalyser.getCategories().contains("computers & electronics")); } @Test public void analyse_textWithNotEnoughWordsToGetCateogry_emptySet() throws IOException { TextAnalyser textAnalyser = new TextAnalyser("Hello!"); assertEquals(Collections.emptySet(), textAnalyser.getCategories()); } @Test public void checkHtmlInjection_HTMLCode_htmlInjection() { TextAnalyser textAnalyser = new TextAnalyser( "<html> <h1>Here are the results that match your query: </h1>" + "<h2>{user-query}</h2><ol><li>Result A<li>Result B</ol></html>" ); assertEquals("html-injection", textAnalyser.checkInjection()); } @Test public void checkHtmlInjection_noHTMLCode_noHtmlInjection() { TextAnalyser textAnalyser = new TextAnalyser("This is a code that doesn't contain html."); assertEquals("no-html-injection", textAnalyser.checkInjection()); } }
package com.jcabi.github; import com.jcabi.aspects.Tv; import java.util.Iterator; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; /** * Test case for {@link RtSearch}. * * @author Carlos Miranda (miranda.cma@gmail.com) * @version $Id$ * @checkstyle MultipleStringLiterals (140 lines) */ @SuppressWarnings("PMD.AvoidDuplicateLiterals") public final class RtSearchITCase { /** * RtSearch can search for repos. * * @throws Exception if a problem occurs */ @Test public void canSearchForRepos() throws Exception { MatcherAssert.assertThat( RtSearchITCase.github().search().repos("repo", "stars", "desc"), Matchers.not(Matchers.emptyIterableOf(Repo.class)) ); } /** * RtSearch can fetch multiple pages of a large result (more than 25 items). * * @throws Exception if a problem occurs */ @Test public void canFetchMultiplePages() throws Exception { final Iterator<Repo> iter = RtSearchITCase.github().search().repos( "java", "", "" ).iterator(); int count = 0; while (iter.hasNext() && count < Tv.HUNDRED) { iter.next(); count += 1; } MatcherAssert.assertThat( count, Matchers.greaterThanOrEqualTo(Tv.HUNDRED) ); } /** * RtSearch can search for issues. * * @throws Exception if a problem occurs */ @Test public void canSearchForIssues() throws Exception { MatcherAssert.assertThat( RtSearchITCase.github().search().issues("issue", "updated", "desc"), Matchers.not(Matchers.emptyIterableOf(Issue.class)) ); } /** * RtSearch can search for users. * * @throws Exception if a problem occurs */ @Test public void canSearchForUsers() throws Exception { MatcherAssert.assertThat( RtSearchITCase.github().search().users("jcabi", "joined", "desc"), Matchers.not(Matchers.emptyIterableOf(User.class)) ); } @Test public void canSearchForContents() throws Exception { MatcherAssert.assertThat( RtSearchITCase.github().search().codes( "addClass repo:jquery/jquery", "joined", "desc" ), Matchers.not(Matchers.emptyIterableOf(Content.class)) ); } /** * Return github for test. * @return Github */ private static Github github() { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); return new RtGithub(key); } }
package org.cactoos.text; import java.io.IOException; import org.hamcrest.core.IsEqual; import org.hamcrest.object.HasToString; import org.junit.Test; import org.llorllale.cactoos.matchers.Assertion; /** * Test case for {@link UncheckedText}. * * @since 0.3 * @checkstyle JavadocMethodCheck (500 lines) */ public final class UncheckedTextTest { @Test(expected = RuntimeException.class) public void rethrowsCheckedToUncheckedException() { new UncheckedText( () -> { throw new IOException("intended"); } ).asString(); } @Test public void toStringMustReturnSameOfAsString() { final String text = "one"; new Assertion<>( "Must implement #toString which returns the same of #asString", new UncheckedText( new TextOf(text) ), new HasToString<>( new IsEqual<>(text) ) ).affirm(); } }
package com.skraylabs.poker; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.skraylabs.poker.model.Card; import com.skraylabs.poker.model.Rank; import com.skraylabs.poker.model.Suit; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; public class TwoPairTest { @Test public void givenLessThanFourCardsReturnsFalse() { Collection<Card> cards = new ArrayList<Card>(); cards.add(new Card(Rank.Ace, Suit.Hearts)); cards.add(new Card(Rank.Ace, Suit.Spades)); cards.add(new Card(Rank.King, Suit.Hearts)); boolean result = ProbabilityCalculator.hasTwoPair(cards); assertThat(result, is(false)); } @Test public void givenFourUnpairedCardsReturnsFalse() { Collection<Card> cards = new ArrayList<Card>(); cards.add(new Card(Rank.Ace, Suit.Hearts)); cards.add(new Card(Rank.King, Suit.Hearts)); cards.add(new Card(Rank.Queen, Suit.Hearts)); cards.add(new Card(Rank.Jack, Suit.Hearts)); boolean result = ProbabilityCalculator.hasTwoPair(cards); assertThat(result, is(false)); } @Test public void givenNotATwoPairReturnsTrue() { Collection<Card> cards = new ArrayList<Card>(); cards.add(new Card(Rank.Ace, Suit.Hearts)); cards.add(new Card(Rank.Ace, Suit.Spades)); cards.add(new Card(Rank.King, Suit.Clubs)); cards.add(new Card(Rank.King, Suit.Diamonds)); boolean result = ProbabilityCalculator.hasTwoPair(cards); assertThat(result, is(true)); } }
package org.icij.extract.core; import java.util.logging.Logger; import java.util.logging.Level; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ArrayBlockingQueue; import org.redisson.Redisson; import com.lambdaworks.redis.RedisConnectionException; import org.junit.Test; import org.junit.BeforeClass; import org.junit.Assert; import org.junit.Assume; public class ConsumerTest { public static final Logger logger = Logger.getLogger("extract:test"); @BeforeClass public static void setUpBeforeClass() { logger.setLevel(Level.INFO); } @Test public void testConsume() throws Throwable { final Extractor extractor = new Extractor(logger); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PrintStream print = new PrintStream(output); final Spewer spewer = new PrintStreamSpewer(logger, print); final int threads = 2; final Consumer consumer = new Consumer(logger, spewer, extractor, threads); final Path file = Paths.get(getClass().getResource("/documents/text/plain.txt").toURI()); consumer.consume(file); consumer.awaitTermination(); Assert.assertEquals("This is a test.\n\n", output.toString()); } @Test public void testConsumeWithQueue() throws Throwable { final Extractor extractor = new Extractor(logger); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PrintStream print = new PrintStream(output); final Spewer spewer = new PrintStreamSpewer(logger, print); final int threads = 2; final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(threads * 2); final PollingConsumer consumer = new PollingConsumer(logger, queue, spewer, extractor, threads); final Path file = Paths.get(getClass().getResource("/documents/text/plain.txt").toURI()); queue.put(file.toString()); consumer.start(); consumer.awaitTermination(); Assert.assertEquals("This is a test.\n\n", output.toString()); } @Test public void testConsumeWithRedisQueue() throws Throwable { final Extractor extractor = new Extractor(logger); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PrintStream print = new PrintStream(output); final Spewer spewer = new PrintStreamSpewer(logger, print); final int threads = 2; try { final Redisson redisson = Redisson.create(); final BlockingQueue<String> queue = redisson.getBlockingQueue("extract:test:queue"); final PollingConsumer consumer = new PollingConsumer(logger, queue, spewer, extractor, threads); final Path file = Paths.get(getClass().getResource("/documents/text/plain.txt").toURI()); queue.put(file.toString()); consumer.start(); consumer.awaitTermination(); redisson.shutdown(); } catch (RedisConnectionException e) { Assume.assumeNoException(e); return; } Assert.assertEquals("This is a test.\n\n", output.toString()); } @Test public void testConsumeWithScanner() throws Throwable { final Extractor extractor = new Extractor(logger); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PrintStream print = new PrintStream(output); final Spewer spewer = new PrintStreamSpewer(logger, print); final int threads = 2; final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(threads * 2); final PollingConsumer consumer = new PollingConsumer(logger, queue, spewer, extractor, threads); final Scanner scanner = new QueueingScanner(logger, queue); scanner.scan(Paths.get(getClass().getResource("/documents/text/plain.txt").toURI())); scanner.scan(Paths.get(getClass().getResource("/documents/ocr/simple.tiff").toURI())); consumer.start(); consumer.awaitTermination(); Assert.assertEquals("This is a test.\n\nHEAVY\nMETAL\n\n\n", output.toString()); } @Test public void testConsumeWithDirectoryScanner() throws Throwable { final Extractor extractor = new Extractor(logger); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final PrintStream print = new PrintStream(output); final Spewer spewer = new PrintStreamSpewer(logger, print); final int threads = 2; final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(threads * 2); final PollingConsumer consumer = new PollingConsumer(logger, queue, spewer, extractor, threads); final Scanner scanner = new QueueingScanner(logger, queue); scanner.scan(Paths.get(getClass().getResource("/documents/text/").toURI())); consumer.start(); consumer.awaitTermination(); Assert.assertEquals("This is a test.\n\nThis is a test.\n\n", output.toString()); } }
package com.sling.rest; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpMethod; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import com.google.common.io.ByteStreams; import com.sling.rest.persist.MongoCRUD; /** * This is our JUnit test for our verticle. The test uses vertx-unit, so we declare a custom runner. */ @RunWith(VertxUnitRunner.class) public class RestVerticleTest { private Vertx vertx; private ArrayList<String> urls; /** * * @param context * the test context. */ @Before public void setUp(TestContext context) throws IOException { vertx = Vertx.vertx(); MongoCRUD.setIsEmbedded(true); try { MongoCRUD.getInstance(vertx).startEmbeddedMongo(); } catch (Exception e1) { e1.printStackTrace(); } DeploymentOptions options = new DeploymentOptions().setConfig(new JsonObject().put("http.port", Integer.valueOf(System.getProperty("http.port")))); vertx.deployVerticle(RestVerticle.class.getName(), options, context.asyncAssertSuccess(id -> { System.out.println("async complete ========================="); try { urls = urlsFromFile(); System.out.println("url complete ========================="); } catch (Exception e) { e.printStackTrace(); } })); } /** * This method, called after our test, just cleanup everything by closing the vert.x instance * * @param context * the test context */ @After public void tearDown(TestContext context) { vertx.close(context.asyncAssertSuccess()); } /** * This method, iterates through the urls.csv and runs each url - currently only checking the returned status codes * * @param context * the test context */ @Test public void checkURLs(TestContext context) { try { int[] urlCount = { urls.size() }; // Async async = context.async(urlCount[0]); urls.forEach(url -> { Async async = context.async(); urlCount[0] = urlCount[0] - 1; HttpMethod method = null; String[] urlInfo = url.split(" , "); if ("POST".equalsIgnoreCase(urlInfo[0].trim())) { method = HttpMethod.POST; } else if ("PUT".equalsIgnoreCase(urlInfo[0].trim())) { method = HttpMethod.PUT; } else if ("DELETE".equalsIgnoreCase(urlInfo[0].trim())) { method = HttpMethod.DELETE; } else { method = HttpMethod.GET; } HttpClient client = vertx.createHttpClient(); HttpClientRequest request = client.requestAbs(method, urlInfo[1], new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse httpClientResponse) { System.out.println(urlInfo[1]); if (httpClientResponse.statusCode() != 404) { // this is cheating for now - add posts to the test case so that // we dont get 404 for missing entities context.assertInRange(200, httpClientResponse.statusCode(), 5); } // System.out.println(context.assertInRange(200, httpClientResponse.statusCode(),5).); httpClientResponse.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer buffer) { /* * // System.out.println("Response (" // + buffer.length() // + "): "); */System.out.println(buffer.getString(0, buffer.length())); async.complete(); } }); } }); request.headers().add("Authorization", "abcdefg"); request.headers().add("Accept", "application/json"); request.setChunked(true); request.end(); }); } catch (Throwable e) { e.printStackTrace(); } finally { } } private ArrayList<String> urlsFromFile() throws IOException { ArrayList<String> ret = new ArrayList<String>(); byte[] content = ByteStreams.toByteArray(getClass().getResourceAsStream("/urls.csv")); InputStream is = null; BufferedReader bfReader = null; try { is = new ByteArrayInputStream(content); bfReader = new BufferedReader(new InputStreamReader(is)); String temp = null; while ((temp = bfReader.readLine()) != null) { ret.add(temp); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (Exception ex) { } } return ret; } }
package com.wizzardo.tools.xml; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; public class NodeTest { @Test public void parse() { String s; Node xml; s = "I say: '${hello}'"; Assert.assertEquals("I say: '${hello}'", new XmlParser().parse(s).textOwn()); s = "<xml><xml>"; Assert.assertEquals("xml", new XmlParser().parse(s).name()); s = "<xml/>"; Assert.assertEquals("xml", new XmlParser().parse(s).name()); s = "<xml attr><xml>"; Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr")); s = "<xml attr ><xml>"; Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr")); s = "<xml attr />"; Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr")); s = "<xml attr/>"; Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr")); s = "<xml attr attr2/>"; Assert.assertEquals(true, new XmlParser().parse(s).hasAttr("attr")); s = "<xml attr=\"qwerty\"/>"; Assert.assertEquals("qwerty", new XmlParser().parse(s).attr("attr")); s = "<xml attr=\"qwerty\" attr2/>"; Assert.assertEquals("qwerty", new XmlParser().parse(s).attr("attr")); s = "<xml attr2 attr=\"qwerty\"/>"; Assert.assertEquals("qwerty", new XmlParser().parse(s).attr("attr")); s = "<xml><child></child></xml>"; Assert.assertEquals(1, new XmlParser().parse(s).size()); s = "<xml><child/></xml>"; Assert.assertEquals(1, new XmlParser().parse(s).size()); s = "<xml><child attr=\"qwerty\"/></xml>"; Assert.assertEquals(1, new XmlParser().parse(s).size()); Assert.assertEquals("qwerty", new XmlParser().parse(s).first().attr("attr")); s = "<xml><child/><child/><child/>ololo</xml>"; Assert.assertEquals(4, new XmlParser().parse(s).size()); Assert.assertEquals("ololo", new XmlParser().parse(s).text()); Assert.assertEquals("ololo", new XmlParser().parse(s).textOwn()); s = "<xml><child/><child/><child>ololo</child></xml>"; Assert.assertEquals(3, new XmlParser().parse(s).size()); Assert.assertEquals("ololo", new XmlParser().parse(s).text()); Assert.assertEquals("", new XmlParser().parse(s).textOwn()); s = "<xml><child/><child/><child>ololo</child>lo</xml>"; Assert.assertEquals(4, new XmlParser().parse(s).size()); Assert.assertEquals("ololo lo", new XmlParser().parse(s).text()); Assert.assertEquals("lo", new XmlParser().parse(s).textOwn()); s = "<xml>\n\t\tololo\n\t\t</xml>"; Assert.assertEquals("ololo", new XmlParser().parse(s).text()); } @Test public void xml_comment_1() throws IOException { String s = "<div><!-- <comment> --></div>"; Node div = new XmlParser().parse(s); Assert.assertEquals(0, div.attributes().size()); Assert.assertEquals(1, div.children().size()); Assert.assertEquals(true, div.children().get(0).isComment()); Assert.assertEquals("<!-- <comment> -->", div.children().get(0).ownText()); } @Test public void xml_comment_2() throws IOException { String s = "" + "<div>\n" + " <!--[if IE]>\n" + " According to the conditional comment this is IE<br />\n" + " <![endif] "</div>\n"; Node div = new XmlParser().parse(s); Assert.assertEquals(0, div.attributes().size()); Assert.assertEquals(1, div.children().size()); Assert.assertEquals(true, div.children().get(0).isComment()); Assert.assertEquals("" + "<!-- [if IE]>\n" + " According to the conditional comment this is IE<br />\n" + " <![endif] -->", div.children().get(0).ownText()); } @Test public void xml_line_number_1() throws IOException { String s = "" + "<div>\n" + " <b>\n" + " test\n" + " </b>\n" + " <b>\n" + "\n" + "\n" + " test_2\n" + " </b>\n" + " <!-- <comment> -->\n" + "</div>"; Node div = new XmlParser().parse(s); Assert.assertEquals(0, div.attributes().size()); Assert.assertEquals(3, div.children().size()); Assert.assertEquals(1, div.getLineNumber()); Node b; b = div.children().get(0); Assert.assertEquals(1, b.children().size()); Assert.assertEquals(2, b.getLineNumber()); Assert.assertEquals(3, b.children().get(0).getLineNumber()); b = div.children().get(1); Assert.assertEquals(1, b.children().size()); Assert.assertEquals(5, b.getLineNumber()); Assert.assertEquals(8, b.children().get(0).getLineNumber()); b = div.children().get(2); Assert.assertEquals(true, b.isComment()); Assert.assertEquals(10, b.getLineNumber()); } @Test public void html_1() throws IOException { String s = ""; for (File f : new File("src/test/resources/xml").listFiles()) { System.out.println("parsing: " + f); new HtmlParser().parse(f); } } @Test public void html_2() throws IOException { String s = "<div width=100px></div>"; Node root = new HtmlParser().parse(s); Node div = root.children().get(0); Assert.assertEquals(1, div.attributes().size()); Assert.assertEquals(0, div.children().size()); Assert.assertEquals("100px", div.attr("width")); s = "<div width=100px height=50px></div>"; root = new HtmlParser().parse(s); div = root.children().get(0); Assert.assertEquals(2, div.attributes().size()); Assert.assertEquals(0, div.children().size()); Assert.assertEquals("100px", div.attr("width")); Assert.assertEquals("50px", div.attr("height")); } @Test public void html_3() throws IOException { String s = "<div><script>\n" + " var a\n" + " for(var i=0; i<10;i++) {\n" + " a+=i;" + " }\n" + "</script></div>"; Node root = new HtmlParser().parse(s); Node div = root.children().get(0); Assert.assertEquals(1, div.children().size()); Node script = div.children.get(0); Assert.assertEquals("var a\n" + " for(var i=0; i<10;i++) {\n" + " a+=i;" + " }\n", script.text()); } @Test public void gsp_1() throws IOException { String s = "<div><g:textField name=\"${it.key}\" placeholder=\"${[].collect({it})}\"/></div>"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(1, div.children().size()); Node textField = div.children().get(0); Assert.assertEquals("g:textField", textField.name()); Assert.assertEquals(0, textField.children().size()); Assert.assertEquals(2, textField.attributes().size()); Assert.assertEquals("${it.key}", textField.attr("name")); Assert.assertEquals("${[].collect({it})}", textField.attr("placeholder")); } @Test public void gsp_2() throws IOException { String s = "<div><g:textField name=\"${it.key}\" placeholder=\"${String.valueOf(it.getValue()).replace(\"\\\"\", \"\")}\"/></div>"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(1, div.children().size()); Node textField = div.children().get(0); Assert.assertEquals("g:textField", textField.name()); Assert.assertEquals(0, textField.children().size()); Assert.assertEquals(2, textField.attributes().size()); Assert.assertEquals("${it.key}", textField.attr("name")); Assert.assertEquals("${String.valueOf(it.getValue()).replace(\"\\\"\", \"\")}", textField.attr("placeholder")); } @Test public void gsp_3() throws IOException { String s = "<div id=\"${id}\"><span>foo:</span>${foo}</div>"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(2, div.children().size()); Assert.assertEquals(1, div.attributes().size()); Assert.assertEquals("${id}", div.attr("id")); Node span = div.children().get(0); Assert.assertEquals("span", span.name()); Assert.assertEquals(1, span.children().size()); Assert.assertEquals("foo:", span.text()); Node foo = div.children().get(1); Assert.assertEquals("${foo}", foo.text()); } @Test public void gsp_4() throws IOException { String s = "<div><script>\n" + " var a\n" + " for(var i=0; i<10;i++) {\n" + " a+=i;" + " }\n" + "</script></div>"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals(1, div.children().size()); Node script = div.children.get(0); Assert.assertEquals("var a\n" + " for(var i=0; i<10;i++) {\n" + " a+=i;" + " }\n", script.text()); } @Test public void gsp_comment_1() throws IOException { String s = "" + "<div>\n" + " %{--<p>$test</p>--}%\n" + "</div>\n"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(1, div.children().size()); Assert.assertEquals(0, div.attributes().size()); Assert.assertEquals("%{--<p>$test</p>--}%", div.children().get(0).textOwn()); } @Test public void gsp_comment_2() throws IOException { String s = "" + "<div %{--foo=\"${bar}\" " \n" + "</div>\n"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(0, div.children().size()); Assert.assertEquals(0, div.attributes().size()); } @Test public void gsp_comment_3() throws IOException { String s = "" + "<div foo=\"bar%{--_$id " \n" + "</div>\n"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(0, div.children().size()); Assert.assertEquals(1, div.attributes().size()); Assert.assertEquals("bar_0", div.attr("foo")); } @Test public void gsp_comment_4() throws IOException { String s = "<div>\n" + " before\n" + " %{--<p>text</p>--}%\n" + " after\n" + "</div>"; Node root = new GspParser().parse(s); Node div = root.children().get(0); Assert.assertEquals("div", div.name()); Assert.assertEquals(3, div.children().size()); Assert.assertEquals("before", div.get(0).text()); Assert.assertEquals("%{--<p>text</p>--}%", div.get(1).text()); Assert.assertEquals("after", div.get(2).text()); } }
package de.meggsimum.w3w; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.junit.Assume.assumeNotNull; /** * Unit test for {@linkplain What3Words} * * @author Christian Mayer, meggsimum */ public class What3WordsTest { /** * The api key is read from command line arguments or can also be entered here manually. */ private String apiKey = null; /** * Name of the system property hodling the API key for W3W. */ public static final String API_KEY_PROPERTY = "W3W_API_KEY"; @Rule public ExpectedException expectedException = ExpectedException.none(); /** * Checks if the API key is either hard coded or passed via system properties. * Only if this precondition is true, the tests are executed. */ @Before public void beforeMethod() { // Try to read the API key from system properties only in case it was not hard coded. if (apiKey == null) { apiKey = System.getProperty(API_KEY_PROPERTY); } // Fall back to environment variable in case API key was not provided as property if(apiKey == null) { apiKey = System.getenv(API_KEY_PROPERTY); } assumeNotNull(apiKey); } /** * Tests the words -> position API wrapper */ @Test public void testWordsToPosition() throws Exception { What3Words w3w = new What3Words(apiKey); String[] words = {"goldfish", "fuzzy", "aggregates"}; double[] coords; coords = w3w.wordsToPosition(words); assertEquals(2, coords.length); assertEquals(49.422636, coords[0], 0.1); assertEquals(8.320833, coords[1], 0.1); } /** * Tests the position -> words API wrapper */ @Test public void testPositionToWords() throws Exception { What3Words w3w = new What3Words(apiKey); double[] coords = {49.422636, 8.320833}; String[] words; words = w3w.positionToWords(coords); assertEquals(3, words.length); assertEquals("goldfish", words[0]); assertEquals("fuzzy", words[1]); assertEquals("aggregates", words[2]); } /** * Tests the position -> words API wrapper after changing the language */ @Test public void testChangeLang() throws Exception { What3Words w3w = new What3Words(apiKey); w3w.setLanguage("de"); double[] coords = {49.422636, 8.320833}; String[] words; try { words = w3w.positionToWords(coords); assertEquals(3, words.length); assertEquals("kleid", words[0]); assertEquals("ober", words[1]); assertEquals("endlos", words[2]); } catch (Exception e) { fail(); } } /** * Test for exception in case of an invalid API-key */ @Test public void testInvalidWhat3WordsAPIKeyException() throws Exception { expectedException.expect(Exception.class); expectedException.expectMessage("Authentication failed; invalid API key"); What3Words w3w = new What3Words(UUID.randomUUID().toString() + apiKey); double[] coords = {49.422636, 8.320833}; w3w.positionToWords(coords); } // Object API tests @Test public void testWordsToPositionObj() throws Exception { What3Words w3w = new What3Words(apiKey); ThreeWords words = new ThreeWords("goldfish", "fuzzy", "aggregates"); Coordinates coords = w3w.wordsToPosition(words); assertEquals(49.422636, coords.getLatitude(), 0.000001); assertEquals(8.320833, coords.getLongitude(), 0.000001); } @Test public void testWordsToPositionWithLangObj() throws Exception { What3Words w3w = new What3Words(apiKey); ThreeWords words = new ThreeWords("kleid", "ober", "endlos"); Coordinates coords = w3w.wordsToPosition(words, "de"); assertEquals(49.422636, coords.getLatitude(), 0.000001); assertEquals(8.320833, coords.getLongitude(), 0.000001); } @Test public void testPositionToWordsObj() throws Exception { What3Words w3w = new What3Words(apiKey); Coordinates coordinates = new Coordinates(49.422636, 8.320833); ThreeWords threeWords = w3w.positionToWords(coordinates); assertEquals(new ThreeWords("goldfish", "fuzzy", "aggregates"), threeWords); } @Test public void testPositionToWordsWithLangObj() throws Exception { What3Words w3w = new What3Words(apiKey); Coordinates coordinates = new Coordinates(49.422636, 8.320833); ThreeWords threeWords = w3w.positionToWords(coordinates, "de"); assertEquals(new ThreeWords("kleid", "ober", "endlos"), threeWords); } @Test public void testGerman3wordAddress()throws Exception { What3Words w3w = new What3Words(apiKey, "de"); String[] words = {"zulassen", "fährst", "wächst"}; double[] coords = w3w.wordsToPosition(words); assertEquals(2, coords.length); assertEquals(50.049496, coords[0], 0.000001); assertEquals(-110.681137, coords[1], 0.000001); } @Test public void testFrench3wordAddress()throws Exception { What3Words w3w = new What3Words(apiKey, "fr"); String[] words = {"garçon", "étaler", "frôler"}; double[] coords = w3w.wordsToPosition(words); assertEquals(2, coords.length); assertEquals(48.246860, coords[0], 0.000001); assertEquals(16.099389, coords[1], 0.000001); } }
package org.takes.facets.auth; import java.io.IOException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.takes.Request; import org.takes.Take; import org.takes.Takes; import org.takes.facets.auth.codecs.CcPlain; import org.takes.facets.forward.RsForward; import org.takes.rq.RqFake; import org.takes.rq.RqWithHeader; import org.takes.rs.RsEmpty; import org.takes.tk.TkEmpty; /** * Test case for {@link TsSecure}. * @author Dmitry Zaytsev (dmitry.zaytsev@gmail.com) * @version $Id$ * @since 0.11 */ public final class TsSecureTest { /** * TsSecure can fail on anonymous access. * @throws IOException If some problem inside */ @Test(expected = RsForward.class) public void failsOnAnonymous() throws IOException { new TsSecure( new Takes() { @Override public Take route(final Request request) throws IOException { return new TkEmpty(); } } ).route(new RqFake()).act(); } /** * TsSecure can pass on registered user. * @throws IOException If some problem inside */ @Test public void passesOnRegisteredUser() throws IOException { MatcherAssert.assertThat( new TsSecure( new Takes() { @Override public Take route(final Request request) throws IOException { return new TkEmpty(); } } ).route( new RqWithHeader( new RqFake(), TsAuth.class.getSimpleName(), new String( new CcPlain().encode(new Identity.Simple("urn:test:1")) ) ) ).act(), Matchers.instanceOf(RsEmpty.class) ); } }
package view; import java.util.*; import javafx.beans.value.ChangeListener; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.scene.control.*; import javafx.scene.layout.*; import model.Proof; import model.ProofListener; public class ProofView implements ProofListener, View{ /* * These are magic constants that decide the lineNo padding. * Margin can't be changed as a property, so the solution is to take into account how much the border * and the padding increases the distance between rows and add the padding to the line numbers accordingly. */ static final int carryAddOpen = 3; static final int carryAddClose = 5; // TextFields of the premises and conclusion for quick access private TextField premises; private TextField conclusion; private Stack<VBox> curBoxDepth = new Stack<>(); // This is a list of BorderPanes, which are the "lines" of the proof. private List<BorderPane> rList = new LinkedList<>(); private int counter = 1; private int carry = 0; private VBox lineNo; private VBox rows; //The tab object of this view private Tab tab; //The proof displayed in this view private Proof proof; //The patth where this proof was loaded/should be saved private String path; //Name of the proof/file of this view private String name; private TextField lastTf; /** * This ia listener that is applied to the last textField. It creates a new row, each time the value of the textField is changed. */ private ChangeListener<? extends String> lastTfListener = (ov, oldValue, newValue) -> { newRow(); }; private AnchorPane createProofPane() { lineNo = new VBox(); rows = new VBox(); lineNo.setFillWidth(true); rows.setFillWidth(true); HBox hb = new HBox(); hb.setHgrow(rows, Priority.ALWAYS); hb.getChildren().addAll(lineNo, rows); hb.setPadding(new Insets(5, 5, 5, 5)); ScrollPane sp = new ScrollPane(hb); sp.getStyleClass().add("fit"); hb.heightProperty().addListener((ov, oldValue, newValue) -> { if (newValue.doubleValue() > oldValue.doubleValue()) { // Change this to only trigger on new row!! sp.setVvalue(1.0); // Otherwise it will scroll down when you insert a row in the middle } }); AnchorPane proofPane = new AnchorPane(sp); proofPane.setTopAnchor(sp, 0.0); proofPane.setRightAnchor(sp, 0.0); proofPane.setLeftAnchor(sp, 0.0); proofPane.setBottomAnchor(sp, 0.0); return proofPane; } public ProofView(TabPane tabPane, Proof proof, HBox premisesAndConclusion) { this.proof = proof; this.proof.registerProofListener(this); this.premises = (TextField) premisesAndConclusion.getChildren().get(0); this.conclusion = (TextField) premisesAndConclusion.getChildren().get(2); SplitPane sp = new SplitPane(premisesAndConclusion, createProofPane()); sp.setOrientation(Orientation.VERTICAL); sp.setDividerPosition(0, 0.1); AnchorPane anchorPane = new AnchorPane(sp); anchorPane.setTopAnchor(sp, 0.0); anchorPane.setRightAnchor(sp, 0.0); anchorPane.setLeftAnchor(sp, 0.0); anchorPane.setBottomAnchor(sp, 0.0); ProofTab tab = new ProofTab("Proof", this); this.tab = tab; tab.setContent(anchorPane); tabPane.getTabs().add(tab); tabPane.getSelectionModel().select(tab); // Byt till den nya tabben newRow(); } public ProofView(TabPane tabPane, Proof proof) { this(tabPane, proof, CommonPanes.premisesAndConclusion()); } public ProofView(TabPane tabPane, Proof proof, String sPremises, String sConclusion) { this(tabPane, proof, CommonPanes.premisesAndConclusion(sPremises, sConclusion)); } /* Controller begin */ public void openBox() { proof.openBox(); } public void closeBox() { proof.closeBox(); } public void newRow() { proof.addRow("", ""); } public void rowDeleteLastRow(){ proof.deleteRow(); } /* End of controller */ private void checkAndAdd(Region item) { if (curBoxDepth.isEmpty()) { rows.getChildren().add(item); } else { VBox temp = curBoxDepth.peek(); temp.getChildren().add(item); } } private BorderPane createRow() { BorderPane bp = new BorderPane(); TextField tf1 = new TextField(); TextField tf2 = new TextField(); tf1.getStyleClass().add("myText"); tf2.getStyleClass().add("myText"); bp.setCenter(tf1); bp.setRight(tf2); return bp; } Label createLabel() { Label lbl = new Label(""+counter++); lbl.getStyleClass().add("lineNo"); lbl.setPadding(new Insets(8+carry,2,2,2)); carry = 0; return lbl; } public void rowInserted() { BorderPane bp = createRow(); checkAndAdd(bp); int curRowNo = counter; lineNo.getChildren().add(createLabel()); if (lastTf != null) { lastTf.textProperty().removeListener((ChangeListener<? super String>) lastTfListener); } TextField tempTf = (TextField) bp.getCenter(); lastTf = tempTf; lastTf.textProperty().addListener((ChangeListener<? super String>) lastTfListener); // Updates the Proof object if the textField is updated lastTf.textProperty().addListener((ov, oldValue, newValue) -> { proof.updateFormulaRow(newValue, curRowNo); }); TextField rule = (TextField) bp.getRight(); // Updates the Proof object if the textField is updated rule.textProperty().addListener((ov, oldValue, newValue) -> { proof.updateRuleRow(newValue, curRowNo); }); rList.add(bp); } // public void focus() { // Save the last focused textfield here for quick resuming? // Platform.runLater(() -> lastTf.requestFocus()); public void boxOpened(){ VBox vb = new VBox(); vb.getStyleClass().add("openBox"); carry += carryAddOpen; checkAndAdd(vb); curBoxDepth.push(vb); newRow(); } public void boxClosed(){ if (!curBoxDepth.isEmpty()) { VBox vb = curBoxDepth.pop(); vb.getStyleClass().clear(); vb.getStyleClass().add("closedBox"); carry += carryAddClose; } } public void rowUpdated(boolean wellFormed, int lineNo) { TextField expression = (TextField) rList.get(lineNo-1).getCenter(); if (wellFormed) { expression.getStyleClass().removeIf((s) -> s.equals("bad")); // Remove the bad-class from textField. } else { expression.getStyleClass().add("bad"); } } public void conclusionReached(){} /**Deletes the last row*/ public void rowDeleted(){ //todo make sure that the lines gets updated correctly + refactor the code int lastRow=rList.size()-1; //Do nothing when no row is present if(rList.size()==0){ } //delete the closing part of the box else if(rList.get(rList.size()-1).getParent().getStyleClass().toString().equals("closedBox")){ VBox node=(VBox)rList.get(rList.size()-1).getParent(); //pushes the box for the last row curBoxDepth.push(node); //used for pushing back the closed boxes ArrayList<VBox>v=new ArrayList<>(); v.add(node); //Remove all the closing part of boxes that encloses the last row while(node.getParent() instanceof VBox){ if(node.getStyleClass().toString().equals("closedBox")) { carry-=carryAddClose; } node.getStyleClass().clear(); node.getStyleClass().add("openBox"); node = (VBox) node.getParent(); v.add(node); } //pushes back the closed boxes to the stack in reverse for(int i=0;i<v.size();i++){ curBoxDepth.push(v.get((v.size()-1)-i)); } } //delete open part of the box else if(rList.get(lastRow).getParent().getChildrenUnmodifiable().size()==1 && rList.get(lastRow).getParent().getStyleClass().toString().equals("openBox")){ ; VBox grandParentBox=((VBox)rList.get(rList.size()-1).getParent().getParent()); grandParentBox.getChildren().remove(grandParentBox.getChildren().size()-1); rList.remove(rList.size()-1); lineNo.getChildren().remove(lineNo.getChildren().size() - 1); counter if (!curBoxDepth.isEmpty()){ curBoxDepth.pop(); } } //delete row else if(rList.get(lastRow).getParent().getChildrenUnmodifiable().size()>0){ ((VBox)rList.get(lastRow).getParent()).getChildren().remove(((VBox) rList.get(lastRow).getParent()).getChildren().size()-1); rList.remove(rList.size()-1); counter lineNo.getChildren().remove(lineNo.getChildren().size() - 1); BorderPane lastBP = rList.get(rList.size()-1); lastTf = (TextField) lastBP.getCenter(); lastTf.textProperty().addListener((ChangeListener<? super String>) lastTfListener); } } public Tab getTab(){ return tab;} public Proof getProof(){ return proof;} public String getPath(){ return path;} public void setPath(String path){ this.path = path; } public String getName(){ return name;} public void setName(String name){ this.name = name; } }
package freemarker.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.junit.Test; import freemarker.template.Configuration; import freemarker.template.Version; import freemarker.template.utility.DateUtil; public class SQLTimeZoneTest extends TemplateOutputTest { private final static TimeZone GMT_P02 = TimeZone.getTimeZone("GMT+02"); private TimeZone lastDefaultTimeZone; private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); { df.setTimeZone(DateUtil.UTC); } // Values that JDBC in GMT+02 would produce private final java.sql.Date sqlDate = new java.sql.Date(utcToLong("2014-07-11T22:00:00")); // 2014-07-12 private final Time sqlTime = new Time(utcToLong("1970-01-01T10:30:05")); // 12:30:05 private final Timestamp sqlTimestamp = new Timestamp(utcToLong("2014-07-12T10:30:05")); // 2014-07-12T12:30:05 private final Date javaDate = new Date(utcToLong("2014-07-12T10:30:05")); // 2014-07-12T12:30:05 private final Date javaDayErrorDate = new Date(utcToLong("2014-07-11T22:00:00")); // 2014-07-12T12:30:05 public TimeZone getLastDefaultTimeZone() { return lastDefaultTimeZone; } public void setLastDefaultTimeZone(TimeZone lastDefaultTimeZone) { this.lastDefaultTimeZone = lastDefaultTimeZone; } public java.sql.Date getSqlDate() { return sqlDate; } public Time getSqlTime() { return sqlTime; } public Timestamp getSqlTimestamp() { return sqlTimestamp; } public Date getJavaDate() { return javaDate; } public Date getJavaDayErrorDate() { return javaDayErrorDate; } private static final String FTL = "${sqlDate} ${sqlTime} ${sqlTimestamp} ${javaDate?datetime}\n" + "${sqlDate?string.iso_fz} ${sqlTime?string.iso_fz} " + "${sqlTimestamp?string.iso_fz} ${javaDate?datetime?string.iso_fz}\n" + "${sqlDate?string.xs_fz} ${sqlTime?string.xs_fz} " + "${sqlTimestamp?string.xs_fz} ${javaDate?datetime?string.xs_fz}\n" + "${sqlDate?string.xs} ${sqlTime?string.xs} " + "${sqlTimestamp?string.xs} ${javaDate?datetime?string.xs}\n" + "<#setting time_zone='GMT'>\n" + "${sqlDate} ${sqlTime} ${sqlTimestamp} ${javaDate?datetime}\n" + "${sqlDate?string.iso_fz} ${sqlTime?string.iso_fz} " + "${sqlTimestamp?string.iso_fz} ${javaDate?datetime?string.iso_fz}\n" + "${sqlDate?string.xs_fz} ${sqlTime?string.xs_fz} " + "${sqlTimestamp?string.xs_fz} ${javaDate?datetime?string.xs_fz}\n" + "${sqlDate?string.xs} ${sqlTime?string.xs} " + "${sqlTimestamp?string.xs} ${javaDate?datetime?string.xs}\n"; private static final String OUTPUT_BEFORE_SETTING_GMT_CFG_GMT2 = "2014-07-12 12:30:05 2014-07-12T12:30:05 2014-07-12T12:30:05\n" + "2014-07-12 12:30:05+02:00 2014-07-12T12:30:05+02:00 2014-07-12T12:30:05+02:00\n" + "2014-07-12+02:00 12:30:05+02:00 2014-07-12T12:30:05+02:00 2014-07-12T12:30:05+02:00\n" + "2014-07-12 12:30:05 2014-07-12T12:30:05+02:00 2014-07-12T12:30:05+02:00\n"; private static final String OUTPUT_BEFORE_SETTING_GMT_CFG_GMT1_SQL_DIFFERENT = "2014-07-12 12:30:05 2014-07-12T11:30:05 2014-07-12T11:30:05\n" + "2014-07-12 12:30:05+02:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n" + "2014-07-12+02:00 12:30:05+02:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n" + "2014-07-12 12:30:05 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n"; private static final String OUTPUT_BEFORE_SETTING_GMT_CFG_GMT1_SQL_SAME = "2014-07-11 11:30:05 2014-07-12T11:30:05 2014-07-12T11:30:05\n" + "2014-07-11 11:30:05+01:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n" + "2014-07-11+01:00 11:30:05+01:00 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n" + "2014-07-11 11:30:05 2014-07-12T11:30:05+01:00 2014-07-12T11:30:05+01:00\n"; private static final String OUTPUT_AFTER_SETTING_GMT_CFG_SQL_SAME = "2014-07-11 10:30:05 2014-07-12T10:30:05 2014-07-12T10:30:05\n" + "2014-07-11 10:30:05Z 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n" + "2014-07-11Z 10:30:05Z 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n" + "2014-07-11 10:30:05 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n"; private static final String OUTPUT_AFTER_SETTING_GMT_CFG_SQL_DIFFERENT = "2014-07-12 12:30:05 2014-07-12T10:30:05 2014-07-12T10:30:05\n" + "2014-07-12 12:30:05+02:00 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n" + "2014-07-12+02:00 12:30:05+02:00 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n" + "2014-07-12 12:30:05 2014-07-12T10:30:05Z 2014-07-12T10:30:05Z\n"; @Test public void testWithDefaultTZAndNullSQL() throws Exception { TimeZone prevSysDefTz = TimeZone.getDefault(); TimeZone.setDefault(GMT_P02); try { Configuration cfg = createConfiguration(); assertNull(cfg.getSQLDateAndTimeTimeZone()); assertEquals(TimeZone.getDefault(), cfg.getTimeZone()); assertOutput(FTL, OUTPUT_BEFORE_SETTING_GMT_CFG_GMT2 + OUTPUT_AFTER_SETTING_GMT_CFG_SQL_SAME, cfg); } finally { TimeZone.setDefault(prevSysDefTz); } } @Test public void testWithDefaultTZAndGMT2SQL() throws Exception { TimeZone prevSysDefTz = TimeZone.getDefault(); TimeZone.setDefault(GMT_P02); try { Configuration cfg = createConfiguration(); cfg.setSQLDateAndTimeTimeZone(GMT_P02); assertOutput(FTL, OUTPUT_BEFORE_SETTING_GMT_CFG_GMT2 + OUTPUT_AFTER_SETTING_GMT_CFG_SQL_DIFFERENT, cfg); } finally { TimeZone.setDefault(prevSysDefTz); } } @Test public void testWithGMT1AndNullSQL() throws Exception { Configuration cfg = createConfiguration(); assertNull(cfg.getSQLDateAndTimeTimeZone()); cfg.setTimeZone(TimeZone.getTimeZone("GMT+01:00")); assertOutput(FTL, OUTPUT_BEFORE_SETTING_GMT_CFG_GMT1_SQL_SAME + OUTPUT_AFTER_SETTING_GMT_CFG_SQL_SAME, cfg); } @Test public void testWithGMT1AndGMT2SQL() throws Exception { Configuration cfg = createConfiguration(); cfg.setSQLDateAndTimeTimeZone(GMT_P02); cfg.setTimeZone(TimeZone.getTimeZone("GMT+01:00")); assertOutput(FTL, OUTPUT_BEFORE_SETTING_GMT_CFG_GMT1_SQL_DIFFERENT + OUTPUT_AFTER_SETTING_GMT_CFG_SQL_DIFFERENT, cfg); } @Test public void testWithGMT2AndNullSQL() throws Exception { Configuration cfg = createConfiguration(); assertNull(cfg.getSQLDateAndTimeTimeZone()); cfg.setTimeZone(TimeZone.getTimeZone("GMT+02")); assertOutput(FTL, OUTPUT_BEFORE_SETTING_GMT_CFG_GMT2 + OUTPUT_AFTER_SETTING_GMT_CFG_SQL_SAME, cfg); } @Test public void testWithGMT2AndGMT2SQL() throws Exception { Configuration cfg = createConfiguration(); cfg.setSQLDateAndTimeTimeZone(GMT_P02); cfg.setTimeZone(TimeZone.getTimeZone("GMT+02")); assertOutput(FTL, OUTPUT_BEFORE_SETTING_GMT_CFG_GMT2 + OUTPUT_AFTER_SETTING_GMT_CFG_SQL_DIFFERENT, cfg); } @Test public void testCacheFlushings() throws Exception { Configuration cfg = createConfiguration(); cfg.setTimeZone(DateUtil.UTC); cfg.setDateFormat("yyyy-MM-dd E"); cfg.setTimeFormat("HH:mm:ss E"); cfg.setDateTimeFormat("yyyy-MM-dd'T'HH:mm:ss E"); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting locale='de'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-11 Fr, 10:30:05 Do, 2014-07-12T10:30:05 Sa, 2014-07-12T10:30:05 Sa, 2014-07-12 Sa, 10:30:05 Sa\n", cfg); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting date_format='yyyy-MM-dd'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-11, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12, 10:30:05 Sat\n", cfg); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting time_format='HH:mm:ss'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-11 Fri, 10:30:05, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05\n", cfg); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting datetime_format='yyyy-MM-dd\\'T\\'HH:mm:ss'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-11 Fri, 10:30:05 Thu, 2014-07-12T10:30:05, 2014-07-12T10:30:05, 2014-07-12 Sat, 10:30:05 Sat\n", cfg); cfg.setSQLDateAndTimeTimeZone(GMT_P02); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting locale='de'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-12 Sa, 12:30:05 Do, 2014-07-12T10:30:05 Sa, 2014-07-12T10:30:05 Sa, 2014-07-12 Sa, 10:30:05 Sa\n", cfg); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting date_format='yyyy-MM-dd'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-12, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12, 10:30:05 Sat\n", cfg); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting time_format='HH:mm:ss'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-12 Sat, 12:30:05, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05\n", cfg); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n" + "<#setting datetime_format='yyyy-MM-dd\\'T\\'HH:mm:ss'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}, ${javaDate?date}, ${javaDate?time}\n", "2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05 Sat, 2014-07-12T10:30:05 Sat, 2014-07-12 Sat, 10:30:05 Sat\n" + "2014-07-12 Sat, 12:30:05 Thu, 2014-07-12T10:30:05, 2014-07-12T10:30:05, 2014-07-12 Sat, 10:30:05 Sat\n", cfg); } @Test public void testDateAndTimeBuiltInsHasNoEffect() throws Exception { Configuration cfg = createConfiguration(); cfg.setTimeZone(DateUtil.UTC); cfg.setSQLDateAndTimeTimeZone(GMT_P02); assertOutput( "${javaDayErrorDate?date} ${javaDayErrorDate?time} ${sqlTimestamp?date} ${sqlTimestamp?time} " + "${sqlDate?date} ${sqlTime?time}\n" + "<#setting time_zone='GMT+02'>\n" + "${javaDayErrorDate?date} ${javaDayErrorDate?time} ${sqlTimestamp?date} ${sqlTimestamp?time} " + "${sqlDate?date} ${sqlTime?time}\n" + "<#setting time_zone='GMT-11'>\n" + "${javaDayErrorDate?date} ${javaDayErrorDate?time} ${sqlTimestamp?date} ${sqlTimestamp?time} " + "${sqlDate?date} ${sqlTime?time}\n", "2014-07-11 22:00:00 2014-07-12 10:30:05 2014-07-12 12:30:05\n" + "2014-07-12 00:00:00 2014-07-12 12:30:05 2014-07-12 12:30:05\n" + "2014-07-11 11:00:00 2014-07-11 23:30:05 2014-07-12 12:30:05\n", cfg); } @Test public void testChangeSettingInTemplate() throws Exception { Configuration cfg = createConfiguration(); cfg.setTimeZone(DateUtil.UTC); assertNull(cfg.getSQLDateAndTimeTimeZone()); assertOutput( "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting sql_date_and_time_time_zone='GMT+02'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting sql_date_and_time_time_zone='null'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting time_zone='GMT+03'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting sql_date_and_time_time_zone='GMT+02'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting sql_date_and_time_time_zone='GMT-11'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting date_format='xs fz'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting time_format='xs fz'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n" + "<#setting datetime_format='iso m'>\n" + "${sqlDate}, ${sqlTime}, ${sqlTimestamp}, ${javaDate?datetime}\n", "2014-07-11, 10:30:05, 2014-07-12T10:30:05, 2014-07-12T10:30:05\n" + "2014-07-12, 12:30:05, 2014-07-12T10:30:05, 2014-07-12T10:30:05\n" + "2014-07-11, 10:30:05, 2014-07-12T10:30:05, 2014-07-12T10:30:05\n" + "2014-07-12, 13:30:05, 2014-07-12T13:30:05, 2014-07-12T13:30:05\n" + "2014-07-12, 12:30:05, 2014-07-12T13:30:05, 2014-07-12T13:30:05\n" + "2014-07-11, 23:30:05, 2014-07-12T13:30:05, 2014-07-12T13:30:05\n" + "2014-07-11-11:00, 23:30:05, 2014-07-12T13:30:05, 2014-07-12T13:30:05\n" + "2014-07-11-11:00, 23:30:05-11:00, 2014-07-12T13:30:05, 2014-07-12T13:30:05\n" + "2014-07-11-11:00, 23:30:05-11:00, 2014-07-12T13:30+03:00, 2014-07-12T13:30+03:00\n", cfg); } @Test public void testFormatUTCFlagHasNoEffect() throws Exception { Configuration cfg = createConfiguration(); cfg.setSQLDateAndTimeTimeZone(GMT_P02); cfg.setTimeZone(TimeZone.getTimeZone("GMT-01")); assertOutput( "<#setting date_format='xs fz'><#setting time_format='xs fz'>\n" + "${sqlDate}, ${sqlTime}, ${javaDate?time}\n" + "<#setting date_format='xs fz u'><#setting time_format='xs fz u'>\n" + "${sqlDate}, ${sqlTime}, ${javaDate?time}\n" + "<#setting sql_date_and_time_time_zone='GMT+03'>\n" + "${sqlDate}, ${sqlTime}, ${javaDate?time}\n" + "<#setting sql_date_and_time_time_zone='null'>\n" + "${sqlDate}, ${sqlTime}, ${javaDate?time}\n" + "<#setting date_format='xs fz'><#setting time_format='xs fz'>\n" + "${sqlDate}, ${sqlTime}, ${javaDate?time}\n" + "<#setting date_format='xs fz fu'><#setting time_format='xs fz fu'>\n" + "${sqlDate}, ${sqlTime}, ${javaDate?time}\n", "2014-07-12+02:00, 12:30:05+02:00, 09:30:05-01:00\n" + "2014-07-12+02:00, 12:30:05+02:00, 10:30:05Z\n" + "2014-07-12+03:00, 13:30:05+03:00, 10:30:05Z\n" + "2014-07-11-01:00, 09:30:05-01:00, 10:30:05Z\n" + "2014-07-11-01:00, 09:30:05-01:00, 09:30:05-01:00\n" + "2014-07-11Z, 10:30:05Z, 10:30:05Z\n", cfg); } private Configuration createConfiguration() { Configuration cfg = new Configuration(new Version(2, 3, 21)); cfg.setLocale(Locale.US); cfg.setDateFormat("yyyy-MM-dd"); cfg.setTimeFormat("HH:mm:ss"); cfg.setDateTimeFormat("yyyy-MM-dd'T'HH:mm:ss"); return cfg; } @Override protected Object createDataModel() { return this; } private long utcToLong(String isoDateTime) { try { return df.parse(isoDateTime).getTime(); } catch (ParseException e) { throw new RuntimeException(e); } } }
package org.thingsboard.gateway; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class SigfoxTest { private static final String DEVICE_TYPE_ID = "DEVICE_TYPE_ID"; private static final String SECURITY_TOKEN = "SECURITY_TOKEN"; private static final String GATEWAY_URL = "http://localhost:9090/sigfox/" + DEVICE_TYPE_ID + "/"; public static void main(String[] args) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", SECURITY_TOKEN); headers.setContentType(MediaType.APPLICATION_JSON); String postJson = new String(Files.readAllBytes(Paths.get("src/test/resources/post.json"))); new RestTemplate().exchange(GATEWAY_URL, HttpMethod.POST, new HttpEntity<>(postJson, headers), String.class); } }
package gumtree.spoon; import gumtree.spoon.builder.SpoonGumTreeBuilder; import gumtree.spoon.diff.Diff; import gumtree.spoon.diff.operations.MoveOperation; import gumtree.spoon.diff.operations.Operation; import gumtree.spoon.diff.operations.OperationKind; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import spoon.Launcher; import spoon.SpoonModelBuilder; import spoon.reflect.code.CtBinaryOperator; import spoon.reflect.code.CtConstructorCall; import spoon.reflect.code.CtIf; import spoon.reflect.code.CtInvocation; import spoon.reflect.code.CtLocalVariable; import spoon.reflect.code.CtNewClass; import spoon.reflect.code.CtReturn; import spoon.reflect.code.CtThrow; import spoon.reflect.declaration.CtClass; import spoon.reflect.declaration.CtElement; import spoon.reflect.declaration.CtType; import spoon.reflect.factory.Factory; import spoon.support.compiler.VirtualFile; import spoon.support.compiler.jdt.JDTBasedSpoonCompiler; import spoon.support.compiler.jdt.JDTSnippetCompiler; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test Spoon Diff * @author Matias Martinez, matias.martinez@inria.fr * */ public class AstComparatorTest { @Test public void testgetCtType() throws Exception { final Factory factory = new Launcher().getFactory(); String c1 = "package spoon1.test; " + "class X {" + "public void foo0() {" + " int x = 0;" + "}" + "}"; assertTrue(getCtType(factory, c1) != null); } @Test public void testAnalyzeStringString() { String c1 = "" + "class X {" + "public void foo0() {" + " int x = 0;" + "}" + "};"; String c2 = "" + "class X {" + "public void foo1() {" + " int x = 0;" + "}" + "};"; AstComparator diff = new AstComparator(); Diff editScript = diff.compare(c1, c2); assertTrue(editScript.getRootOperations().size() == 1); } @Test public void exampleInsertAndUpdate() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test1/TypeHandler1.java"); File fr = new File("src/test/resources/examples/test1/TypeHandler2.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(2, actions.size()); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtClass); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation")); assertTrue(result.containsOperation(OperationKind.Update, "FieldRead")); assertFalse(result.containsOperation(OperationKind.Delete, "Invocation")); assertFalse(result.containsOperation(OperationKind.Update, "Invocation")); } @Test public void exampleSingleUpdate() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test2/CommandLine1.java"); File fr = new File("src/test/resources/examples/test2/CommandLine2.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Literal"/*"PAR-Literal"*/)); } @Test public void exampleRemoveMethod() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test3/CommandLine1.java"); File fr = new File("src/test/resources/examples/test3/CommandLine2.java"); Diff result = diff.compare(fl,fr); //result.debugInformation(); // commenting the assertion on the number of actions // we now have three actions, with two updates of invocations because of binding to the ol/new method // while it is not visible in the AST, this is indeed a change in the behavior // it means that the AST diff in this case also captures something deeper // assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "Method")); } @Test public void exampleInsert() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test4/CommandLine1.java"); File fr = new File("src/test/resources/examples/test4/CommandLine2.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Method","resolveOptionNew")); } @Test public void testMain() throws Exception{ File fl = new File("src/test/resources/examples/test4/CommandLine1.java"); File fr = new File("src/test/resources/examples/test4/CommandLine2.java"); AstComparator.main(new String []{fl.getAbsolutePath(), fr.getAbsolutePath()}); } @Test public void testContent() throws Exception{ final Factory factory = new Launcher().createFactory(); File fl = new File("src/test/resources/examples/test4/CommandLine1.java"); assertNotNull(getSpoonType(factory, readFile(fl))); } public static CtType<?> getCtType(Factory factory, String content) { SpoonModelBuilder compiler = new JDTBasedSpoonCompiler(factory); compiler.addInputSource(new VirtualFile(content, "/test")); compiler.build(); return factory.Type().getAll().get(0); } private static CtType getSpoonType(Factory factory, String content) { try { canBuild(factory, content); } catch (Exception e) { // must fails } List<CtType<?>> types = factory.Type().getAll(); if (types.isEmpty()) { throw new RuntimeException("No Type was created by spoon"); } CtType spt = types.get(0); spt.getPackage().getTypes().remove(spt); return spt; } private static void canBuild(Factory factory, String content) { SpoonModelBuilder builder = new JDTSnippetCompiler(factory, content); try { builder.build(); } catch (Exception e) { throw new RuntimeException("snippet compilation error while compiling: " + content, e); } } private static String readFile(File f) throws IOException { FileReader reader = new FileReader(f); char[] chars = new char[(int) f.length()]; reader.read(chars); String content = new String(chars); reader.close(); return content; } @Test public void testJDTBasedSpoonCompiler(){ String content1 = "package spoon1.test; " + "class X {" + "public void foo0() {" + " int x = 0;" + "}" + "}"; Factory factory = new Launcher().createFactory(); SpoonModelBuilder compiler = new JDTSnippetCompiler(factory, content1); compiler.build(); CtClass<?> clazz1 = (CtClass<?>) factory.Type().getAll().get(0); Assert.assertNotNull(clazz1); } @Test public void test5() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test5/left_LmiInitialContext_1.5.java"); File fr = new File("src/test/resources/examples/test5/right_LmiInitialContext_1.6.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "BinaryOperator","AND")); } @Test public void test6() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test6/A.java"); File fr = new File("src/test/resources/examples/test6/B.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "Parameter","i")); } @Test public void test7() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/test7/left_QuickNotepad_1.13.java src/test/resources/examples/test7/right_QuickNotepad_1.14.java File fl = new File("src/test/resources/examples/test7/left_QuickNotepad_1.13.java"); File fr = new File("src/test/resources/examples/test7/right_QuickNotepad_1.14.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); System.out.println(actions); assertEquals(2, actions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "Invocation", "QuickNotepadTextArea#addKeyListener(QuickNotepad$KeyHandler)")); assertTrue(result.containsOperation(OperationKind.Delete, "Class","KeyHandler")); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtClass); assertEquals("QuickNotepad", ((CtClass)ancestor).getSimpleName()); } @Test public void test8() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test8/left.java"); File fr = new File("src/test/resources/examples/test8/right.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); assertEquals(1, actions.size()); assertTrue(actions.toString(), result.containsOperation(OperationKind.Update, "VARIABLE_TYPE", "java.lang.Throwable")); } @Test public void test9() throws Exception{ // contract: we detect local variable changes too AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/test9/left.java"); File fr = new File("src/test/resources/examples/test9/right.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(1, actions.size()); assertTrue(actions.toString(), result.containsOperation(OperationKind.Update, "VARIABLE_TYPE", "boolean")); } @Test public void test_t_286700() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_286700/left_CmiContext_1.2.java src/test/resources/examples/t_286700/right_CmiContext_1.3.java File fl = new File("src/test/resources/examples/t_286700/left_CmiContext_1.2.java"); File fr = new File("src/test/resources/examples/t_286700/right_CmiContext_1.3.java"); Diff result = diff.compare(fl,fr); //result.debugInformation(); assertTrue(result.containsOperation(OperationKind.Insert, "Method", "getObjectPort")); // commented for the same reason as exampleRemoveMethod // assertEquals(1, actions.size()); } @Test public void test_t_202564() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_202564/left_PropPanelModelElement_1.9.java src/test/resources/examples/t_202564/right_PropPanelModelElement_1.10.java File fl = new File("src/test/resources/examples/t_202564/left_PropPanelModelElement_1.9.java"); File fr = new File("src/test/resources/examples/t_202564/right_PropPanelModelElement_1.10.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Field", "_assocEndRoleIcon")); } @Test public void test_t_204225() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_204225/left_UMLModelElementStereotypeComboBoxModel_1.3.java src/test/resources/examples/t_204225/right_UMLModelElementStereotypeComboBoxModel_1.4.java File fl = new File("src/test/resources/examples/t_204225/left_UMLModelElementStereotypeComboBoxModel_1.3.java"); File fr = new File("src/test/resources/examples/t_204225/right_UMLModelElementStereotypeComboBoxModel_1.4.java"); Diff result = diff.compare(fl,fr); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtReturn); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(actions.size(), 2); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "OR")); assertTrue(result.containsOperation(OperationKind.Move, "BinaryOperator", "AND")); } @Test public void test_t_208618() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_208618/left_PropPanelUseCase_1.39.java src/test/resources/examples/t_208618/right_PropPanelUseCase_1.40.java File fl = new File("src/test/resources/examples/t_208618/left_PropPanelUseCase_1.39.java"); File fr = new File("src/test/resources/examples/t_208618/right_PropPanelUseCase_1.40.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation", "#addField(<unknown>,<unknown>)")); } @Test public void test_t_209184() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_209184/left_ActionCollaborationDiagram_1.28.java src/test/resources/examples/t_209184/right_ActionCollaborationDiagram_1.29.java File fl = new File("src/test/resources/examples/t_209184/left_ActionCollaborationDiagram_1.28.java"); File fr = new File("src/test/resources/examples/t_209184/right_ActionCollaborationDiagram_1.29.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "#getTarget()")); } @Test public void test_t_211903() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_211903/left_MemberFilePersister_1.4.java src/test/resources/examples/t_211903/right_MemberFilePersister_1.5.java File fl = new File("src/test/resources/examples/t_211903/left_MemberFilePersister_1.4.java"); File fr = new File("src/test/resources/examples/t_211903/right_MemberFilePersister_1.5.java"); Diff result = diff.compare(fl,fr); //result.debugInformation(); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtConstructorCall); assertEquals(88,ancestor.getPosition().getLine()); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertTrue(result.containsOperation(OperationKind.Update, "ConstructorCall", "java.io.FileReader(java.io.File)")); assertTrue(result.containsOperation(OperationKind.Insert, "ConstructorCall", "java.io.InputStreamReader(java.io.InputStream,java.lang.String)")); // additional checks on low-level actions assertTrue(result.containsOperations(result.getAllOperations(), OperationKind.Insert, "Literal", "\"UTF-8\"")); // the change is in the local variable declaration CtElement elem = actions.get(0).getNode(); assertNotNull(elem); assertNotNull(elem.getParent(CtLocalVariable.class)); } @Test public void test_t_212496() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_212496/left_CoreHelperImpl_1.29.java src/test/resources/examples/t_212496/right_CoreHelperImpl_1.30.java File fl = new File("src/test/resources/examples/t_212496/left_CoreHelperImpl_1.29.java"); File fr = new File("src/test/resources/examples/t_212496/right_CoreHelperImpl_1.30.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Method", "setEnumerationLiterals")); } @Test public void test_t_214116() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_214116/left_Modeller_1.134.java src/test/resources/examples/t_214116/right_Modeller_1.135.java File fl = new File("src/test/resources/examples/t_214116/left_Modeller_1.134.java"); File fr = new File("src/test/resources/examples/t_214116/right_Modeller_1.135.java"); Diff result = diff.compare(fl,fr); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtBinaryOperator); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(actions.size(), 2); assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\" \"")); // the change is in a throw CtElement elem = actions.get(0).getNode(); assertNotNull(elem); assertNotNull(elem.getParent(CtThrow.class)); } @Test public void test_t_214614() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_214614/left_JXButtonGroupPanel_1.2.java src/test/resources/examples/t_214614/right_JXButtonGroupPanel_1.3.java File fl = new File("src/test/resources/examples/t_214614/left_JXButtonGroupPanel_1.2.java"); File fr = new File("src/test/resources/examples/t_214614/right_JXButtonGroupPanel_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Delete, "Invocation", "java.awt.Container#setFocusTraversalPolicyProvider(boolean)")); } @Test public void test_t_220985() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_220985/left_Server_1.20.java src/test/resources/examples/t_220985/right_Server_1.21.java File fl = new File("src/test/resources/examples/t_220985/left_Server_1.20.java"); File fr = new File("src/test/resources/examples/t_220985/right_Server_1.21.java"); Diff result = diff.compare(fl,fr); result.getRootOperations(); //result.debugInformation(); assertTrue(result.containsOperation(OperationKind.Insert, "Conditional")); // TODO the delete literal "." found could also be a move to the new conditional, so we don't specify this // this is the case if gumtree.match.gt.minh" = "0" (but bad for other tests) } @Test public void test_t_221070() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221070/left_Server_1.68.java src/test/resources/examples/t_221070/right_Server_1.69.java File fl = new File("src/test/resources/examples/t_221070/left_Server_1.68.java"); File fr = new File("src/test/resources/examples/t_221070/right_Server_1.69.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Delete, "Break")); } @Test public void test_t_221295() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221295/left_Board_1.5.java src/test/resources/examples/t_221295/right_Board_1.6.java File fl = new File("src/test/resources/examples/t_221295/left_Board_1.5.java"); File fr = new File("src/test/resources/examples/t_221295/right_Board_1.6.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "BinaryOperator", "GT")); CtElement elem = actions.get(0).getNode(); assertNotNull(elem); assertNotNull(elem.getParent(CtReturn.class)); } @Test public void test_t_221966() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221966/left_TurnOrdered_1.3.java src/test/resources/examples/t_221966/right_TurnOrdered_1.4.java File fl = new File("src/test/resources/examples/t_221966/left_TurnOrdered_1.3.java"); File fr = new File("src/test/resources/examples/t_221966/right_TurnOrdered_1.4.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Delete, "Invocation", "java.io.PrintStream#println(char[])")); } @Test public void test_t_221343() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221343/left_Server_1.186.java src/test/resources/examples/t_221343/right_Server_1.187.java File fl = new File("src/test/resources/examples/t_221343/left_Server_1.186.java"); File fr = new File("src/test/resources/examples/t_221343/right_Server_1.187.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "java.util.Vector#remove(int)")); } @Test public void test_t_221345() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221345/left_Server_1.187.java src/test/resources/examples/t_221345/right_Server_1.188.java File fl = new File("src/test/resources/examples/t_221345/left_Server_1.187.java"); File fr = new File("src/test/resources/examples/t_221345/right_Server_1.188.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "java.util.Vector#removeElement(java.lang.Object)")); } @Test public void test_t_221422() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221422/left_Server_1.227.java src/test/resources/examples/t_221422/right_Server_1.228.java File fl = new File("src/test/resources/examples/t_221422/left_Server_1.227.java"); File fr = new File("src/test/resources/examples/t_221422/right_Server_1.228.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "java.util.Vector#add(E)")); } @Test public void test_t_221958() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_221958/left_TilesetManager_1.22.java src/test/resources/examples/t_221958/right_TilesetManager_1.23.java File fl = new File("src/test/resources/examples/t_221958/left_TilesetManager_1.22.java"); File fr = new File("src/test/resources/examples/t_221958/right_TilesetManager_1.23.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Literal", "null")); CtElement elem = actions.get(0).getNode(); assertNotNull(elem); assertNotNull(elem.getParent(CtReturn.class)); } @Test public void test_t_222361() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_222361/left_CommonSettingsDialog_1.22.java src/test/resources/examples/t_222361/right_CommonSettingsDialog_1.23.java File fl = new File("src/test/resources/examples/t_222361/left_CommonSettingsDialog_1.22.java"); File fr = new File("src/test/resources/examples/t_222361/right_CommonSettingsDialog_1.23.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\"By holding down CTL and dragging.\"")); } @Test public void test_t_222399() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_222399/left_TdbFile_1.7.java src/test/resources/examples/t_222399/right_TdbFile_1.8.java File fl = new File("src/test/resources/examples/t_222399/left_TdbFile_1.7.java"); File fr = new File("src/test/resources/examples/t_222399/right_TdbFile_1.8.java"); Diff result = diff.compare(fl,fr); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtIf); assertEquals(229,ancestor.getPosition().getLine()); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(3, actions.size()); assertEquals(229,ancestor.getPosition().getLine()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "#equals(java.lang.String)")); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "NE")); assertTrue(result.containsOperation(OperationKind.Move, "Invocation", "#equals(java.lang.String)")); // updated the if condition CtElement elem = actions.get(0).getNode(); assertNotNull(elem); assertNotNull(elem.getParent(CtIf.class)); } @Test public void test_t_222884() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_222884/left_MechView_1.21.java src/test/resources/examples/t_222884/right_MechView_1.22.java File fl = new File("src/test/resources/examples/t_222884/left_MechView_1.21.java"); File fr = new File("src/test/resources/examples/t_222884/right_MechView_1.22.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation", "#append(java.lang.String)")); } @Test public void test_t_222894() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_222894/left_Client_1.150.java src/test/resources/examples/t_222894/right_Client_1.151.java File fl = new File("src/test/resources/examples/t_222894/left_Client_1.150.java"); File fr = new File("src/test/resources/examples/t_222894/right_Client_1.151.java"); Diff result = diff.compare(fl,fr); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtIf); result.getRootOperations(); result.debugInformation(); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "AND")); // TODO there is a move that is not detected but should be // assertTrue(result.containsOperation(OperationKind.Move, VariableRead", "Settings.keepServerlog")); // this is the case if gumtree.match.gt.minh" = "0" (but bad for other tests) } @Test public void test_t_223054() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_223054/left_GameEvent_1.2.java src/test/resources/examples/t_223054/right_GameEvent_1.3.java File fl = new File("src/test/resources/examples/t_223054/left_GameEvent_1.2.java"); File fr = new File("src/test/resources/examples/t_223054/right_GameEvent_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Field", "GAME_NEW_ATTACK")); } @Test public void test_t_223056() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_223056/left_Server_1.646.java src/test/resources/examples/t_223056/right_Server_1.647.java File fl = new File("src/test/resources/examples/t_223056/left_Server_1.646.java"); File fr = new File("src/test/resources/examples/t_223056/right_Server_1.647.java"); Diff result = diff.compare(fl,fr); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtClass); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 2); assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\" \"")); assertTrue(result.containsOperation(OperationKind.Update, "Literal","\" \\n\"")); } @Test public void test_t_223118() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_223118/left_TestBot_1.48.java src/test/resources/examples/t_223118/right_TestBot_1.49.java File fl = new File("src/test/resources/examples/t_223118/left_TestBot_1.48.java"); File fr = new File("src/test/resources/examples/t_223118/right_TestBot_1.49.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation", "megamek.client.bot.CEntity#refresh()")); } @Test public void test_t_223454() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_223454/left_EntityListFile_1.17.java src/test/resources/examples/t_223454/right_EntityListFile_1.18.java File fl = new File("src/test/resources/examples/t_223454/left_EntityListFile_1.17.java"); File fr = new File("src/test/resources/examples/t_223454/right_EntityListFile_1.18.java"); Diff result = diff.compare(fl,fr); result.getRootOperations(); result.debugInformation(); List<Operation> actions = result.getRootOperations(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "ConstructorCall")); } @Test public void test_t_223542() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_223542/left_BoardView1_1.214.java src/test/resources/examples/t_223542/right_BoardView1_1.215.java File fl = new File("src/test/resources/examples/t_223542/left_BoardView1_1.214.java"); File fr = new File("src/test/resources/examples/t_223542/right_BoardView1_1.215.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "FieldRead", "MOVE_VTOL_RUN")); } @Test public void test_t_224512() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224512/left_Server_1.925.java src/test/resources/examples/t_224512/right_Server_1.926.java File fl = new File("src/test/resources/examples/t_224512/left_Server_1.925.java"); File fr = new File("src/test/resources/examples/t_224512/right_Server_1.926.java"); Diff result = diff.compare(fl,fr); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtBinaryOperator); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 2); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "AND")); assertTrue(result.containsOperation(OperationKind.Move, "BinaryOperator", "AND")); } @Test public void test_t_224542() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224542/left_TestBot_1.75.java src/test/resources/examples/t_224542/right_TestBot_1.76.java File fl = new File("src/test/resources/examples/t_224542/left_TestBot_1.75.java"); File fr = new File("src/test/resources/examples/t_224542/right_TestBot_1.76.java"); Diff result = diff.compare(fl,fr); result.debugInformation(); CtElement ancestor = result.commonAncestor(); assertTrue(ancestor instanceof CtInvocation); assertEquals("println", ((CtInvocation)ancestor).getExecutable().getSimpleName()); assertEquals(344,ancestor.getPosition().getLine()); List<Operation> actions = result.getRootOperations(); assertTrue(actions.size() >= 3); assertTrue(result.containsOperation(OperationKind.Delete, "Invocation", "java.lang.String#format(java.lang.String,java.lang.Object[])")); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "PLUS")); // the move can be either getEntity or getShortName assertTrue(result.containsOperation(OperationKind.Move, "Invocation")); assertEquals(344, result.changedNode(MoveOperation.class).getPosition().getLine()); } @Test public void test_t_224766() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224766/left_SegmentTermEnum_1.1.java src/test/resources/examples/t_224766/right_SegmentTermEnum_1.2.java File fl = new File("src/test/resources/examples/t_224766/left_SegmentTermEnum_1.1.java"); File fr = new File("src/test/resources/examples/t_224766/right_SegmentTermEnum_1.2.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 2); assertTrue(result.containsOperation(OperationKind.Insert, "If")); assertTrue(result.containsOperation(OperationKind.Move, "Invocation", "org.apache.lucene.index.SegmentTermEnum#growBuffer(int)")); } @Test public void test_t_224771() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224771/left_IndexWriter_1.2.java src/test/resources/examples/t_224771/right_IndexWriter_1.3.java File fl = new File("src/test/resources/examples/t_224771/left_IndexWriter_1.2.java"); File fr = new File("src/test/resources/examples/t_224771/right_IndexWriter_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 2); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "OR")); assertTrue(result.containsOperation(OperationKind.Move, "Invocation", "org.apache.lucene.index.SegmentReader#hasDeletions()")); } @Test public void test_t_224798() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224798/left_SegmentsReader_1.4.java src/test/resources/examples/t_224798/right_SegmentsReader_1.5.java File fl = new File("src/test/resources/examples/t_224798/left_SegmentsReader_1.4.java"); File fr = new File("src/test/resources/examples/t_224798/right_SegmentsReader_1.5.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "#delete(int)" )); } @Test public void test_t_224834() throws Exception{ // wonderful example where the text diff is impossible to comprehend AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224834/left_TestPriorityQueue_1.2.java src/test/resources/examples/t_224834/right_TestPriorityQueue_1.3.java File fl = new File("src/test/resources/examples/t_224834/left_TestPriorityQueue_1.2.java"); File fr = new File("src/test/resources/examples/t_224834/right_TestPriorityQueue_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Method", "testClear")); } @Test public void test_t_224863() throws Exception { AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224863/left_PhraseQuery_1.4.java src/test/resources/examples/t_224863/right_PhraseQuery_1.5.java File fl = new File("src/test/resources/examples/t_224863/left_PhraseQuery_1.4.java"); File fr = new File("src/test/resources/examples/t_224863/right_PhraseQuery_1.5.java"); Diff result = diff.compare(fl, fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Insert, "Assignment")); // the change is in the block that starts at line110 assertEquals(110, result.changedNode().getPosition().getLine()); // and the new element is at line 111 assertEquals(111, actions.get(0).getNode().getPosition().getLine()); } @Test public void test_t_224882() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224882/left_Token_1.3.java src/test/resources/examples/t_224882/right_Token_1.4.java File fl = new File("src/test/resources/examples/t_224882/left_Token_1.3.java"); File fr = new File("src/test/resources/examples/t_224882/right_Token_1.4.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\"Increment must be positive: \"")); } @Test public void test_t_224890() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_224890/left_DateField_1.4.java src/test/resources/examples/t_224890/right_DateField_1.5.java File fl = new File("src/test/resources/examples/t_224890/left_DateField_1.4.java"); File fr = new File("src/test/resources/examples/t_224890/right_DateField_1.5.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(2, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Literal", "' '")); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "java.lang.StringBuffer#insert(int,char)")); } /** * This test is ignored because we cannot replicate easily its behaviour. * Its proper behaviour should be to return only one Update action as specified in the assert. * However in some conditions we obtained two actions: a Delete of the method and an Insert. * When studying that bug we discover that: * - it's only reproducible when executing the entire test suite * - it's not reproducible when using a Java debugger even without any breakpoint * - it appears when changing the version of Spoon but without clear relation of what changes * * Given those information we think that the bug might be related with some optimization done in JVM or with the order of loading classes. */ @Ignore @Test public void test_t_225008() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225008/left_Similarity_1.9.java src/test/resources/examples/t_225008/right_Similarity_1.10.java File fl = new File("src/test/resources/examples/t_225008/left_Similarity_1.9.java"); File fr = new File("src/test/resources/examples/t_225008/right_Similarity_1.10.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); StringBuilder stringBuilder = new StringBuilder(); for (Operation action : actions) { stringBuilder.append(action.toString()); stringBuilder.append("\n"); } assertEquals("Actions: "+stringBuilder.toString(), 1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Modifier", "protected")); } @Test public void test_t_225073() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225073/left_IndexWriter_1.21.java src/test/resources/examples/t_225073/right_IndexWriter_1.22.java File fl = new File("src/test/resources/examples/t_225073/left_IndexWriter_1.21.java"); File fr = new File("src/test/resources/examples/t_225073/right_IndexWriter_1.22.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "NewClass")); // the change is in a constructor call assertTrue(result.changedNode() instanceof CtNewClass); } @Test public void test_t_286696() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_286696/left_IrmiPRODelegate_1.2.java src/test/resources/examples/t_286696/right_IrmiPRODelegate_1.3.java File fl = new File("src/test/resources/examples/t_286696/left_IrmiPRODelegate_1.2.java"); File fr = new File("src/test/resources/examples/t_286696/right_IrmiPRODelegate_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(actions.size(), 1); assertTrue(result.containsOperation(OperationKind.Update, "FieldRead", "SERVER_JRMP_PORT")); } @Test public void test_t_225106() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225106/left_SegmentTermDocs_1.6.java src/test/resources/examples/t_225106/right_SegmentTermDocs_1.7.java File fl = new File("src/test/resources/examples/t_225106/left_SegmentTermDocs_1.6.java"); File fr = new File("src/test/resources/examples/t_225106/right_SegmentTermDocs_1.7.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "BinaryOperator", "GT")); } @Test public void test_t_213712() throws Exception{ // works with gumtree.match.gt.minh = 1 (and not the default 2) AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_213712/left_ActionAddSignalsToSignalEvent_1.2.java src/test/resources/examples/t_213712/right_ActionAddSignalsToSignalEvent_1.3.java File fl = new File("src/test/resources/examples/t_213712/left_ActionAddSignalsToSignalEvent_1.2.java"); File fr = new File("src/test/resources/examples/t_213712/right_ActionAddSignalsToSignalEvent_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Field", "serialVersionUID")); // in Spoon 5.4 implicit blocks are made explicit // so we don't detect them anymore //assertTrue(result.containsOperation(OperationKind.Insert, "Block")); } @Test public void test_t_225225() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225225/left_TestSpans_1.3.java src/test/resources/examples/t_225225/right_TestSpans_1.4.java File fl = new File("src/test/resources/examples/t_225225/left_TestSpans_1.3.java"); File fr = new File("src/test/resources/examples/t_225225/right_TestSpans_1.4.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "LocalVariable", "buffer")); } @Test public void test_t_225247() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225247/left_BooleanScorer_1.10.java src/test/resources/examples/t_225247/right_BooleanScorer_1.11.java File fl = new File("src/test/resources/examples/t_225247/left_BooleanScorer_1.10.java"); File fr = new File("src/test/resources/examples/t_225247/right_BooleanScorer_1.11.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "BinaryOperator", "BITOR")); } @Test public void test_t_225262() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225262/left_FieldInfos_1.9.java src/test/resources/examples/t_225262/right_FieldInfos_1.10.java File fl = new File("src/test/resources/examples/t_225262/left_FieldInfos_1.9.java"); File fr = new File("src/test/resources/examples/t_225262/right_FieldInfos_1.10.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Break" )); // in Spoon 5.4 implicit blocks are made explicit // assertTrue(result.containsOperation(OperationKind.Insert, "Block")); } @Test public void test_t_225391() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225391/left_IndexHTML_1.4.java src/test/resources/examples/t_225391/right_IndexHTML_1.5.java File fl = new File("src/test/resources/examples/t_225391/left_IndexHTML_1.4.java"); File fr = new File("src/test/resources/examples/t_225391/right_IndexHTML_1.5.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(3, actions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "Assignment")); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation", "org.apache.lucene.index.IndexWriter#setMaxFieldLength(int)" )); assertTrue(result.containsOperation(OperationKind.Move, "FieldRead", "writer" )); } @Test public void test_t_225414() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225414/left_IndexWriter_1.41.java src/test/resources/examples/t_225414/right_IndexWriter_1.42.java File fl = new File("src/test/resources/examples/t_225414/left_IndexWriter_1.41.java"); File fr = new File("src/test/resources/examples/t_225414/right_IndexWriter_1.42.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "java.lang.Throwable#getMessage()")); } @Test public void test_t_225434() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225434/left_BufferedIndexInput_1.2.java src/test/resources/examples/t_225434/right_BufferedIndexInput_1.3.java File fl = new File("src/test/resources/examples/t_225434/left_BufferedIndexInput_1.2.java"); File fr = new File("src/test/resources/examples/t_225434/right_BufferedIndexInput_1.3.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "BinaryOperator", "EQ")); } @Test public void test_t_225525() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225525/left_Module_1.6.java src/test/resources/examples/t_225525/right_Module_1.7.java File fl = new File("src/test/resources/examples/t_225525/left_Module_1.6.java"); File fr = new File("src/test/resources/examples/t_225525/right_Module_1.7.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Method", "getAttributes" )); } @Test public void test_t_225724() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225724/left_ScarabRequestTool_1.36.java src/test/resources/examples/t_225724/right_ScarabRequestTool_1.37.java File fl = new File("src/test/resources/examples/t_225724/left_ScarabRequestTool_1.36.java"); File fr = new File("src/test/resources/examples/t_225724/right_ScarabRequestTool_1.37.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); //result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "org.apache.turbine.util.Log#error(java.lang.String,java.lang.Exception)")); } @Test public void test_t_225893() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_225893/left_RQueryUser_1.1.java src/test/resources/examples/t_225893/right_RQueryUser_1.2.java File fl = new File("src/test/resources/examples/t_225893/left_RQueryUser_1.1.java"); File fr = new File("src/test/resources/examples/t_225893/right_RQueryUser_1.2.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Method", "delete")); } @Test public void test_t_226145() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226145/left_ScarabRequestTool_1.90.java src/test/resources/examples/t_226145/right_ScarabRequestTool_1.91.java File fl = new File("src/test/resources/examples/t_226145/left_ScarabRequestTool_1.90.java"); File fr = new File("src/test/resources/examples/t_226145/right_ScarabRequestTool_1.91.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Method", "getIssueByUniqueId")); } @Test public void test_t_226330() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226330/left_ActivityRule_1.4.java src/test/resources/examples/t_226330/right_ActivityRule_1.5.java File fl = new File("src/test/resources/examples/t_226330/left_ActivityRule_1.4.java"); File fr = new File("src/test/resources/examples/t_226330/right_ActivityRule_1.5.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "TypeAccess", "DBImport.STATE_DB_INSERTION")); } @Test public void test_t_226480() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226480/left_ScarabRequestTool_1.113.java src/test/resources/examples/t_226480/right_ScarabRequestTool_1.114.java File fl = new File("src/test/resources/examples/t_226480/left_ScarabRequestTool_1.113.java"); File fr = new File("src/test/resources/examples/t_226480/right_ScarabRequestTool_1.114.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation", "org.apache.turbine.Log#debug(java.lang.String)")); } @Test public void test_t_226555() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226555/left_Attachment_1.24.java src/test/resources/examples/t_226555/right_Attachment_1.25.java File fl = new File("src/test/resources/examples/t_226555/left_Attachment_1.24.java"); File fr = new File("src/test/resources/examples/t_226555/right_Attachment_1.25.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); // root actions assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "java.lang.String#lastIndexOf(java.lang.String)")); // low level actions assertTrue(result.containsOperations(result.getAllOperations(), OperationKind.Delete, "FieldRead", "separator")); assertTrue(result.containsOperations(result.getAllOperations(), OperationKind.Insert, "Literal", "'/'" )); } @Test public void test_t_226622() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226622/left_AttributeValue_1.49.java src/test/resources/examples/t_226622/right_AttributeValue_1.50.java File fl = new File("src/test/resources/examples/t_226622/left_AttributeValue_1.49.java"); File fr = new File("src/test/resources/examples/t_226622/right_AttributeValue_1.50.java"); Diff result = diff.compare(fl,fr); result.getRootOperations(); result.debugInformation(); // no assert on number of actions because a move migt be detected (TODO?) assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "AND")); } @Test public void test_t_226685() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226685/left_ResetCacheValve_1.1.java src/test/resources/examples/t_226685/right_ResetCacheValve_1.2.java File fl = new File("src/test/resources/examples/t_226685/left_ResetCacheValve_1.1.java"); File fr = new File("src/test/resources/examples/t_226685/right_ResetCacheValve_1.2.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "Invocation", "java.io.PrintStream#println(java.lang.String)")); } @Test public void test_t_226926() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226926/left_ScarabUserManager_1.4.java src/test/resources/examples/t_226926/right_ScarabUserManager_1.5.java File fl = new File("src/test/resources/examples/t_226926/left_ScarabUserManager_1.4.java"); File fr = new File("src/test/resources/examples/t_226926/right_ScarabUserManager_1.5.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Modifier", "public")); } @Test public void test_t_226963() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_226963/left_Issue_1.140.java src/test/resources/examples/t_226963/right_Issue_1.141.java File fl = new File("src/test/resources/examples/t_226963/left_Issue_1.140.java"); File fr = new File("src/test/resources/examples/t_226963/right_Issue_1.141.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "#addAscendingOrderByColumn()" )); } @Test public void test_t_227005() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_227005/left_AttributeValue_1.56.java src/test/resources/examples/t_227005/right_AttributeValue_1.57.java File fl = new File("src/test/resources/examples/t_227005/left_AttributeValue_1.56.java"); File fr = new File("src/test/resources/examples/t_227005/right_AttributeValue_1.57.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(2, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "BinaryOperator", "AND")); assertTrue(result.containsOperation(OperationKind.Move, "BinaryOperator", "AND")); } @Test public void test_t_227130() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_227130/left_Transaction_1.37.java src/test/resources/examples/t_227130/right_Transaction_1.38.java File fl = new File("src/test/resources/examples/t_227130/left_Transaction_1.37.java"); File fr = new File("src/test/resources/examples/t_227130/right_Transaction_1.38.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation( OperationKind.Insert, "Method", "create")); } @Test public void test_t_227368() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_227368/left_IssueTemplateInfo_1.12.java src/test/resources/examples/t_227368/right_IssueTemplateInfo_1.13.java File fl = new File("src/test/resources/examples/t_227368/left_IssueTemplateInfo_1.12.java"); File fr = new File("src/test/resources/examples/t_227368/right_IssueTemplateInfo_1.13.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(2, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Invocation", "org.tigris.scarab.util.Email#sendEmail(org.apache.fulcrum.template.TemplateContext,org.tigris.scarab.om.Module,<unknown>,<unknown>,java.lang.String,java.lang.String)")); // one parameter is moved to another argument assertTrue(result.containsOperation(OperationKind.Move, "Invocation")); } @Test public void test_t_227811() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_227811/left_RModuleIssueType_1.24.java src/test/resources/examples/t_227811/right_RModuleIssueType_1.25.java File fl = new File("src/test/resources/examples/t_227811/left_RModuleIssueType_1.24.java"); File fr = new File("src/test/resources/examples/t_227811/right_RModuleIssueType_1.25.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Invocation", "#setDisplayDescription(java.lang.String)" )); } @Test public void test_t_227985() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_227985/left_IssueSearch_1.65.java src/test/resources/examples/t_227985/right_IssueSearch_1.66.java File fl = new File("src/test/resources/examples/t_227985/left_IssueSearch_1.65.java"); File fr = new File("src/test/resources/examples/t_227985/right_IssueSearch_1.66.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "Assignment")); } @Test public void test_t_228064() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_228064/left_ModuleManager_1.21.java src/test/resources/examples/t_228064/right_ModuleManager_1.22.java File fl = new File("src/test/resources/examples/t_228064/left_ModuleManager_1.21.java"); File fr = new File("src/test/resources/examples/t_228064/right_ModuleManager_1.22.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Modifier", "public")); } @Test public void test_t_228325() throws Exception{ AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_228325/left_ForgotPassword_1.10.java src/test/resources/examples/t_228325/right_ForgotPassword_1.11.java File fl = new File("src/test/resources/examples/t_228325/left_ForgotPassword_1.10.java"); File fr = new File("src/test/resources/examples/t_228325/right_ForgotPassword_1.11.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "Literal", "\"ForgotPassword.vm\"")); } @Test public void test_t_228643() throws Exception{ // works only if AbstractBottomUpMatcher.SIZE_THRESHOLD >= 7 //AbstractBottomUpMatcher.SIZE_THRESHOLD = 10; AstComparator diff = new AstComparator(); // meld src/test/resources/examples/t_228643/left_ScopePeer_1.3.java src/test/resources/examples/t_228643/right_ScopePeer_1.4.java File fl = new File("src/test/resources/examples/t_228643/left_ScopePeer_1.3.java"); File fr = new File("src/test/resources/examples/t_228643/right_ScopePeer_1.4.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(1, actions.size()); assertTrue(result.containsOperation(OperationKind.Update, "ConstructorCall", "org.apache.torque.util.Criteria()")); } @Test public void test_issue31() throws Exception{ // the cause of this bug is the value of gumtree.match.bu.sim set in AstComparator // with gumtree.match.bu.sim=0.4 (the previous value), the block of the whole method (starting line 408) was not mapped, and this created a lot of spurious moves // with gumtree.match.bu.sim=0.6 (the new default value in the commit to fix the bug), the block of the whole method is mapped, and the diff becomes perfect AstComparator diff = new AstComparator(); // meld src/test/resources/examples/issue31/original.java src/test/resources/examples/issue31/patched.java File fl = new File("src/test/resources/examples/issue31/original.java"); File fr = new File("src/test/resources/examples/issue31/patched.java"); Diff result = diff.compare(fl,fr); List<Operation> rootActions = result.getRootOperations(); //result.debugInformation(); System.out.println("root: "+result.getRootOperations().size()); for(Operation o: result.getRootOperations()) { System.out.println(o.getClass().getSimpleName()+ " " + o.getSrcNode().getClass().getSimpleName()+ " " + o.getSrcNode().getPosition().getLine()); } System.out.println("all: "+result.getAllOperations().size()); assertEquals(2, rootActions.size()); assertTrue(result.containsOperation(OperationKind.Delete, "If", "if")); assertTrue(result.containsOperation(OperationKind.Move, "If")); // the else if moved one level up } public void test_chart18() throws Exception{ AstComparator diff = new AstComparator(); File fl = new File("src/test/resources/examples/chart18/DefaultKeyedValues2D.java"); File fr = new File("src/test/resources/examples/chart18/new_DefaultKeyedValues2D.java"); Diff result = diff.compare(fl,fr); List<Operation> actions = result.getRootOperations(); result.debugInformation(); assertEquals(5, actions.size()); assertTrue(result.containsOperation(OperationKind.Insert, "LocalVariable", "index")); assertTrue(result.containsOperation(OperationKind.Insert, "If", "if")); } }
package seedu.geekeep.model.task; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class TitleTest { @Test public void isValidTitle() { // invalid title assertFalse(Title.isValidTitle("")); // empty string assertFalse(Title.isValidTitle(" ")); // spaces only assertFalse(Title.isValidTitle("^")); // only non-alphanumeric characters assertFalse(Title.isValidTitle("peter*")); // contains non-alphanumeric characters // valid title assertTrue(Title.isValidTitle("peter jack")); // alphabets only assertTrue(Title.isValidTitle("12345")); // numbers only assertTrue(Title.isValidTitle("peter the 2nd")); // alphanumeric characters assertTrue(Title.isValidTitle("Capital Tan")); // with capital letters assertTrue(Title.isValidTitle("David Roger Jackson Ray Jr 2nd")); // long names } }
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * @author * Holger Rehn */ public class StatementTest extends TestBase { public StatementTest( String name ) { super( name ); } /** * Test for bug #544, getMoreResults() does not work with insert triggers. */ public void testBug544() throws Exception { dropTrigger( "Bug544T" ); dropTable( "Bug544a" ); dropTable( "Bug544b" ); Statement sta = con.createStatement(); sta.executeUpdate( "create table Bug544a(A int, B int identity not null)" ); sta.executeUpdate( "create table Bug544b(A int)" ); // insert a row to bump up the identity value sta.execute( "insert into Bug544a values( 9 )" ); // create insert trigger sta.executeUpdate( "create trigger Bug544T on Bug544a for insert as begin insert into Bug544b values (12) end" ); // insert data to fire the trigger sta.execute( "insert into Bug544a values( 1 ) select @@identity" ); // dumpAll( sta ); // check update counts assertEquals( 1, sta.getUpdateCount() ); // original insert assertFalse( sta.getMoreResults() ); assertEquals( 1, sta.getUpdateCount() ); // insert executed by the trigger assertTrue( sta.getMoreResults() ); ResultSet res = sta.getResultSet(); // result of "select @@identity" assertTrue( res.next() ); assertEquals( 2, res.getInt( 1 ) ); // the generated value assertFalse( res.next() ); // check the target table res = sta.executeQuery( "select * from Bug544b" ); assertTrue( res.next() ); assertEquals( 12, res.getInt( 1 ) ); assertFalse( res.next() ); } /** * Test for bug #500, Statement.execute() raises executeQuery() exception if * using cursors (useCursors=true) and SHOWPLAN_ALL is set to ON. */ public void testBug500() throws Exception { Properties override = new Properties(); override.put( "useCursors", "true" ); Connection connection = getConnection( override ); Statement stmt = connection.createStatement(); stmt.executeUpdate( "create table #Bug500 (A int)" ); for( int i = 0; i < 10; i ++ ) { stmt.executeUpdate( "insert into #Bug500 values(" + i + ")" ); } stmt.executeUpdate( "set SHOWPLAN_ALL on" ); // or stmt.execute( "set SHOWPLAN_ALL on" ); - doesn't matters stmt.execute( "select top 5 * from #Bug500" ); dumpAll( stmt ); // stmt.execute( "select top 5 * from #Bug500" ); // ResultSet rs = stmt.getResultSet(); } /** * Regression test for bug #528, ResultSet not getting populated correctly * with autogenerated keys. */ public void testBug528() throws Exception { Statement sta = con.createStatement(); sta.executeUpdate( "create table #Bug528 (A int identity, B varchar(10))" ); boolean result = sta.execute( "insert into #Bug528(B) values ('test') " + // Update Count: 1 "insert into #Bug528(B) values ('test') " + // Update Count: 1 "select * from #Bug528", // ResultSet: [1, test] [2, test] Statement.RETURN_GENERATED_KEYS ); // Generated Keys: 1,2 // dumpAll( sta ); assertFalse( result ); // first is an update count for 1st insert assertEquals( 1, sta.getUpdateCount() ); // check update count assertFalse( sta.getMoreResults() ); // next is an update count for 2nd insert assertEquals( 1, sta.getUpdateCount() ); // check update count assertTrue( sta.getMoreResults() ); // resultset generated by select (this used to fail) // get and check resultset ResultSet res = sta.getResultSet(); assertTrue( res.next() ); assertEquals( 1, res.getInt( 1 ) ); assertEquals( "test", res.getString( 2 ) ); assertTrue( res.next() ); assertEquals( 2, res.getInt( 1 ) ); assertEquals( "test", res.getString( 2 ) ); assertFalse( res.next() ); // now check generated keys res = sta.getGeneratedKeys(); // FIXME: the driver is not yet able to return generated keys for anything but the last update // assertTrue( res.next() ); // assertEquals( 1, res.getInt( 1 ) ); assertTrue( res.next() ); assertEquals( 2, res.getInt( 1 ) ); assertFalse( res.next() ); sta.close(); } /** * Test for bug #559, unique constraint violation error hidden by an internal * jTDS error. */ public void testBug559() throws Exception { Statement st = con.createStatement(); st.executeUpdate( "create table #Bug559 (A int, unique (A))" ); try { st.executeUpdate( "select 1;insert into #Bug559 values( 1 );insert into #Bug559 values( 1 )" ); fail(); } catch( SQLException e ) { // expected, executeUpdate() cannot return a resultset assertTrue( e.getMessage().toLowerCase().contains( "executeupdate" ) ); } st.close(); } /** * Test for bug #609, slow finalization in {@link SharedSocket#closeStream()} * can block JVM finalizer thread or cause OOM errors. */ public void testBug609() throws Exception { final int STATEMENTS = 50000; final int THREADS = 10; final Connection connection = con; final boolean[] running = new boolean[] { true }; List block = new ArrayList( 1000 ); try { while( true ) { block.add( new byte[32*1024*1024] ); System.gc(); } } catch( OutOfMemoryError oome ) { block.remove( block.size() - 1 ); } System.gc(); System.out.println( "free memory: " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + " MB" ); Statement sta = connection.createStatement(); sta.executeUpdate( "create table #bug609( A int primary key, B varchar(max) )" ); sta.close(); Thread[] threads = new Thread[THREADS]; // start threads that keeps sending data to block VirtualSocket table in SharedSocket as much as possible for( int t = 0; t < threads.length; t ++ ) { final int i = t; threads[t] = new Thread() { public void run() { try { Statement sta = connection.createStatement(); sta.executeUpdate( "insert into #bug609 values( " + i + ", 'nix' )" ); String value = "BIGVAL"; while( value.length() < 64 * 1024 ) { value += value + "BIGVAL"; } String sql = "update #bug609 set B = '" + value + "' where A = " + i; while( running[0] ) { sta.executeUpdate( sql ); } sta.close(); } catch( SQLException s ) { // test stopped, connection is closed } catch( Throwable t ) { t.printStackTrace(); } } }; threads[t].setPriority( Thread.MIN_PRIORITY ); threads[t].start(); } int stats = 0; long start = System.currentTimeMillis(); try { // buffer some statements that can later be closed together, otherwise // the connection's TdsCore cache would prevent the TdsCore from being // closed (and SharedSocket.closeStream to be called) most of the time Statement[] buffered = new Statement[2500]; for( ; stats < STATEMENTS; stats ++ ) { int r = stats % buffered.length; buffered[r] = con.createStatement(); if( r == buffered.length - 1 ) { for( int c = 0; c < buffered.length; c ++ ) { buffered[c] = null; } System.out.println( stats + 1 ); } } } catch( OutOfMemoryError oome ) { block = null; System.gc(); fail( "OOM after " + (System.currentTimeMillis() - start) + " ms, " + stats + " statements created successfully" ); } long elapsed = System.currentTimeMillis() - start; System.out.println( "time: " + elapsed + " ms" ); assertTrue( elapsed < 10000 ); // stop threads running[0] = false; for( int t = 0; t < threads.length; t ++ ) { threads[t].join(); } } /** * Test for bug #473, Statement.setMaxRows() also effects INSERT, UPDATE, * DELETE and SELECT INTO. */ public void testBug473() throws Exception { Statement sta = con.createStatement(); // create test table and fill with data sta.executeUpdate( "create table #Bug473( X int )" ); sta.executeUpdate( "insert into #Bug473 values( 1 )" ); sta.executeUpdate( "insert into #Bug473 values( 2 )" ); // copy all data (maxRows shouldn't have any effect) sta.setMaxRows( 1 ); sta.executeUpdate( "select * into #copy from #Bug473" ); // ensure all table data has been copied sta.setMaxRows( 0 ); ResultSet res = sta.executeQuery( "select * from #copy" ); assertTrue ( res.next() ); assertTrue ( res.next() ); assertFalse( res.next() ); res.close(); sta.close(); } /** * Test for bug #635, select from a view with order by clause doesn't work if * correctly if using Statement.setMaxRows(). */ public void testBug635() throws Exception { final int[] data = new int[] { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 }; dropTable( "Bug635T" ); dropView ( "Bug635V" ); Statement sta = con.createStatement(); sta.setMaxRows( 7 ); sta.executeUpdate( "create table Bug635T( X int )" ); sta.executeUpdate( "create view Bug635V as select * from Bug635T" ); for( int i = 0; i < data.length; i ++ ) { sta.executeUpdate( "insert into Bug635T values( " + data[i] + " )" ); } ResultSet res = sta.executeQuery( "select X from Bug635V order by X" ); for( int i = 1; i <= 7; i ++ ) { assertTrue( res.next() ); assertEquals( i, res.getInt( 1 ) ); } res.close(); sta.close(); } /** * Test for bug #624, full text search causes connection reset when connected * to Microsoft SQL Server 2008. */ // TODO: test CONTAINSTABLE, FREETEXT, FREETEXTTABLE public void testFullTextSearch() throws Exception { // cleanup dropTable( "Bug624" ); dropDatabase( "Bug624DB" ); // create DB Statement stmt = con.createStatement(); stmt.executeUpdate( "create database Bug624DB" ); stmt.executeUpdate( "use Bug624DB" ); // create table and fulltext index stmt.executeUpdate( "create fulltext catalog FTS_C as default" ); stmt.executeUpdate( "create table Bug624 ( ID int primary key, A varchar( 100 ) )" ); ResultSet res = stmt.executeQuery( "select name from sysindexes where object_id( 'Bug624' ) = id" ); assertTrue( res.next() ); String pk = res.getString( 1 ); assertFalse( res.next() ); res.close(); stmt.executeUpdate( "create fulltext index on Bug624( A ) key index " + pk ); // insert test data assertEquals( 1, stmt.executeUpdate( "insert into Bug624 values( 0, 'Strange Axolotl, that!' )" ) ); // wait for the index to be build for( boolean indexed = false; ! indexed; ) { res = stmt.executeQuery( "select FULLTEXTCATALOGPROPERTY( 'FTS_C', 'PopulateStatus' )" ); assertTrue( res.next() ); indexed = res.getInt( 1 ) == 0; res.close(); Thread.sleep( 10 ); } // query table using CONTAINS PreparedStatement ps = con.prepareStatement( "select * from Bug624 where contains( A, ? )" ); ps.setString( 1, "Axolotl" ); res = ps.executeQuery(); assertTrue( res.next() ); assertEquals( 0, res.getInt( 1 ) ); assertEquals( "Strange Axolotl, that!", res.getString( 2 ) ); } /** * Test for computed results, bug #678. */ public void testComputeClause() throws Exception { final int VALUES = 150; Statement sta = con.createStatement(); sta.executeUpdate( "create table #Bug678( X int, A varchar(10), B int, C bigint )" ); for( int i = 0; i < VALUES; i ++ ) { sta.executeUpdate( "insert into #Bug678 values( " + i % Math.max( 1, i / 20 ) + ", 'VAL" + i + "'," + ( VALUES - i ) + ", " + (long)i * Integer.MAX_VALUE + " )" ); } assertTrue( sta.execute( "select * from #Bug678 order by X, A asc compute min( A ), max( A ), min( C ), max( C ), avg( B ), sum( B ), count( A ), count_big( C ) by X" ) ); // expected result groups, each followed by a computed result int[] expected = new int[] { 72, 32, 20, 13, 8, 4, 1 }; for( int i = 0; i < expected.length; i ++ ) { ResultSet res = sta.getResultSet(); // consume rows for( int r = 0; r < expected[i]; r ++ ) { assertTrue( res.next() ); } assertFalse( res.next() ); res.close(); // consume computed result assertTrue( sta.getMoreResults() ); res = sta.getResultSet(); assertTrue( res.next() ); assertEquals( expected[i], res.getInt( 7 ) ); assertFalse( res.next() ); res.close(); // move to next result if any assertEquals( i == expected.length -1 ? false : true, sta.getMoreResults() ); } // no update count expected for MSSQL, Sybase seems to sum up the inserts and computed rows to a total of 157 assertEquals( isMSSQL() ? -1 : 157, sta.getUpdateCount() ); sta.close(); } /** * <p> Test to ensure that single results generated as result of aggregation * operations (COMPUTE clause) can be closed individually without affecting * remaining {@link ResultSet}s. </p> */ public void testCloseComputedResult() throws Exception { Statement sta = con.createStatement(); sta.executeUpdate( "create table #Bug678( NAME varchar(10), CREDITS int )" ); sta.executeUpdate( "insert into #Bug678 values( 'Alf' , 10 )" ); sta.executeUpdate( "insert into #Bug678 values( 'Alf' , 20 )" ); sta.executeUpdate( "insert into #Bug678 values( 'Alf' , 30 )" ); sta.executeUpdate( "insert into #Bug678 values( 'Ronny', 5 )" ); sta.executeUpdate( "insert into #Bug678 values( 'Ronny', 10 )" ); assertTrue( sta.execute( "select * from #Bug678 order by NAME compute sum( CREDITS ) by NAME" ) ); ResultSet res = sta.getResultSet(); // check 1st row of 1st ResultSet assertTrue ( res.next() ); assertEquals( "Alf", res.getString( 1 ) ); assertEquals( 10, res.getInt( 2 ) ); assertTrue ( res.next() ); // close 1st ResultSet res.close(); // 3 ResultSets should be left assertTrue( sta.getMoreResults() ); res = sta.getResultSet(); // close 2nd (computed) ResultSet without processing it res.close(); // 2 ResultSets should be left assertTrue( sta.getMoreResults() ); res = sta.getResultSet(); // check 1st row of 3rd ResultSet assertTrue( res.next() ); assertEquals( "Ronny", res.getString( 1 ) ); assertEquals( 5, res.getInt( 2 ) ); // close 3rd ResultSet res.close(); // 1 ResultSet should be left assertTrue( sta.getMoreResults() ); res = sta.getResultSet(); // check 1st row of 4th (computed) ResultSet assertTrue( res.next() ); assertEquals( 15, res.getInt( 1 ) ); assertFalse( res.next() ); // no ResultSets should be left assertFalse( sta.getMoreResults() ); sta.close(); } public void testConcurrentClose() throws Exception { final int THREADS = 10; final int STATEMENTS = 200; final int RESULTSETS = 100; final List errors = new ArrayList<>(); final Statement[] stm = new Statement[STATEMENTS]; final ResultSet[] res = new ResultSet[STATEMENTS*RESULTSETS]; Connection con = getConnection(); for( int i = 0; i < STATEMENTS; i ++ ) { stm[i] = con.createStatement(); for( int r = 0; r < RESULTSETS; r ++ ) { res[i * RESULTSETS + r] = stm[i].executeQuery( "select 1" ); } } Thread[] threads = new Thread[THREADS]; for( int i = 0; i < THREADS; i ++ ) { threads[i] = new Thread( "closer " + i ) { public void run() { try { for( int i = 0; i < STATEMENTS; i ++ ) { stm[i].close(); } } catch( Exception e ) { synchronized( errors ) { errors.add( e ); } } } }; } for( int i = 0; i < THREADS; i ++ ) { threads[i].start(); } for( int i = 0; i < THREADS; i ++ ) { threads[i].join(); } for( int i = 0; i < errors.size(); i ++ ) { ( (Exception) errors.get( i ) ).printStackTrace(); } assertTrue( errors.toString(), errors.isEmpty() ); } /** * Regression test for bug #677, deadlock in {@link JtdsStatement#close()}. */ public void testCloseDeadlock() throws Exception { final int THREADS = 100; final int STATEMENTS = 1000; final List errors = new ArrayList<>(); Thread[] threads = new Thread[THREADS]; for( int i = 0; i < THREADS; i ++ ) { threads[i] = new Thread( "deadlock " + i ) { public void run() { try { Connection con = getConnection(); final Statement[] stm = new Statement[STATEMENTS]; for( int i = 0; i < STATEMENTS; i ++ ) { stm[i] = con.createStatement(); } new Thread( Thread.currentThread().getName() + " (closer)" ) { public void run() { try { for( int i = 0; i < STATEMENTS; i ++ ) { stm[i].close(); } } catch( SQLException e ) { // statements might already be closed by closing the connection if( ! "HY010".equals( e.getSQLState() ) ) { synchronized( errors ) { errors.add( e ); } } } } }.start(); Thread.sleep( 1 ); con.close(); } catch( Exception e ) { synchronized( errors ) { errors.add( e ); } } } }; } for( int i = 0; i < THREADS; i ++ ) { threads[i].start(); } System.currentTimeMillis(); int running = THREADS; while( running != 0 ) { Thread.sleep( 2500 ); int last = running; running = THREADS; for( int i = 0; i < THREADS; i ++ ) { if( threads[i].getState() == Thread.State.TERMINATED ) { running } } if( running == last ) { // for( int i = 0; i < THREADS; i ++ ) // if( threads[i].getState() != Thread.State.TERMINATED ) // Exception e = new Exception(); // e.setStackTrace( threads[i].getStackTrace() ); // e.printStackTrace(); fail( "deadlock detected, none of the remaining connections closed within 2500 ms" ); } } // for( int i = 0; i < errors.size(); i ++ ) // ( (Exception) errors.get( i ) ).printStackTrace(); assertTrue( errors.toString(), errors.isEmpty() ); } /** * Test for #676, error in multi line comment handling. */ public void testMultiLineComment() throws Exception { Statement st = con.createStatement(); st.executeUpdate( "create table /*/ comment '\"?@[*-} /**/*/ #Bug676a (A int) /* */" ); try { // SQL server stacks, instead of ignoring 'inner comments' st.executeUpdate( "create table #Bug676b (A int)" ); } catch( SQLException e ) { // thrown by jTDS due to unclosed 'inner comment' assertEquals( String.valueOf( 22025 ), e.getSQLState() ); } st.close(); } /** * Test for bug #669, no error if violating unique constraint in update. */ public void testDuplicateKey() throws Exception { Statement st = con.createStatement(); st.executeUpdate( "create table #Bug669 (A int, unique (A))" ); st.executeUpdate( "insert into #Bug669 values( 1 )" ); try { st.executeUpdate( "insert into #Bug669 values( 1 )" ); fail(); } catch( SQLException e ) { // expected, unique constraint violation } try { st.execute( "insert into #Bug669 values( 1 )" ); fail(); } catch( SQLException e ) { // expected, unique constraint violation } st.close(); } /** * <p> Test for bug [1694194], queryTimeout does not work on MSSQL2005 when * property 'useCursors' is set to 'true'. Furthermore, the test also checks * timeout with a query that cannot use a cursor. </p> * * <p> This test requires property 'queryTimeout' to be set to true. </p> */ public void testQueryTimeout() throws Exception { Statement st = con.createStatement(); st.setQueryTimeout( 1 ); st.execute( "create procedure #testTimeout as begin waitfor delay '00:00:30'; select 1; end" ); long start = System.currentTimeMillis(); try { // this query doesn't use a cursor st.executeQuery( "exec #testTimeout" ); fail( "query did not time out" ); } catch( SQLException e ) { assertEquals( "HYT00", e.getSQLState() ); assertEquals( 1000, System.currentTimeMillis() - start, 50 ); } st.execute( "create table #dummy1(A varchar(200))" ); st.execute( "create table #dummy2(B varchar(200))" ); st.execute( "create table #dummy3(C varchar(200))" ); // create test data con.setAutoCommit( false ); for( int i = 0; i < 100; i++ ) { st.execute( "insert into #dummy1 values('" + i + "')" ); st.execute( "insert into #dummy2 values('" + i + "')" ); st.execute( "insert into #dummy3 values('" + i + "')" ); } con.commit(); con.setAutoCommit( true ); start = System.currentTimeMillis(); try { // this query can use a cursor st.executeQuery( "select * from #dummy1, #dummy2, #dummy3 order by A desc, B asc, C desc" ); fail( "query did not time out" ); } catch( SQLException e ) { assertEquals( "HYT00", e.getSQLState() ); assertEquals( 1000, System.currentTimeMillis() - start, 100 ); } st.close(); } }
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.test; import java.sql.*; import java.math.BigDecimal; import java.io.InputStream; import java.util.ArrayList; /** * @version 1.0 */ public class ResultSetTest extends DatabaseTestCase { public ResultSetTest(String name) { super(name); } /** * Test BIT data type. */ public void testGetObject1() throws Exception { boolean data = true; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject1 (data BIT, minval BIT, maxval BIT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject1 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setBoolean(1, data); pstmt.setBoolean(2, false); pstmt.setBoolean(3, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject1"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).byteValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Boolean); assertEquals(true, ((Boolean) tmpData).booleanValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.BIT, resultSetMetaData.getColumnType(1)); assertFalse(rs.getBoolean(2)); assertTrue(rs.getBoolean(3)); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test TINYINT data type. */ public void testGetObject2() throws Exception { byte data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject2 (data TINYINT, minval TINYINT, maxval TINYINT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject2 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setByte(1, data); pstmt.setByte(2, Byte.MIN_VALUE); pstmt.setByte(3, Byte.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject2"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).byteValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Integer); assertEquals(data, ((Integer) tmpData).byteValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.TINYINT, resultSetMetaData.getColumnType(1)); assertEquals(rs.getByte(2), Byte.MIN_VALUE); assertEquals(rs.getByte(3), Byte.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test SMALLINT data type. */ public void testGetObject3() throws Exception { short data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject3 (data SMALLINT, minval SMALLINT, maxval SMALLINT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject3 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setShort(1, data); pstmt.setShort(2, Short.MIN_VALUE); pstmt.setShort(3, Short.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject3"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).shortValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Integer); assertEquals(data, ((Integer) tmpData).shortValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.SMALLINT, resultSetMetaData.getColumnType(1)); assertEquals(rs.getShort(2), Short.MIN_VALUE); assertEquals(rs.getShort(3), Short.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test INT data type. */ public void testGetObject4() throws Exception { int data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject4 (data INT, minval INT, maxval INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject4 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setInt(1, data); pstmt.setInt(2, Integer.MIN_VALUE); pstmt.setInt(3, Integer.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject4"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).intValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof Integer); assertEquals(data, ((Integer) tmpData).intValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.INTEGER, resultSetMetaData.getColumnType(1)); assertEquals(rs.getInt(2), Integer.MIN_VALUE); assertEquals(rs.getInt(3), Integer.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test BIGINT data type. */ public void testGetObject5() throws Exception { long data = 1; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #getObject5 (data DECIMAL(28, 0), minval DECIMAL(28, 0), maxval DECIMAL(28, 0))"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #getObject5 (data, minval, maxval) VALUES (?, ?, ?)"); pstmt.setLong(1, data); pstmt.setLong(2, Long.MIN_VALUE); pstmt.setLong(3, Long.MAX_VALUE); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); ResultSet rs = stmt2.executeQuery("SELECT data, minval, maxval FROM #getObject5"); assertTrue(rs.next()); assertTrue(rs.getBoolean(1)); assertTrue(rs.getByte(1) == 1); assertTrue(rs.getShort(1) == 1); assertTrue(rs.getInt(1) == 1); assertTrue(rs.getLong(1) == 1); assertTrue(rs.getFloat(1) == 1); assertTrue(rs.getDouble(1) == 1); assertTrue(rs.getBigDecimal(1).longValue() == 1); assertEquals("1", rs.getString(1)); Object tmpData = rs.getObject(1); assertTrue(tmpData instanceof BigDecimal); assertEquals(data, ((BigDecimal) tmpData).longValue()); ResultSetMetaData resultSetMetaData = rs.getMetaData(); assertNotNull(resultSetMetaData); assertEquals(Types.DECIMAL, resultSetMetaData.getColumnType(1)); assertEquals(rs.getLong(2), Long.MIN_VALUE); assertEquals(rs.getLong(3), Long.MAX_VALUE); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test for bug [961594] ResultSet. */ public void testResultSetScroll1() throws Exception { int count = 125; Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetScroll1 (data INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetScroll1 (data) VALUES (?)"); for (int i = 1; i <= count; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt2.executeQuery("SELECT data FROM #resultSetScroll1"); assertTrue(rs.last()); assertEquals(count, rs.getRow()); stmt2.close(); rs.close(); } /** * Test for bug [945462] getResultSet() return null if you use scrollable/updatable. */ public void testResultSetScroll2() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetScroll2 (data INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetScroll2 (data) VALUES (?)"); pstmt.setInt(1, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt2.executeQuery("SELECT data FROM #resultSetScroll2"); ResultSet rs = stmt2.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test for bug [1028881] statement.execute() causes wrong ResultSet type. */ public void testResultSetScroll3() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetScroll3 (data INT)"); stmt.execute("CREATE PROCEDURE #procResultSetScroll3 AS SELECT data FROM #resultSetScroll3"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetScroll3 (data) VALUES (?)"); pstmt.setInt(1, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); // Test plain Statement Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); assertTrue("Was expecting a ResultSet", stmt2.execute("SELECT data FROM #resultSetScroll3")); ResultSet rs = stmt2.getResultSet(); assertEquals("ResultSet not scrollable", ResultSet.TYPE_SCROLL_INSENSITIVE, rs.getType()); rs.close(); stmt2.close(); // Test PreparedStatement pstmt = con.prepareStatement("SELECT data FROM #resultSetScroll3", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); assertTrue("Was expecting a ResultSet", pstmt.execute()); rs = pstmt.getResultSet(); assertEquals("ResultSet not scrollable", ResultSet.TYPE_SCROLL_INSENSITIVE, rs.getType()); rs.close(); pstmt.close(); // Test CallableStatement CallableStatement cstmt = con.prepareCall("{call #procResultSetScroll3}", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); assertTrue("Was expecting a ResultSet", cstmt.execute()); rs = cstmt.getResultSet(); assertEquals("ResultSet not scrollable", ResultSet.TYPE_SCROLL_INSENSITIVE, rs.getType()); rs.close(); cstmt.close(); } /** * Test for bug [1008208] 0.9-rc1 updateNull doesn't work. */ public void testResultSetUpdate1() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetUpdate1 (id INT PRIMARY KEY, dsi SMALLINT NULL, di INT NULL)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetUpdate1 (id, dsi, di) VALUES (?, ?, ?)"); pstmt.setInt(1, 1); pstmt.setShort(2, (short) 1); pstmt.setInt(3, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.executeQuery("SELECT id, dsi, di FROM #resultSetUpdate1"); ResultSet rs = stmt.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); rs.updateNull("dsi"); rs.updateNull("di"); rs.updateRow(); rs.moveToInsertRow(); rs.updateInt(1, 2); rs.updateNull("dsi"); rs.updateNull("di"); rs.insertRow(); stmt.close(); rs.close(); stmt = con.createStatement(); stmt.executeQuery("SELECT id, dsi, di FROM #resultSetUpdate1 ORDER BY id"); rs = stmt.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); rs.getShort(2); assertTrue(rs.wasNull()); rs.getInt(3); assertTrue(rs.wasNull()); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); rs.getShort(2); assertTrue(rs.wasNull()); rs.getInt(3); assertTrue(rs.wasNull()); assertFalse(rs.next()); stmt.close(); rs.close(); } /** * Test for bug [1009233] ResultSet getColumnName, getColumnLabel return wrong values */ public void testResultSetColumnName1() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #resultSetCN1 (data INT)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #resultSetCN1 (data) VALUES (?)"); pstmt.setInt(1, 1); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); Statement stmt2 = con.createStatement(); stmt2.executeQuery("SELECT data as test FROM #resultSetCN1"); ResultSet rs = stmt2.getResultSet(); assertNotNull(rs); assertTrue(rs.next()); assertEquals(1, rs.getInt("test")); assertFalse(rs.next()); stmt2.close(); rs.close(); } /** * Test for fixed bugs in ResultSetMetaData: * <ol> * <li>isNullable() always returns columnNoNulls. * <li>isSigned returns true in error for TINYINT columns. * <li>Type names for numeric / decimal have (prec,scale) appended in error. * <li>Type names for auto increment columns do not have "identity" appended. * </ol> * NB: This test assumes getColumnName has been fixed to work as per the suggestion * in bug report [1009233]. * * @throws Exception */ public void testResultSetMetaData() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.execute("CREATE TABLE #TRSMD (id INT IDENTITY NOT NULL, byte TINYINT NOT NULL, num DECIMAL(28,10) NULL)"); ResultSetMetaData rsmd = stmt.executeQuery("SELECT id as idx, byte, num FROM #TRSMD").getMetaData(); assertNotNull(rsmd); // Check id assertEquals("idx", rsmd.getColumnName(1)); // no longer returns base name assertEquals("idx", rsmd.getColumnLabel(1)); assertTrue(rsmd.isAutoIncrement(1)); assertTrue(rsmd.isSigned(1)); assertEquals(ResultSetMetaData.columnNoNulls, rsmd.isNullable(1)); assertEquals("int identity", rsmd.getColumnTypeName(1)); assertEquals(Types.INTEGER, rsmd.getColumnType(1)); // Check byte assertFalse(rsmd.isAutoIncrement(2)); assertFalse(rsmd.isSigned(2)); assertEquals(ResultSetMetaData.columnNoNulls, rsmd.isNullable(2)); assertEquals("tinyint", rsmd.getColumnTypeName(2)); assertEquals(Types.TINYINT, rsmd.getColumnType(2)); // Check num assertFalse(rsmd.isAutoIncrement(3)); assertTrue(rsmd.isSigned(3)); assertEquals(ResultSetMetaData.columnNullable, rsmd.isNullable(3)); assertEquals("decimal", rsmd.getColumnTypeName(3)); assertEquals(Types.DECIMAL, rsmd.getColumnType(3)); stmt.close(); } /** * Test for bug [1022445] Cursor downgrade warning not raised. */ public void testCursorWarning() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TESTCW (id INT PRIMARY KEY, DATA VARCHAR(255))"); stmt.execute("CREATE PROC #SPTESTCW @P0 INT OUTPUT AS SELECT * FROM #TESTCW"); stmt.close(); CallableStatement cstmt = con.prepareCall("{call #SPTESTCW(?)}", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); cstmt.registerOutParameter(1, Types.INTEGER); ResultSet rs = cstmt.executeQuery(); // This should generate a ResultSet type/concurrency downgraded error. assertNotNull(rs.getWarnings()); cstmt.close(); } /** * Test that the cursor fallback logic correctly discriminates between * "real" sql errors and cursor open failures. * <p/> * This illustrates the logic added to fix: * <ol> * <li>[1323363] Deadlock Exception not reported (SQL Server)</li> * <li>[1283472] Unable to cancel statement with cursor resultset</li> * </ol> */ public void testCursorFallback() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // This test should fail on the cursor open but fall back to normal // execution returning two result sets stmt.execute("CREATE PROC #testcursor as SELECT 'data' select 'data2'"); stmt.execute("exec #testcursor"); assertNotNull(stmt.getWarnings()); ResultSet rs = stmt.getResultSet(); assertNotNull(rs); // First result set OK assertTrue(stmt.getMoreResults()); rs = stmt.getResultSet(); assertNotNull(rs); // Second result set OK // This test should fail on the cursor open (because of the for browse) // but fall back to normal execution returning a single result set rs = stmt.executeQuery("SELECT description FROM master..sysmessages FOR BROWSE"); assertNotNull(rs); assertNotNull(rs.getWarnings()); rs.close(); // Enable logging to see that this test should just fail without // attempting to fall back on normal execution. // DriverManager.setLogStream(System.out); try { stmt.executeQuery("select bad from syntax"); fail("Expected SQLException"); } catch (SQLException e) { assertEquals("S0002", e.getSQLState()); } // DriverManager.setLogStream(null); stmt.close(); } /** * Test for bug [1246270] Closing a statement after canceling it throws an * exception. */ public void testCancelResultSet() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #TEST (id int primary key, data varchar(255))"); for (int i = 1; i < 1000; i++) { stmt.executeUpdate("INSERT INTO #TEST VALUES (" + i + ", 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')"); } ResultSet rs = stmt.executeQuery("SELECT * FROM #TEST"); assertNotNull(rs); assertTrue(rs.next()); stmt.cancel(); stmt.close(); } /** * Test whether retrieval by name returns the first occurence (that's what * the spec requires). */ public void testGetByName() throws Exception { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1 myCol, 2 myCol, 3 myCol"); assertTrue(rs.next()); assertEquals(1, rs.getInt("myCol")); assertFalse(rs.next()); stmt.close(); } /** * Test if COL_INFO packets are processed correctly for * <code>ResultSet</code>s with over 255 columns. */ public void testMoreThan255Columns() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); // create the table int cols = 260; StringBuffer create = new StringBuffer("create table #manycolumns ("); for (int i=0; i<cols; ++i) { create.append("col" + i + " char(10), ") ; } create.append(")"); stmt.executeUpdate(create.toString()); String query = "select * from #manycolumns"; ResultSet rs = stmt.executeQuery(query); rs.close(); stmt.close(); } /** * Test that <code>insertRow()</code> works with no values set. */ public void testEmptyInsertRow() throws Exception { int rows = 10; Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #emptyInsertRow (id int identity, val int default 10)"); ResultSet rs = stmt.executeQuery("select * from #emptyInsertRow"); for (int i=0; i<rows; i++) { rs.moveToInsertRow(); rs.insertRow(); } rs.close(); rs = stmt.executeQuery("select count(*) from #emptyInsertRow"); assertTrue(rs.next()); assertEquals(rows, rs.getInt(1)); rs.close(); rs = stmt.executeQuery("select * from #emptyInsertRow order by id"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(10, rs.getInt(2)); rs.close(); stmt.close(); } /** * Test that inserted rows are visible in a scroll sensitive * <code>ResultSet</code> and that they show up at the end. */ public void testInsertRowVisible() throws Exception { int rows = 10; Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #insertRowNotVisible (val int primary key)"); ResultSet rs = stmt.executeQuery("select * from #insertRowNotVisible"); for (int i = 1; i <= rows; i++) { rs.moveToInsertRow(); rs.updateInt(1, i); rs.insertRow(); rs.moveToCurrentRow(); rs.last(); assertEquals(i, rs.getRow()); } rs.close(); stmt.close(); } /** * Test that updated rows are marked as deleted and the new values inserted * at the end of the <code>ResultSet</code> if the primary key is updated. */ public void testUpdateRowDuplicatesRow() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #updateRowDuplicatesRow (val int primary key)"); stmt.executeUpdate( "insert into #updateRowDuplicatesRow (val) values (1)"); stmt.executeUpdate( "insert into #updateRowDuplicatesRow (val) values (2)"); stmt.executeUpdate( "insert into #updateRowDuplicatesRow (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #updateRowDuplicatesRow order by val"); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); rs.updateInt(1, rs.getInt(1) + 10); rs.updateRow(); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertTrue(rs.rowDeleted()); } for (int i = 11; i <= 13; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); assertEquals(i, rs.getInt(1)); } rs.close(); stmt.close(); } /** * Test that updated rows are modified in place if the primary key is not * updated. */ public void testUpdateRowUpdatesRow() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #updateRowUpdatesRow (id int primary key, val int)"); stmt.executeUpdate( "insert into #updateRowUpdatesRow (id, val) values (1, 1)"); stmt.executeUpdate( "insert into #updateRowUpdatesRow (id, val) values (2, 2)"); stmt.executeUpdate( "insert into #updateRowUpdatesRow (id, val) values (3, 3)"); ResultSet rs = stmt.executeQuery( "select id, val from #updateRowUpdatesRow order by id"); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); rs.updateInt(2, rs.getInt(2) + 10); rs.updateRow(); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); assertEquals(rs.getInt(1) + 10, rs.getInt(2)); } assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test that deleted rows are not removed but rather marked as deleted. */ public void testDeleteRowMarksDeleted() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #deleteRowMarksDeleted (val int primary key)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (1)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (2)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #deleteRowMarksDeleted order by val"); for (int i = 0; i < 3; i++) { assertTrue(rs.next()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertFalse(rs.rowDeleted()); rs.deleteRow(); assertFalse(rs.rowUpdated()); assertFalse(rs.rowInserted()); assertTrue(rs.rowDeleted()); } assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1170777] resultSet.updateRow() fails if no row has been * changed. */ public void testUpdateRowNoChanges() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.executeUpdate( "create table #deleteRowMarksDeleted (val int primary key)"); stmt.executeUpdate( "insert into #deleteRowMarksDeleted (val) values (1)"); ResultSet rs = stmt.executeQuery( "select val from #deleteRowMarksDeleted order by val"); assertTrue(rs.next()); // This should not crash; it should be a no-op rs.updateRow(); rs.refreshRow(); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test the behavior of <code>sp_cursorfetch</code> with fetch sizes * greater than 1. * <p> * <b>Assertions tested:</b> * <ul> * <li>The <i>current row</i> is always the first row returned by the * last fetch, regardless of what fetch type was used. * <li>Row number parameter is ignored by fetch types other than absolute * and relative. * <li>Refresh fetch type simply reruns the previous request (it ignores * both row number and number of rows) and will not affect the * <i>current row</i>. * <li>Fetch next returns the packet of rows right after the last row * returned by the last fetch (regardless of what type of fetch that * was). * <li>Fetch previous returns the packet of rows right before the first * row returned by the last fetch (regardless of what type of fetch * that was). * <li>If a fetch previous tries to read before the start of the * <code>ResultSet</code> the requested number of rows is returned, * starting with row 1 and the error code returned is non-zero (2). * </ul> */ public void testCursorFetch() throws Exception { int rows = 10; Statement stmt = con.createStatement(); stmt.executeUpdate( "create table #testCursorFetch (id int primary key, val int)"); stmt.close(); PreparedStatement pstmt = con.prepareStatement( "insert into #testCursorFetch (id, val) values (?, ?)"); for (int i = 1; i <= rows; i++) { pstmt.setInt(1, i); pstmt.setInt(2, i); pstmt.executeUpdate(); } pstmt.close(); // Open cursor CallableStatement cstmt = con.prepareCall( "{?=call sp_cursoropen(?, ?, ?, ?, ?)}"); // Return value (OUT) cstmt.registerOutParameter(1, Types.INTEGER); // Cursor handle (OUT) cstmt.registerOutParameter(2, Types.INTEGER); // Statement (IN) cstmt.setString(3, "select * from #testCursorFetch order by id"); // Scroll options (INOUT) cstmt.setInt(4, 1); // Keyset driven cstmt.registerOutParameter(4, Types.INTEGER); // Concurrency options (INOUT) cstmt.setInt(5, 2); // Scroll locks cstmt.registerOutParameter(5, Types.INTEGER); // Row count (OUT) cstmt.registerOutParameter(6, Types.INTEGER); ResultSet rs = cstmt.executeQuery(); assertEquals(2, rs.getMetaData().getColumnCount()); assertFalse(rs.next()); assertEquals(0, cstmt.getInt(1)); int cursor = cstmt.getInt(2); assertEquals(1, cstmt.getInt(4)); assertEquals(2, cstmt.getInt(5)); assertEquals(rows, cstmt.getInt(6)); cstmt.close(); // Play around with fetch cstmt = con.prepareCall("{?=call sp_cursorfetch(?, ?, ?, ?)}"); // Return value (OUT) cstmt.registerOutParameter(1, Types.INTEGER); // Cursor handle (IN) cstmt.setInt(2, cursor); // Fetch type (IN) cstmt.setInt(3, 2); // Next row // Row number (INOUT) cstmt.setInt(4, 1); // Only matters for absolute and relative fetching // Number of rows (INOUT) cstmt.setInt(5, 2); // Read 2 rows // Fetch rows 1-2 (current row is 1) rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch rows 3-4 (current row is 3) rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Refresh rows 3-4 (current row is 3) cstmt.setInt(3, 0x80); // Refresh cstmt.setInt(4, 2); // Try to refresh only 2nd row (will be ignored) cstmt.setInt(5, 1); // Try to refresh only 1 row (will be ignored) rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch rows 5-6 (current row is 5) cstmt.setInt(3, 2); // Next cstmt.setInt(4, 1); // Row number 1 cstmt.setInt(5, 2); // Get 2 rows rs = cstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.next()); assertEquals(6, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch previous rows (3-4) (current row is 3) cstmt.setInt(3, 4); // Previous rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Refresh rows 3-4 (current row is 3) cstmt.setInt(3, 0x80); // Refresh rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch previous rows (1-2) (current row is 1) cstmt.setInt(3, 4); // Previous rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch next rows (3-4) (current row is 3) cstmt.setInt(3, 2); // Next rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch first rows (1-2) (current row is 1) cstmt.setInt(3, 1); // First rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch last rows (9-10) (current row is 9) cstmt.setInt(3, 8); // Last rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(9, rs.getInt(1)); assertTrue(rs.next()); assertEquals(10, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch next rows; should not fail (current position is after last) cstmt.setInt(3, 2); // Next rs = cstmt.executeQuery(); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch absolute starting with 6 (6-7) (current row is 6) cstmt.setInt(3, 0x10); // Absolute cstmt.setInt(4, 6); rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(6, rs.getInt(1)); assertTrue(rs.next()); assertEquals(7, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch relative -4 (2-3) (current row is 2) cstmt.setInt(3, 0x20); // Relative cstmt.setInt(4, -4); rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); // Fetch previous 2 rows; should fail (current row is 1) cstmt.setInt(3, 4); // Previous rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertFalse(rs.next()); rs.close(); // Returns 2 on error assertEquals(2, cstmt.getInt(1)); // Fetch next rows (3-4) (current row is 3) cstmt.setInt(3, 2); // Next rs = cstmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertFalse(rs.next()); rs.close(); assertEquals(0, cstmt.getInt(1)); cstmt.close(); // Close cursor cstmt = con.prepareCall("{?=call sp_cursorclose(?)}"); // Return value (OUT) cstmt.registerOutParameter(1, Types.INTEGER); // Cursor handle (IN) cstmt.setInt(2, cursor); assertFalse(cstmt.execute()); assertEquals(0, cstmt.getInt(1)); cstmt.close(); } /** * Test that <code>absolute(-1)</code> works the same as <code>last()</code>. */ public void testAbsoluteMinusOne() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate( "create table #absoluteMinusOne (val int primary key)"); stmt.executeUpdate( "insert into #absoluteMinusOne (val) values (1)"); stmt.executeUpdate( "insert into #absoluteMinusOne (val) values (2)"); stmt.executeUpdate( "insert into #absoluteMinusOne (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #absoluteMinusOne order by val"); rs.absolute(-1); assertTrue(rs.isLast()); assertEquals(3, rs.getInt(1)); assertFalse(rs.next()); rs.last(); assertTrue(rs.isLast()); assertEquals(3, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test that calling <code>absolute()</code> with very large positive * values positions the cursor after the last row and with very large * negative values positions the cursor before the first row. */ public void testAbsoluteLargeValue() throws SQLException { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate( "create table #absoluteLargeValue (val int primary key)"); stmt.executeUpdate( "insert into #absoluteLargeValue (val) values (1)"); stmt.executeUpdate( "insert into #absoluteLargeValue (val) values (2)"); stmt.executeUpdate( "insert into #absoluteLargeValue (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #absoluteLargeValue order by val"); assertFalse(rs.absolute(10)); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.next()); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.absolute(-10)); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); assertFalse(rs.previous()); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); rs.close(); stmt.close(); } /** * Test that calling <code>absolute()</code> with very large positive * values positions the cursor after the last row and with very large * negative values positions the cursor before the first row. */ public void testRelativeLargeValue() throws SQLException { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.executeUpdate( "create table #relativeLargeValue (val int primary key)"); stmt.executeUpdate( "insert into #relativeLargeValue (val) values (1)"); stmt.executeUpdate( "insert into #relativeLargeValue (val) values (2)"); stmt.executeUpdate( "insert into #relativeLargeValue (val) values (3)"); ResultSet rs = stmt.executeQuery( "select val from #relativeLargeValue order by val"); assertFalse(rs.relative(10)); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.next()); assertEquals(0, rs.getRow()); assertTrue(rs.isAfterLast()); assertFalse(rs.relative(-10)); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); assertFalse(rs.previous()); assertEquals(0, rs.getRow()); assertTrue(rs.isBeforeFirst()); rs.close(); stmt.close(); } /** * Test that <code>read()</code> works ok on the stream returned by * <code>ResultSet.getUnicodeStream()</code> (i.e. it doesn't always fill * the buffer, regardless of whether there's available data or not). */ public void testUnicodeStream() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #unicodeStream (val varchar(255))"); stmt.executeUpdate("insert into #unicodeStream (val) values ('test')"); ResultSet rs = stmt.executeQuery("select val from #unicodeStream"); if (rs.next()) { byte[] buf = new byte[8000]; InputStream is = rs.getUnicodeStream(1); int length = is.read(buf); assertEquals(4 * 2, length); } rs.close(); stmt.close(); } /** * Test that <code>Statement.setMaxRows()</code> works on cursor * <code>ResultSet</code>s. */ public void testCursorMaxRows() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #cursorMaxRows (val int)"); stmt.close(); // Insert 10 rows PreparedStatement pstmt = con.prepareStatement( "insert into #cursorMaxRows (val) values (?)"); for (int i = 0; i < 10; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); // Create a cursor ResultSet stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Set maxRows to 5 stmt.setMaxRows(5); // Select all (should only return 5 rows) ResultSet rs = stmt.executeQuery("select * from #cursorMaxRows"); rs.last(); assertEquals(5, rs.getRow()); rs.beforeFirst(); int cnt = 0; while (rs.next()) { cnt++; } assertEquals(5, cnt); rs.close(); stmt.close(); } /** * Test for bug [1075977] <code>setObject()</code> causes SQLException. * <p> * Conversion of <code>float</code> values to <code>String</code> adds * grouping to the value, which cannot then be parsed. */ public void testSetObjectScale() throws Exception { Statement stmt = con.createStatement(); stmt.execute("create table #testsetobj (i int)"); PreparedStatement pstmt = con.prepareStatement("insert into #testsetobj values(?)"); // next line causes sqlexception pstmt.setObject(1, new Float(1234.5667), Types.INTEGER, 0); assertEquals(1, pstmt.executeUpdate()); ResultSet rs = stmt.executeQuery("select * from #testsetobj"); assertTrue(rs.next()); assertEquals("1234", rs.getString(1)); } /** * Test that <code>ResultSet.previous()</code> works correctly on cursor * <code>ResultSet</code>s. */ public void testCursorPrevious() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #cursorPrevious (val int)"); stmt.close(); // Insert 10 rows PreparedStatement pstmt = con.prepareStatement( "insert into #cursorPrevious (val) values (?)"); for (int i = 0; i < 10; i++) { pstmt.setInt(1, i); assertEquals(1, pstmt.executeUpdate()); } pstmt.close(); // Create a cursor ResultSet stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Set fetch size to 2 stmt.setFetchSize(2); // Select all ResultSet rs = stmt.executeQuery("select * from #cursorPrevious"); rs.last(); int i = 10; do { assertEquals(i, rs.getRow()); assertEquals(--i, rs.getInt(1)); } while (rs.previous()); assertTrue(rs.isBeforeFirst()); assertEquals(0, i); rs.close(); stmt.close(); } /** * Test the behavior of the ResultSet/Statement/Connection when the JVM * runs out of memory (hopefully) in the middle of a packet. * <p/> * Previously jTDS was not able to close a ResultSet/Statement/Connection * after an OutOfMemoryError because the input stream pointer usually * remained inside a packet and further attempts to dump the rest of the * response failed because of "protocol confusions". */ public void testOutOfMemory() throws SQLException { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #testOutOfMemory (val binary(8000))"); // Insert a 8KB value byte[] val = new byte[8000]; PreparedStatement pstmt = con.prepareStatement( "insert into #testOutOfMemory (val) values (?)"); pstmt.setBytes(1, val); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); // Create a list and keep adding rows to it until we run out of memory // Most probably this will happen in the middle of a row packet, when // jTDS tries to allocate the array, after reading the data length ArrayList results = new ArrayList(); ResultSet rs = null; try { while (true) { rs = stmt.executeQuery("select val from #testOutOfMemory"); assertTrue(rs.next()); results.add(rs.getBytes(1)); assertFalse(rs.next()); rs.close(); rs = null; } } catch (OutOfMemoryError err) { // Do not remove this. Although not really used, it will free // memory, avoiding another OutOfMemoryError results = null; if (rs != null) { // This used to fail, because the parser got confused rs.close(); } } // Make sure the Statement still works rs = stmt.executeQuery("select 1"); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1182066] regression bug resultset: relative() not working * as expected. */ public void testRelative() throws Exception { final int ROW_COUNT = 99; Statement stmt = con.createStatement(); stmt.executeUpdate("create table #test2 (i int primary key, v varchar(100))"); for (int i = 1; i <= ROW_COUNT; i++) { stmt.executeUpdate("insert into #test2 (i, v) values (" + i + ", 'This is a test')"); } stmt.close(); String sql = "select * from #test2"; PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); pstmt.setFetchSize(10); ResultSet rs = pstmt.executeQuery(); int resCnt = 0; if (rs.next()) { do { assertEquals(++resCnt, rs.getInt(1)); } while (rs.relative(1)); } assertEquals(ROW_COUNT, resCnt); if (rs.previous()) { do { assertEquals(resCnt--, rs.getInt(1)); } while (rs.relative(-1)); } pstmt.close(); assertEquals(0, resCnt); } /** * Test that after updateRow() the cursor is positioned correctly. */ public void testUpdateRowPosition() throws Exception { final int ROW_COUNT = 99; final int TEST_ROW = 33; Statement stmt = con.createStatement(); stmt.executeUpdate("create table #testPos (i int primary key, v varchar(100))"); for (int i = 1; i <= ROW_COUNT; i++) { stmt.executeUpdate("insert into #testPos (i, v) values (" + i + ", 'This is a test')"); } stmt.close(); String sql = "select * from #testPos order by i"; PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setFetchSize(10); ResultSet rs = pstmt.executeQuery(); for (int i = 1; i <= TEST_ROW; i++) { assertTrue(rs.next()); assertEquals(i, rs.getInt(1)); } // We're on TEST_ROW now assertEquals(TEST_ROW, rs.getRow()); rs.updateString(2, "This is another test"); rs.updateRow(); assertEquals(TEST_ROW, rs.getRow()); assertEquals(TEST_ROW, rs.getInt(1)); rs.refreshRow(); assertEquals(TEST_ROW, rs.getRow()); assertEquals(TEST_ROW, rs.getInt(1)); for (int i = TEST_ROW + 1; i <= ROW_COUNT; i++) { assertTrue(rs.next()); assertEquals(i, rs.getInt(1)); } pstmt.close(); } /** * Test for bug [1197603] Cursor downgrade error in CachedResultSet -- * updateable result sets were incorrectly downgraded to read only forward * only ones when client side cursors were used. */ public void testUpdateableClientCursor() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #testUpdateableClientCursor " + "(i int primary key, v varchar(100))"); stmt.executeUpdate("insert into #testUpdateableClientCursor " + "(i, v) values (1, 'This is a test')"); stmt.close(); // Use a statement that the server won't be able to create a cursor on String sql = "select * from #testUpdateableClientCursor where i = ?"; PreparedStatement pstmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertNull(pstmt.getWarnings()); rs.updateString(2, "This is another test"); rs.updateRow(); rs.close(); pstmt.close(); stmt = con.createStatement(); rs = stmt.executeQuery( "select * from #testUpdateableClientCursor"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("This is another test", rs.getString(2)); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test bug with Sybase where readonly scrollable result set based on a * SELECT DISTINCT returns duplicate rows. */ public void testDistinctBug() throws Exception { Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.execute( "CREATE TABLE #testdistinct (id int primary key, c varchar(255))"); stmt.addBatch("INSERT INTO #testdistinct VALUES(1, 'AAAA')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(2, 'AAAA')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(3, 'BBBB')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(4, 'BBBB')"); stmt.addBatch("INSERT INTO #testdistinct VALUES(5, 'CCCC')"); int counts[] = stmt.executeBatch(); assertEquals(5, counts.length); ResultSet rs = stmt.executeQuery( "SELECT DISTINCT c FROM #testdistinct"); assertNotNull(rs); int rowCount = 0; while (rs.next()) { rowCount++; } assertEquals(3, rowCount); stmt.close(); } /** * Test pessimistic concurrency for SQL Server (for Sybase optimistic * concurrency will always be used). */ public void testPessimisticConcurrency() throws Exception { dropTable("pessimisticConcurrency"); Connection con2 = getConnection(); Statement stmt = null; ResultSet rs = null; try { // Create statement using pessimistic locking. stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE + 1); stmt.execute("CREATE TABLE pessimisticConcurrency (id int primary key, data varchar(255))"); for (int i = 0; i < 4; i++) { stmt.executeUpdate("INSERT INTO pessimisticConcurrency VALUES("+i+", 'Table A line "+i+"')"); } // Fetch one row at a time, making sure we know exactly which row is locked stmt.setFetchSize(1); // Open cursor rs = stmt.executeQuery("SELECT id, data FROM pessimisticConcurrency ORDER BY id"); assertNull(rs.getWarnings()); assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, rs.getType()); assertEquals(ResultSet.CONCUR_UPDATABLE + 1, rs.getConcurrency()); // If not a MSCursorResultSet, give up as no locking will happen if (rs.getClass().getName().indexOf("MSCursorResultSet") == -1) { rs.close(); stmt.close(); return; } // Scroll to and lock row 3 for (int i = 0; i < 3; ++i) { rs.next(); } // Create a second statement final Statement stmt2 = con2.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE + 1); // No better idea to store exceptions final ArrayList container = new ArrayList(); // Launch a thread that will cancel the second statement if it hangs. new Thread() { public void run() { try { sleep(1000); stmt2.cancel(); } catch (Exception ex) { container.add(ex); } } }.start(); // Open second cursor ResultSet rs2 = stmt2.executeQuery("SELECT id, data FROM pessimisticConcurrency WHERE id = 2"); assertNull(rs2.getWarnings()); assertEquals(ResultSet.TYPE_SCROLL_SENSITIVE, rs2.getType()); assertEquals(ResultSet.CONCUR_UPDATABLE + 1, rs2.getConcurrency()); try { System.out.println(rs2.next()); } catch (SQLException ex) { ex.printStackTrace(); System.out.println(ex.getNextException()); if ("HY010".equals(ex.getSQLState())) { stmt2.getMoreResults(); } if (!"HY008".equals(ex.getSQLState()) && !"HY010".equals(ex.getSQLState())) { fail("Expecting cancel exception."); } } rs.close(); stmt.close(); rs2.close(); stmt2.close(); // Check for exceptions thrown in the cancel thread if (container.size() != 0) { throw (SQLException) container.get(0); } } finally { dropTable("pessimisticConcurrency"); if (con2 != null) { con2.close(); } } } /** * Test if dynamic cursors (<code>ResultSet.TYPE_SCROLL_SENSITIVE+1</code>) * see others' updates. SQL Server only. */ public void testDynamicCursors() throws Exception { final int ROWS = 4; dropTable("dynamicCursors"); Connection con2 = getConnection(); try { Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE + 1, ResultSet.CONCUR_READ_ONLY); stmt.execute("CREATE TABLE dynamicCursors (id int primary key, data varchar(255))"); for (int i = 0; i < ROWS; i++) { stmt.executeUpdate("INSERT INTO dynamicCursors VALUES(" + i + ", 'Table A line " + i + "')"); } // Open cursor ResultSet rs = stmt.executeQuery("SELECT id, data FROM dynamicCursors"); // If not a MSCursorResultSet, give up as it will not see inserts if (rs.getClass().getName().indexOf("MSCursorResultSet") == -1) { rs.close(); stmt.close(); return; } // Insert new row from other connection Statement stmt2 = con2.createStatement(); assertEquals(1, stmt2.executeUpdate( "INSERT INTO dynamicCursors VALUES(" + ROWS + ", 'Table A line " + ROWS + "')")); stmt2.close(); // Count rows and make sure the newly inserted row is visible int cnt; for (cnt = 0; rs.next(); cnt++); assertEquals(ROWS + 1, cnt); rs.close(); stmt.close(); } finally { dropTable("dynamicCursors"); if (con2 != null) { con2.close(); } } } /** * Test for bug [1232733] setFetchSize(0) causes exception. */ public void testZeroFetchSize() throws Exception { Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(0); ResultSet rs = stmt.executeQuery("SELECT 1 UNION SELECT 2"); assertTrue(rs.next()); rs.setFetchSize(0); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); stmt.close(); } /** * Test for bug [1329765] Pseudo column ROWSTAT is back with SQL 2005 * (September CTP). */ public void testRowstat() throws Exception { PreparedStatement stmt = con.prepareStatement("SELECT 'STRING' str", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(); assertEquals(1, rs.getMetaData().getColumnCount()); assertTrue(rs.next()); assertFalse(rs.next()); rs.close(); stmt.close(); } public static void main(String[] args) { junit.textui.TestRunner.run(ResultSetTest.class); } }
package org.apache.lucene.search; import org.apache.lucene.index.Term; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.search.Query; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.analysis.SimpleAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.DateField; import java.io.IOException; import junit.framework.TestCase; /** * DateFilter JUnit tests. * * @author Otis Gospodnetic * @version $Revision$ */ public class TestDateFilter extends TestCase { public TestDateFilter(String name) { super(name); } public static void testBefore() throws IOException { // create an index RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true); long now = System.currentTimeMillis(); Document doc = new Document(); // add time that is in the past doc.add(Field.Text("datefield", DateField.timeToString(now - 1000))); doc.add(Field.Text("body", "Today is a very sunny day in New York City")); writer.addDocument(doc); writer.optimize(); writer.close(); IndexSearcher searcher = new IndexSearcher(indexStore); // filter that should preserve matches DateFilter df1 = DateFilter.Before("datefield", now); // filter that should discard matches DateFilter df2 = DateFilter.Before("datefield", now - 999999); // search something that doesn't exist with DateFilter Query query1 = new TermQuery(new Term("body", "NoMatchForThis")); // search for something that does exists Query query2 = new TermQuery(new Term("body", "sunny")); Hits result; // ensure that queries return expected results without DateFilter first result = searcher.search(query1); assertEquals(0, result.length()); result = searcher.search(query2); assertEquals(1, result.length()); // run queries with DateFilter result = searcher.search(query1, df1); assertEquals(0, result.length()); result = searcher.search(query1, df2); assertEquals(0, result.length()); result = searcher.search(query2, df1); assertEquals(1, result.length()); result = searcher.search(query2, df2); assertEquals(0, result.length()); } public static void testAfter() throws IOException { // create an index RAMDirectory indexStore = new RAMDirectory(); IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true); long now = System.currentTimeMillis(); Document doc = new Document(); // add time that is in the future doc.add(Field.Text("datefield", DateField.timeToString(now - 888888))); doc.add(Field.Text("body", "Today is a very sunny day in New York City")); writer.addDocument(doc); writer.optimize(); writer.close(); IndexSearcher searcher = new IndexSearcher(indexStore); // filter that should preserve matches DateFilter df1 = DateFilter.After("datefield", now); // filter that should discard matches DateFilter df2 = DateFilter.After("datefield", now + 999999); // search something that doesn't exist with DateFilter Query query1 = new TermQuery(new Term("body", "NoMatchForThis")); // search for something that does exists Query query2 = new TermQuery(new Term("body", "sunny")); Hits result; // ensure that queries return expected results without DateFilter first result = searcher.search(query1); assertEquals(0, result.length()); result = searcher.search(query2); assertEquals(1, result.length()); // run queries with DateFilter result = searcher.search(query1, df1); assertEquals(0, result.length()); result = searcher.search(query1, df2); assertEquals(0, result.length()); result = searcher.search(query2, df1); assertEquals(1, result.length()); result = searcher.search(query2, df2); assertEquals(0, result.length()); } }
package org.mozilla.taskcluster; import java.nio.ByteBuffer; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.mozilla.taskcluster.client.APICallFailure; import org.mozilla.taskcluster.client.CallSummary; import org.mozilla.taskcluster.client.queue.Queue; import org.mozilla.taskcluster.client.queue.TaskDefinition; import org.mozilla.taskcluster.client.queue.TaskStatusResponse; import net.iharder.Base64; public class APITest { /** * Generates a 22 character random slugId that is url-safe ([0-9a-zA-Z_\-]*) */ public static String slug() { UUID uuid = UUID.randomUUID(); long hi = uuid.getMostSignificantBits(); long lo = uuid.getLeastSignificantBits(); ByteBuffer raw = ByteBuffer.allocate(16); raw.putLong(hi); raw.putLong(lo); byte[] rawBytes = raw.array(); return Base64.encodeBytes(rawBytes).replace('+', '-').replace('/', '_').substring(0, 22); } /** * Tests whether it is possible to define a task against the production * Queue. */ @Test public void testDefineTask() { String clientId = System.getenv("TASKCLUSTER_CLIENT_ID"); String accessToken = System.getenv("TASKCLUSTER_ACCESS_TOKEN"); String certificate = System.getenv("TASKCLUSTER_CERTIFICATE"); Assume.assumeFalse(clientId == null || clientId == "" || accessToken == null || accessToken == ""); Queue queue; if (certificate == null || certificate == "") { queue = new Queue(clientId, accessToken); } else { queue = new Queue(clientId, accessToken, certificate); } String taskId = slug(); TaskDefinition td = new TaskDefinition(); td.created = new Date(); Calendar c = Calendar.getInstance(); c.setTime(td.created); c.add(Calendar.DATE, 1); td.deadline = c.getTime(); td.expires = td.deadline; Map<String, Object> index = new HashMap<String, Object>(); index.put("rank", 12345); Map<String, Object> extra = new HashMap<String, Object>(); extra.put("index", index); td.extra = extra; td.metadata = td.new Metadata(); td.metadata.description = "Stuff"; td.metadata.name = "[TC] Pete"; td.metadata.owner = "pmoore@mozilla.com"; td.metadata.source = "http://somewhere.com/"; Map<String, Object> features = new HashMap<String, Object>(); features.put("relengAPIProxy", true); Map<String, Object> payload = new HashMap<String, Object>(); payload.put("features", features); td.payload = payload; td.provisionerId = "win-provisioner"; td.retries = 5; td.routes = new String[] { "tc-treeherder.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163", "tc-treeherder-stage.mozilla-inbound.bcf29c305519d6e120b2e4d3b8aa33baaf5f0163" }; td.schedulerId = "junit-test-scheduler"; td.scopes = new String[] { "docker-worker:image:taskcluster/builder:0.5.6", "queue:define-task:aws-provisioner-v1/build-c4-2xlarge" }; Map<String, Object> tags = new HashMap<String, Object>(); tags.put("createdForUser", "cbook@mozilla.com"); td.tags = tags; td.taskGroupId = "dtwuF2n9S-i83G37V9eBuQ"; td.workerType = "win2008-worker"; try { CallSummary<TaskDefinition, TaskStatusResponse> cs = queue.defineTask(taskId, td); Assert.assertEquals(cs.requestPayload.provisionerId, "win-provisioner"); Assert.assertEquals(cs.responsePayload.status.schedulerId, "junit-test-scheduler"); Assert.assertEquals(cs.responsePayload.status.retriesLeft, 5); Assert.assertEquals(cs.responsePayload.status.state, "unscheduled"); } catch (APICallFailure e) { e.printStackTrace(); Assert.fail("Exception thrown"); } } }
package org.oregami.rest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.restassured.RestAssured; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.path.json.JsonPath; import com.jayway.restassured.response.Header; import com.jayway.restassured.response.Response; import io.dropwizard.testing.junit.DropwizardAppRule; import org.hamcrest.Matchers; import org.junit.*; import org.oregami.data.*; import org.oregami.dropwizard.OregamiAppRule; import org.oregami.dropwizard.OregamiApplication; import org.oregami.dropwizard.OregamiConfiguration; import org.oregami.entities.*; import org.oregami.entities.datalist.Script; import org.oregami.util.StartHelper; import java.util.HashMap; import java.util.List; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; public class RestEntityTest { @ClassRule public static final DropwizardAppRule<OregamiConfiguration> RULE = new OregamiAppRule(OregamiApplication.class, StartHelper.CONFIG_FILENAME_TEST); private static ObjectMapper mapper; @BeforeClass public static void initClass() { StartHelper.getInstance(DatabaseFiller.class).initData(); } @AfterClass public static void finish() { StartHelper.getInstance(DatabaseFiller.class).dropAllData(); } /** * login, create new GameTitle */ @Test public void createNewGameTitle() throws JsonProcessingException { String token = loginAndGetToken(); Response response = RestAssured.get(RestTestHelper.URL_GAMETITLES); JsonPath jsonPath = new JsonPath(response.body().prettyPrint()); List<HashMap> liste = jsonPath.getList("$"); Assert.assertNotNull(liste); Assert.assertThat(liste.size(), Matchers.greaterThan(0)); GameTitle gameTitle = new GameTitle(); gameTitle.setNativeSpelling("The Secret of Monkey Island"); //set Header for secured request: Header authHeader = new Header("Authorization", "bearer " + token); response = saveNewEntity(gameTitle, RestTestHelper.URL_GAMETITLES, authHeader); //Load entity with new GET request String location = response.header("Location"); response = RestAssured.get(location); String nativeSpelling = response.body().jsonPath().get("nativeSpelling"); Assert.assertThat(nativeSpelling, equalTo(gameTitle.getNativeSpelling())); Assert.assertThat(location, containsString(response.body().jsonPath().get("id").toString())); } private String loginAndGetToken() { Header header = new Header("Content-Type", "application/x-www-form-urlencoded"); Response response = RestAssured.given().formParam("username", "user1").formParam("password", "password1").header(header).request().post(RestTestHelper.URL_LOGIN); response.then().contentType(ContentType.JSON).statusCode(200); response.then().contentType(ContentType.JSON).body("token", Matchers.notNullValue()); response.then().contentType(ContentType.JSON).body("token", Matchers.containsString(".")); //get JsonWebToken from response: String token = response.body().jsonPath().get("token"); return token; } private String getJsonString(Object entity) { try { return getJsonMapper().writeValueAsString(entity); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } private static ObjectMapper getJsonMapper() { if (mapper==null) { mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } return mapper; } @Test public void createNewHardwarePlatform() throws JsonProcessingException { String token = loginAndGetToken(); Header authHeader = new Header("Authorization", "bearer " + token); Response response = RestAssured.get(RestTestHelper.URL_HARDWAREPLATFORM); JsonPath jsonPath = new JsonPath(response.body().prettyPrint()); List<HashMap> liste = jsonPath.getList("$"); Assert.assertNotNull(liste); TransliteratedString playstationLatinEnglish = new TransliteratedString(); Language langEnglish = StartHelper.getInstance(LanguageDao.class).findByExactName(Language.ENGLISH); playstationLatinEnglish.setLanguage(langEnglish); Script scriptLatin = StartHelper.getInstance(BaseListFinder.class).getScript(Script.LATIN); Response response1 = RestAssured.given().when().get(RestTestHelper.URL_SCRIPT + "/" + scriptLatin.getId()); System.out.println(response1.body().prettyPrint()); //Script s = RestAssured.given().when().get(RestTestHelper.URL_SCRIPT+ "/" + scriptLatin.getId()).as(Script.class); playstationLatinEnglish.setScript(scriptLatin); playstationLatinEnglish.setText("Sony Playstation"); response = saveNewEntity(playstationLatinEnglish, RestTestHelper.URL_TRANSLITERATEDSTRING, authHeader); String loc = response.header("Location"); playstationLatinEnglish = StartHelper.getInstance(TransliteratedStringDao.class).findOne(loc.substring(loc.lastIndexOf("/") + 1)); TransliteratedString playstationJapanese = new TransliteratedString(); Language langJapanese = StartHelper.getInstance(LanguageDao.class).findByExactName(Language.JAPANESE); playstationJapanese.setLanguage(langJapanese); Script scriptJapanese = StartHelper.getInstance(BaseListFinder.class).getScript(Script.JAPANESE); playstationJapanese.setScript(scriptJapanese); playstationJapanese.setText(""); response = saveNewEntity(playstationJapanese, RestTestHelper.URL_TRANSLITERATEDSTRING, authHeader); loc = response.header("Location"); playstationJapanese = StartHelper.getInstance(TransliteratedStringDao.class).findOne(loc.substring(loc.lastIndexOf("/") + 1)); HardwarePlatform hp = new HardwarePlatform(); hp.addTitle(playstationJapanese); hp.addTitle(playstationLatinEnglish); response = saveNewEntity(hp, RestTestHelper.URL_HARDWAREPLATFORM, authHeader); //Load entity with new GET request String location = response.header("Location"); response = RestAssured.get(location); Assert.assertThat(location, containsString(response.body().jsonPath().get("id").toString())); //String text = response.body().jsonPath().get("title.text"); System.out.println(response.body().prettyPrint()); } private Response saveNewEntity(BaseEntityUUID entity, String url, Header authHeader) { entity.setChangeTime(null); Header jsonContentHeader = new Header("Content-Type", "application/json"); System.out.println(getJsonString(entity)); Response response = RestAssured.given() .header(authHeader) .header(jsonContentHeader) .body(getJsonString(entity)) .post(url); System.out.println(response.body().prettyPrint()); response.then().contentType(ContentType.JSON).statusCode(equalTo(javax.ws.rs.core.Response.Status.CREATED.getStatusCode())); return response; } }
package seedu.address.ui; import static org.junit.Assert.assertEquals; //import org.junit.After; //import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.testfx.api.FxRobot; import org.testfx.api.FxToolkit; import javafx.scene.web.WebView; import seedu.address.testutil.GuiTests; @Category({GuiTests.class}) public class HelpWindowTest extends FxRobot { private HelpWindow helpWindow; private WebView webView; @BeforeClass public static void setupFxToolkit() throws Exception { FxToolkit.registerPrimaryStage(); } /*@Before public void setupHelpWindow() throws Exception { FxToolkit.registerStage(() -> { return helpWindow = new HelpWindow(); //return helpWindow.getRoot(); }); FxToolkit.showStage(); webView = lookup("#webView").query(); } @After public void teardownHelpWindow() throws Exception { FxToolkit.cleanupStages(); }**/ @Test public void constructor() { assertEquals("https://github.com/se-edu/addressbook-level4/blob/master/docs/UserGuide.md", webView.getEngine().getLocation()); } }
package sublandroid; import sublandroid.messages.*; import static sublandroid.Path.*; import static sublandroid.help.Helper.*; import java.io.*; import org.testng.annotations.*; import com.alibaba.fastjson.TypeReference; import static org.assertj.core.api.Assertions.*; public class ClientConnectorTest { @Test(timeOut=10000) public void helloCommand() throws Throwable { try (Client client = new Client(PROJECT_01, 12345)) { client.send(MCommand.from("hello")); MHello hello = client.read(MHello.class); assertThat(hello).isNotNull(); assertThat(hello.message).isEqualTo("Woohoo!"); } } @Test(timeOut=5000, expectedExceptions=CommandFailed.class) public void unknowCommand() throws Throwable { try(Client client = new Client(PROJECT_01, 12346)) { client.send(MCommand.from("unknowCommand")); client.read(Object.class); } } }
package us.kbase.workspace.database; import static java.util.Objects.requireNonNull; import static us.kbase.workspace.database.Util.xorNameId; import static us.kbase.workspace.database.Util.noNulls; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import us.kbase.typedobj.core.SubsetSelection; import static us.kbase.workspace.database.ObjectIDNoWSNoVer.checkObjectName; import static us.kbase.common.utils.StringUtils.checkString; /** Identifies an object, or portions of an object, in a workspace. * * Some methods or class variables refer to references. These are a reference to an object in * a workspace of the form X/Y/Z, where X is the workspace name or ID, Y is the object name or ID, * and Z is an optional version. */ public class ObjectIdentifier { // TODO TEST complete unit tests (move from WorkspaceTest, mostly covered there) // also need to test toString code, but not super high priority /** The separator between parts of a workspace reference to an object. */ public final static String REFERENCE_SEP = "/"; /** The separator between references in a reference path. */ public static final String REFERENCE_PATH_SEP = ";"; private final WorkspaceIdentifier wsi; private final String name; private final long id; private final int version; private ObjectIdentifier( final WorkspaceIdentifier wsi, final long id, final String name, final int version) { this.wsi = wsi; this.name = name; this.id = id; this.version = version; } /** Get the identifier for the workspace in which the object resides. * @return the workspace ID. */ public WorkspaceIdentifier getWorkspaceIdentifier() { return wsi; } /** Get the name of the object. Exactly one of the name or ID of the object must be specified. * @return the object name if present. */ public Optional<String> getName() { return Optional.ofNullable(name); } /** Get the ID of the object. Exactly one of the name or ID of the object must be specified. * @return the object ID if present. */ public Optional<Long> getID() { return id < 1 ? Optional.empty() : Optional.of(id); } /** Get the version of the object. * @return the version of the object, if present. */ public Optional<Integer> getVersion() { return version < 1 ? Optional.empty() : Optional.of(version); } /** Returns whether this object identifier has a reference path. * @return true if this object identifier has a reference path, false otherwise. */ public boolean hasRefPath() { return false; } /** Returns the reference path to the target object, excluding the first object in the path. * @return the reference path. */ public List<ObjectIdentifier> getRefPath() { return Collections.emptyList(); } public ObjectIdentifier getLast() { throw new IllegalStateException("This object identifier has no reference path"); } public boolean isLookupRequired() { return false; } /** Get the subset of the object to return. * @return the subset selection for the object. */ public SubsetSelection getSubSet() { return SubsetSelection.EMPTY; } /** Validate an object reference. Notably, reference paths will cause an error. * If a reference path is permissible input, use {@link #validateReference(String, boolean)}. * @param reference the object reference. * @param absolute true to enforce absolute references, otherwise known as Unique Permanent * Addresses. */ public static void validateReference(final String reference, final boolean absolute) { checkString(reference, "reference"); processReference(reference, null, true, absolute); } /** Validate an object reference or reference path. * Example: "my_ws/my_obj/5;6/7;ws1/obj2;6/7/8" * In the example, only the last reference in the path is an absolute reference, otherwise * known as a Unique Permanent Address. * * @param reference the object reference or path. * @param absolute true to enforce absolute references, otherwise known as Unique Permanent * Addresses. */ public static void validateReferencePath(final String refpath, final boolean absolute) { processReferencePath(refpath, null, absolute); } private static void processReferencePath( final String refpath, final Builder builder, final boolean absolute) { checkString(refpath, "refpath"); String[] parts = refpath.split(REFERENCE_PATH_SEP); // remove trailing whitespace after last REFERENCE_PATH_SEP // also will ignore stuff like '1/1/1; ;' since the parsing alg doesn't make a // distinction. Fine for now if (parts.length > 1 && parts[parts.length - 1].trim().isEmpty()) { parts = Arrays.copyOf(parts, parts.length - 1); } final LinkedList<ObjectIdentifier> path = new LinkedList<>(); for (int i = 0; i < parts.length; i++) { try { if (i == 0) { processReference(parts[i], builder, builder == null, absolute); } else { // could eliminate the path here when builder == null, YAGNI for now path.add(processReference(parts[i], null, builder == null, absolute)); } } catch (IllegalArgumentException e) { final String errprefix = parts.length == 1 ? "" : String.format("Reference path position %s: ", i + 1); throw new IllegalArgumentException(errprefix + e.getLocalizedMessage(), e); } } if (!path.isEmpty() & builder != null) { builder.refpath = Collections.unmodifiableList(path); // needs to be immutable } } private static ObjectIdentifier processReference( final String reference, final Builder builder, final boolean noReturn, final boolean absolute) { // treat spaces in individual ref as errors final String[] r = reference.trim().split(REFERENCE_SEP); if (r.length != 2 && r.length != 3) { throw new IllegalArgumentException(String.format( "Illegal number of separators '%s' in object reference '%s'", REFERENCE_SEP, reference)); } // TODO CODE make a validation method for WI and avoid instantiating a class WorkspaceIdentifier wsi; try { wsi = new WorkspaceIdentifier(Long.parseLong(r[0])); } catch (NumberFormatException nfe) { wsi = new WorkspaceIdentifier(r[0]); } long id = -1; String name = null; try { id = checkID(Long.parseLong(r[1])); } catch (NumberFormatException nfe) { name = checkObjectName(r[1]); } final int version = r.length == 3 ? checkVersion(parseInt(r[2], reference, "version")) : -1; if (absolute && !isAbsolute(wsi, id, version)) { throw new IllegalArgumentException(String.format( "Reference %s is not absolute", reference)); } ObjectIdentifier ret = null; if (builder != null) { builder.wsi = wsi; builder.id = id; builder.name = name; builder.version = version; } if (!noReturn) { ret = new ObjectIdentifier(wsi, id, name, version); } return ret; } private static boolean isAbsolute( final WorkspaceIdentifier wsi, final long id, final int version) { return version > 0 && id > 0 && wsi.getId() != null; } private static long checkID(final Long id) { if (id < 1) { throw new IllegalArgumentException("Object id must be > 0"); } return id; } private static int checkVersion(final Integer version) { if (version != null && version < 1) { throw new IllegalArgumentException("Object version must be > 0"); } return version == null ? -1 : version; } /** Get an identifier string for the object. This is either the name or the ID, depending on * which is present. * @return the identifier string. */ public String getIdentifierString() { if (!getID().isPresent()) { return getName().get(); } return "" + getID().get(); } /** Get the workspace identifier string. This is identical to what is returned by * {@link WorkspaceIdentifier#getIdentifierString()}. * @return the identifier string. */ public String getWorkspaceIdentifierString() { return wsi.getIdentifierString(); } /** Get a reference string for this object. * @return the reference string. */ public String getReferenceString() { return getWorkspaceIdentifierString() + REFERENCE_SEP + getIdentifierString() + (version < 1 ? "" : REFERENCE_SEP + version); } /** Determine whether this object identifier must always point to the same object. This means * that permanent IDs rather than mutable names are present for the workspace and object * and a version is present. * * Note that any identifiers in the reference path are not checked by this method, and must * be checked individually. * @return true if this object identifier is absolute. */ public boolean isAbsolute() { return isAbsolute(wsi, id, version); } /** Resolve the workspace for this identifier, guaranteeing it exists. Reference paths, * lookup directions, and subset information is not preserved is the resolved object. * @param rwsi the resolved workspace ID. * @return an object identifier with a resolved workspace. */ public ObjectIDResolvedWS resolveWorkspace(final ResolvedWorkspaceID rwsi) { if (rwsi == null) { throw new IllegalArgumentException("rwsi cannot be null"); } if (name == null) { if (version < 1) { return new ObjectIDResolvedWS(rwsi, id); } else { return new ObjectIDResolvedWS(rwsi, id, version); } } if (version < 1) { return new ObjectIDResolvedWS(rwsi, name); } else { return new ObjectIDResolvedWS(rwsi, name, version); } } private static Integer parseInt(final String s, final String reference, final String portion) { try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format( "Unable to parse %s portion of object reference '%s' to an integer", portion, reference)); } } @Override public String toString() { return "ObjectIdentifier [wsi=" + wsi + ", name=" + getName() + ", id=" + getID() + ", version=" + getVersion() + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + version; result = prime * result + ((wsi == null) ? 0 : wsi.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ObjectIdentifier other = (ObjectIdentifier) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (version != other.version) return false; if (wsi == null) { if (other.wsi != null) return false; } else if (!wsi.equals(other.wsi)) return false; return true; } // so theoretically there could be a whole lot of different classes to represent different // configurations of object identifiers. For now we'll just go with these three because // they exist at the time of writing. However, we could add more classes to further reduce // memory usage by optimizing which fields are present in the future. private static class ObjectIDWithRefPath extends ObjectIdentifier { private final List<ObjectIdentifier> refpath; private final boolean lookup; private ObjectIDWithRefPath( final WorkspaceIdentifier wsi, final long id, final String name, final int version, final List<ObjectIdentifier> refpath, final boolean lookup) { super(wsi, id, name, version); this.refpath = refpath; this.lookup = lookup; } @Override public List<ObjectIdentifier> getRefPath() { return refpath == null ? Collections.emptyList() : refpath; } @Override public boolean hasRefPath() { return refpath != null; } @Override public ObjectIdentifier getLast() { if (!hasRefPath()) { throw new IllegalStateException("This object identifier has no reference path"); } return refpath.get(refpath.size() - 1); } @Override public boolean isLookupRequired() { return lookup; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (lookup ? 1231 : 1237); result = prime * result + ((refpath == null) ? 0 : refpath.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } ObjectIDWithRefPath other = (ObjectIDWithRefPath) obj; if (lookup != other.lookup) { return false; } if (refpath == null) { if (other.refpath != null) { return false; } } else if (!refpath.equals(other.refpath)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ObjectIDWithRefPath [refpath="); builder.append(refpath); builder.append(", lookup="); builder.append(lookup); builder.append(", getWorkspaceIdentifier()="); builder.append(getWorkspaceIdentifier()); builder.append(", getName()="); builder.append(getName()); builder.append(", getId()="); builder.append(getID()); builder.append(", getVersion()="); builder.append(getVersion()); builder.append("]"); return builder.toString(); } } private static class ObjIDWithRefPathAndSubset extends ObjectIDWithRefPath { private final SubsetSelection subset; private ObjIDWithRefPathAndSubset( final WorkspaceIdentifier wsi, final long id, final String name, final int version, final List<ObjectIdentifier> refpath, final boolean lookup, final SubsetSelection subset) { super(wsi, id, name, version, refpath, lookup); this.subset = subset; } @Override public SubsetSelection getSubSet() { return subset; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((subset == null) ? 0 : subset.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; ObjIDWithRefPathAndSubset other = (ObjIDWithRefPathAndSubset) obj; if (subset == null) { if (other.subset != null) return false; } else if (!subset.equals(other.subset)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ObjIDWithRefPathAndSubset [subset="); builder.append(subset); builder.append(", getRefPath()="); builder.append(getRefPath()); builder.append(", isLookupRequired()="); builder.append(isLookupRequired()); builder.append(", getWorkspaceIdentifier()="); builder.append(getWorkspaceIdentifier()); builder.append(", getName()="); builder.append(getName()); builder.append(", getId()="); builder.append(getID()); builder.append(", getVersion()="); builder.append(getVersion()); builder.append("]"); return builder.toString(); } } /** Get a builder for an {@link ObjectIdentifier}. * @param wsi the workspace identifier for the object. * @return a new builder. */ public static Builder getBuilder(final WorkspaceIdentifier wsi) { return new Builder(wsi); } /** Get a builder for an {@link ObjectIdentifier} starting with the same. * @param oi the object identifier from which to initialize the build. * @return a new builder. */ public static Builder getBuilder(final ObjectIdentifier oi) { return new Builder(oi); } /** Get a builder given an object reference. Notably, reference paths will cause an error. * If a reference path is permissible input, use {@link #getBuilderFromRefPath(String)}. * @param reference the object reference. * @return a new builder. */ public static Builder getBuilder(final String reference) { return new Builder(reference); } /** Get a builder given an object reference or reference path. * Example: "my_ws/my_obj/5;6/7;ws1/obj2;6/7/8" * * @param reference the object reference or path. * @return a new builder. */ public static Builder getBuilderFromRefPath(final String refpath) { return new Builder(refpath, true); } /** Create a copy of the input builder. * @param b the builder to copy. * @return a new builder with the same state as the input builder. */ public static Builder getBuilder(final Builder b) { return new Builder(b); } /** A builder for an {@link ObjectIdentifier}. */ public static class Builder { private WorkspaceIdentifier wsi; private String name = null; private long id = -1; private int version = -1; private List<ObjectIdentifier> refpath = null; private boolean lookup = false; private SubsetSelection subset = SubsetSelection.EMPTY; private Builder(final WorkspaceIdentifier wsi) { this.wsi = requireNonNull(wsi, "wsi"); } private Builder(final ObjectIdentifier oi) { this.wsi = requireNonNull(oi, "oi").getWorkspaceIdentifier(); this.id = oi.getID().orElse(-1L); this.name = oi.getName().orElse(null); this.version = oi.getVersion().orElse(-1); this.refpath = oi.getRefPath().isEmpty() ? null : oi.getRefPath(); this.lookup = oi.isLookupRequired(); this.subset = oi.getSubSet(); } private Builder(final Builder b) { this.wsi = requireNonNull(b, "b").wsi; this.id = b.id; this.name = b.name; this.version = b.version; this.refpath = b.refpath; // immutable so safe to make a shallow copy this.lookup = b.lookup; this.subset = b.subset; } private Builder(final String reference) { checkString(reference, "reference"); processReference(reference, this, false, false); } private Builder(final String refpath, boolean ignored) { processReferencePath(refpath, this, false); } /** Set a name for the object. This will remove any previously set ID. * @param name the objects's name. null is treated as a no-op. * @return this builder. */ public Builder withName(final String name) { if (name != null) { this.name = checkObjectName(name); this.id = -1; } return this; } /** Behaves identically to {@link #withName(String)}, except that optionally if an ID * is already set an error can be thrown. * @param name the name of the object. null is treated as a no-op. * @param throwError true to throw an error if the ID is already set. * @return this builder */ public Builder withName(final String name, boolean throwError) { if (throwError && id > 0) { xorNameId(name, id, "object"); // reuse the error generating code } return withName(name); } /** Set an ID for the object. This will remove any previously set name. * @param id the object's ID, which must be > 0. null is treated as a no-op. * @return this builder. */ public Builder withID(final Long id) { if (id != null) { this.id = checkID(id); this.name = null; } return this; } /** Behaves identically to {@link #withID(Long)}, except that optionally if a name * is already set an error can be thrown. * @param id the object's ID, which must be > 0. null is treated as a no-op. * @param throwError true to throw an error if the name is already set. * @return this builder. */ public Builder withID(final Long id, boolean throwError) { if (throwError && name != null) { xorNameId(name, id, "object"); // reuse the error generating code } return withID(id); } /** Set the version of this object. Passing null removes any previously set version. * @param version the object's version, which must be > 0. * @return this builder. */ public Builder withVersion(final Integer version) { this.version = checkVersion(version); return this; } public Builder withLookupRequired(final boolean lookupRequired) { this.lookup = lookupRequired; this.refpath = lookupRequired ? null : this.refpath; return this; } /** Add a reference path to a target object from the head of the path, where the path * head is not included and is represented by this {@link ObjectIdentifier}. * @param refpath the reference path. Passing a null or empty list will remove any * previously set path. If the case is otherwise, the lookup required flag will be set * to false. * @return this builder. */ public Builder withReferencePath(final List<ObjectIdentifier> refpath) { if (refpath == null || refpath.isEmpty()) { this.refpath = null; } else { noNulls(refpath, "Nulls are not allowed in reference paths"); // make immutable and prevent alteration by mutating the input list this.refpath = Collections.unmodifiableList(new ArrayList<>(refpath)); this.lookup = false; } return this; } /** Add a specification of what parts of the object to return. * @param subset the subset of the object to return. * @return this builder. */ public Builder withSubsetSelection(final SubsetSelection subset) { this.subset = subset == null ? SubsetSelection.EMPTY : subset; return this; } /** Build the {@link ObjectIdentifier}. One of {@link #withName(String)}, * {@link #withName(String, boolean), {@link #withID(Long)}, or * {@link #withID(Long, boolean)} must have been called successfully prior to building. * @return the identifier. */ public ObjectIdentifier build() { xorNameId(name, id < 1 ? null : id, "object"); // reuse error creation if (!subset.equals(SubsetSelection.EMPTY)) { return new ObjIDWithRefPathAndSubset( wsi, id, name, version, refpath, lookup, subset); } else if (lookup || refpath != null) { return new ObjectIDWithRefPath(wsi, id, name, version, refpath, lookup); } else { return new ObjectIdentifier(wsi, id, name, version); } } } }
package vg.civcraft.mc.prisonpearl; import java.util.logging.Level; import org.bukkit.Bukkit; import vg.civcraft.mc.civmodcore.ACivMod; import vg.civcraft.mc.prisonpearl.command.PrisonPearlCommandHandler; import vg.civcraft.mc.prisonpearl.database.DataBaseHandler; import vg.civcraft.mc.prisonpearl.listener.AltsListListener; import vg.civcraft.mc.prisonpearl.listener.BanListener; import vg.civcraft.mc.prisonpearl.listener.BetterShardsListener; import vg.civcraft.mc.prisonpearl.listener.CombatTagListener; import vg.civcraft.mc.prisonpearl.listener.DamageListener; import vg.civcraft.mc.prisonpearl.listener.MercuryListener; import vg.civcraft.mc.prisonpearl.listener.PlayerListener; import vg.civcraft.mc.prisonpearl.listener.PrisonPortaledPlayerListener; import vg.civcraft.mc.prisonpearl.managers.AltsListManager; import vg.civcraft.mc.prisonpearl.managers.BanManager; import vg.civcraft.mc.prisonpearl.managers.BroadcastManager; import vg.civcraft.mc.prisonpearl.managers.CombatTagManager; import vg.civcraft.mc.prisonpearl.managers.DamageLogManager; import vg.civcraft.mc.prisonpearl.managers.MercuryManager; import vg.civcraft.mc.prisonpearl.managers.NameLayerManager; import vg.civcraft.mc.prisonpearl.managers.PrisonPearlManager; import vg.civcraft.mc.prisonpearl.managers.PrisonPortaledPlayerManager; import vg.civcraft.mc.prisonpearl.managers.SummonManager; import vg.civcraft.mc.prisonpearl.managers.WorldBorderManager; public class PrisonPearlPlugin extends ACivMod { private static PrisonPearlPlugin plugin; private static DataBaseHandler dbHandle; // This class handles both the save/load and getting storage types. private static AltsListManager altsManager; private static BanManager banManager; private static BroadcastManager broadManager; private static CombatTagManager combatManager; private static DamageLogManager damageManager; private static MercuryManager mercuryManager; private static NameLayerManager namelayerManager; private static WorldBorderManager worldborderManager; private static PrisonPearlManager pearlManager; private static PrisonPortaledPlayerManager portaledManager; private static SummonManager summonManager; public void onEnable() { super.onEnable(); plugin = this; // It would be best to load the storage first so all managers have it available; dbHandle = new DataBaseHandler(); dbHandle.getSaveLoadHandler().load(); handleManagers(); handleListeners(); // Register commands. PrisonPearlCommandHandler handle = new PrisonPearlCommandHandler(); setCommandHandler(handle); handle.registerCommands(); new PrisonPearlUtil(); } public void onDisable() { super.onDisable(); dbHandle.getSaveLoadHandler().save(); } private void handleManagers() { altsManager = new AltsListManager(); banManager = BanManager.initialize(); broadManager = new BroadcastManager(); combatManager = new CombatTagManager(plugin.getServer(), plugin.getLogger()); damageManager = new DamageLogManager(); mercuryManager = new MercuryManager(); namelayerManager = new NameLayerManager(); worldborderManager = new WorldBorderManager(); pearlManager = new PrisonPearlManager(); portaledManager = new PrisonPortaledPlayerManager(); summonManager = new SummonManager(); } private void handleListeners() { new AltsListListener(); new BanListener(); new DamageListener(); new MercuryListener(); new PlayerListener(); new PrisonPortaledPlayerListener(); new CombatTagListener(); new BetterShardsListener(); } @Override protected String getPluginName() { return "PrisonPearl"; } public static DataBaseHandler getDBHandler() { return dbHandle; } public static BanManager getBanManager() { return banManager; } public static AltsListManager getAltsListManager() { return altsManager; } public static BroadcastManager getBroadcastManager() { return broadManager; } public static CombatTagManager getCombatTagManager() { return combatManager; } public static DamageLogManager getDamageLogManager() { return damageManager; } public static MercuryManager getMercuryManager() { return mercuryManager; } public static NameLayerManager getNameLayerManager() { return namelayerManager; } public static PrisonPearlManager getPrisonPearlManager() { return pearlManager; } public static PrisonPortaledPlayerManager getPrisonPortaledPlayerManager() { return portaledManager; } public static SummonManager getSummonManager() { return summonManager; } public static WorldBorderManager getWorldBorderManager() { return worldborderManager; } public static PrisonPearlPlugin getInstance() { return plugin; } public static void log(String message) { plugin.getLogger().log(Level.INFO, message); } public static boolean isNameLayerEnabled() { return Bukkit.getPluginManager().isPluginEnabled("NameLayer"); } public static boolean isCBanManagementEnabled() { return Bukkit.getPluginManager().isPluginEnabled("CBanManagement"); } public static boolean isMercuryEnabled() { return Bukkit.getPluginManager().isPluginEnabled("Mercury"); } public static boolean isBetterShardsEnabled() { return Bukkit.getPluginManager().isPluginEnabled("BetterShards"); } public static boolean isWorldBorderEnabled() { return Bukkit.getPluginManager().isPluginEnabled("WorldBorder"); } }
package sax; import java.io.PrintWriter; import org.xml.sax.Attributes; import org.xml.sax.Parser; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.ParserAdapter; import org.xml.sax.helpers.ParserFactory; /** * A sample SAX2 counter. This sample program illustrates how to * register a SAX2 ContentHandler and receive the callbacks in * order to print information about the document. The output of * this program shows the time and count of elements, attributes, * ignorable whitespaces, and characters appearing in the document. * <p> * This class is useful as a "poor-man's" performance tester to * compare the speed and accuracy of various SAX parsers. However, * it is important to note that the first parse time of a parser * will include both VM class load time and parser initialization * that would not be present in subsequent parses with the same * file. * <p> * <strong>Note:</strong> The results produced by this program * should never be accepted as true performance measurements. * * @author Andy Clark, IBM * * @version $Id$ */ public class Counter extends DefaultHandler { // Constants // feature ids protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces"; protected static final String NAMESPACE_PREFIXES_FEATURE_ID = "http://xml.org/sax/features/namespace-prefixes"; protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation"; protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema"; protected static final String DYNAMIC_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/dynamic"; // default settings /** Default parser name. */ protected static final String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser"; /** Default repetition (1). */ protected static final int DEFAULT_REPETITION = 1; /** Default namespaces support (true). */ protected static final boolean DEFAULT_NAMESPACES = true; /** Default namespace prefixes (false). */ protected static final boolean DEFAULT_NAMESPACE_PREFIXES = false; /** Default validation support (false). */ protected static final boolean DEFAULT_VALIDATION = false; /** Default Schema validation support (true). */ protected static final boolean DEFAULT_SCHEMA_VALIDATION = true; /** Default dynamic validation support (false). */ protected static final boolean DEFAULT_DYNAMIC_VALIDATION = false; /** Default memory usage report (false). */ protected static final boolean DEFAULT_MEMORY_USAGE = false; /** Default "tagginess" report (false). */ protected static final boolean DEFAULT_TAGGINESS = false; // Data /** Number of elements. */ protected long fElements; /** Number of attributes. */ protected long fAttributes; /** Number of characters. */ protected long fCharacters; /** Number of ignorable whitespace characters. */ protected long fIgnorableWhitespace; /** Number of characters of tags. */ protected long fTagCharacters; /** Number of other content characters for the "tagginess" calculation. */ protected long fOtherCharacters; // Constructors /** Default constructor. */ public Counter() { } // <init>() // Public methods /** Prints the results. */ public void printResults(PrintWriter out, String uri, long time, long memory, boolean tagginess, int repetition) { // filename.xml: 631 ms (4 elems, 0 attrs, 78 spaces, 0 chars) out.print(uri); out.print(": "); if (repetition == 1) { out.print(time); } else { out.print(time); out.print('/'); out.print(repetition); out.print('='); out.print(time/repetition); } out.print(" ms"); if (memory != Long.MIN_VALUE) { out.print(", "); out.print(memory); out.print(" bytes"); } out.print(" ("); out.print(fElements); out.print(" elems, "); out.print(fAttributes); out.print(" attrs, "); out.print(fIgnorableWhitespace); out.print(" spaces, "); out.print(fCharacters); out.print(" chars)"); if (tagginess) { out.print(' '); long totalCharacters = fTagCharacters + fOtherCharacters + fCharacters + fIgnorableWhitespace; long tagValue = fTagCharacters * 100 / totalCharacters; out.print(tagValue); out.print("% tagginess"); } out.println(); out.flush(); } // printResults(PrintWriter,String,long) // ContentHandler methods /** Start document. */ public void startDocument() throws SAXException { fElements = 0; fAttributes = 0; fCharacters = 0; fIgnorableWhitespace = 0; fTagCharacters = 0; } // startDocument() /** Start element. */ public void startElement(String uri, String local, String raw, Attributes attrs) throws SAXException { fElements++; fTagCharacters++; // open angle bracket fTagCharacters += raw.length(); if (attrs != null) { int attrCount = attrs.getLength(); fAttributes += attrCount; for (int i = 0; i < attrCount; i++) { fTagCharacters++; // space fTagCharacters += attrs.getQName(i).length(); fTagCharacters++; fTagCharacters++; // open quote fOtherCharacters += attrs.getValue(i).length(); fTagCharacters++; // close quote } } fTagCharacters++; // close angle bracket } // startElement(String,String,StringAttributes) /** Characters. */ public void characters(char ch[], int start, int length) throws SAXException { fCharacters += length; } // characters(char[],int,int); /** Ignorable whitespace. */ public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { fIgnorableWhitespace += length; } // ignorableWhitespace(char[],int,int); /** Processing instruction. */ public void processingInstruction(String target, String data) throws SAXException { fTagCharacters += 2; fTagCharacters += target.length(); if (data != null && data.length() > 0) { fTagCharacters++; // space fOtherCharacters += data.length(); } fTagCharacters += 2; } // processingInstruction(String,String) // ErrorHandler methods /** Warning. */ public void warning(SAXParseException ex) throws SAXException { printError("Warning", ex); } // warning(SAXParseException) /** Error. */ public void error(SAXParseException ex) throws SAXException { printError("Error", ex); } // error(SAXParseException) /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { printError("Fatal Error", ex); //throw ex; } // fatalError(SAXParseException) // Protected methods /** Prints the error message. */ protected void printError(String type, SAXParseException ex) { System.err.print("["); System.err.print(type); System.err.print("] "); if (ex== null) { System.out.println("!!!"); } String systemId = ex.getSystemId(); if (systemId != null) { int index = systemId.lastIndexOf('/'); if (index != -1) systemId = systemId.substring(index + 1); System.err.print(systemId); } System.err.print(':'); System.err.print(ex.getLineNumber()); System.err.print(':'); System.err.print(ex.getColumnNumber()); System.err.print(": "); System.err.print(ex.getMessage()); System.err.println(); System.err.flush(); } // printError(String,SAXParseException) // MAIN /** Main program entry point. */ public static void main(String argv[]) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables Counter counter = new Counter(); PrintWriter out = new PrintWriter(System.out); XMLReader parser = null; int repetition = DEFAULT_REPETITION; boolean namespaces = DEFAULT_NAMESPACES; boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES; boolean validation = DEFAULT_VALIDATION; boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION; boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION; boolean memoryUsage = DEFAULT_MEMORY_USAGE; boolean tagginess = DEFAULT_TAGGINESS; // process arguments for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("p")) { // get parser name if (++i == argv.length) { System.err.println("error: Missing argument to -p option."); continue; } String parserName = argv[i]; // create parser try { parser = XMLReaderFactory.createXMLReader(parserName); } catch (Exception e) { try { Parser sax1Parser = ParserFactory.makeParser(parserName); parser = new ParserAdapter(sax1Parser); System.err.println("warning: Features and properties not supported on SAX1 parsers."); } catch (Exception ex) { parser = null; System.err.println("error: Unable to instantiate parser ("+parserName+")"); } } continue; } if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number ("+number+")."); } continue; } if (option.equalsIgnoreCase("n")) { namespaces = option.equals("n"); continue; } if (option.equalsIgnoreCase("np")) { namespacePrefixes = option.equals("np"); continue; } if (option.equalsIgnoreCase("v")) { validation = option.equals("v"); continue; } if (option.equalsIgnoreCase("s")) { schemaValidation = option.equals("s"); continue; } if (option.equalsIgnoreCase("dv")) { dynamicValidation = option.equals("dv"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equalsIgnoreCase("t")) { tagginess = option.equals("t"); continue; } if (option.equals("-rem")) { if (++i == argv.length) { System.err.println("error: Missing argument to -# option."); continue; } System.out.print(" System.out.println(argv[i]); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } // use default parser? if (parser == null) { // create parser try { parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME); } catch (Exception e) { System.err.println("error: Unable to instantiate parser ("+DEFAULT_PARSER_NAME+")"); continue; } } // set parser features try { parser.setFeature(NAMESPACES_FEATURE_ID, namespaces); } catch (SAXException e) { System.err.println("warning: Parser does not support feature ("+NAMESPACES_FEATURE_ID+")"); } try { parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID, namespacePrefixes); } catch (SAXException e) { System.err.println("warning: Parser does not support feature ("+NAMESPACE_PREFIXES_FEATURE_ID+")"); } try { parser.setFeature(VALIDATION_FEATURE_ID, validation); } catch (SAXException e) { System.err.println("warning: Parser does not support feature ("+VALIDATION_FEATURE_ID+")"); } try { parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature ("+SCHEMA_VALIDATION_FEATURE_ID+")"); } try { parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation); } catch (SAXNotRecognizedException e) { // ignore } catch (SAXNotSupportedException e) { System.err.println("warning: Parser does not support feature ("+DYNAMIC_VALIDATION_FEATURE_ID+")"); } // parse file parser.setContentHandler(counter); parser.setErrorHandler(counter); try { long timeBefore = System.currentTimeMillis(); long memoryBefore = Runtime.getRuntime().freeMemory(); for (int j = 0; j < repetition; j++) { parser.parse(arg); } long memoryAfter = Runtime.getRuntime().freeMemory(); long timeAfter = System.currentTimeMillis(); long time = timeAfter - timeBefore; long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE; counter.printResults(out, arg, time, memory, tagginess, repetition); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); Exception se = e; if (e instanceof SAXException) { se = ((SAXException)e).getException(); } if (se != null) se.printStackTrace(System.err); else e.printStackTrace(System.err); } } } // main(String[]) // Private static methods /** Prints the usage. */ private static void printUsage() { System.err.println("usage: java sax.Counter (options) uri ..."); System.err.println(); System.err.println("options:"); System.err.println(" -p name Select parser by name."); System.err.println(" -x number Select number of repetitions."); System.err.println(" -n | -N Turn on/off namespace processing."); System.err.println(" -np | -NP Turn on/off namespace prefixes."); System.err.println(" NOTE: Requires use of -n."); System.err.println(" -v | -V Turn on/off validation."); System.err.println(" -s | -S Turn on/off Schema validation support."); System.err.println(" NOTE: Not supported by all parsers."); System.err.println(" -dv | -DV Turn on/off dynamic validation."); System.err.println(" NOTE: Requires use of -v and not supported by all parsers."); System.err.println(" -m | -M Turn on/off memory usage report"); System.err.println(" -t | -T Turn on/off \"tagginess\" report."); System.err.println(" --rem text Output user defined comment before next parse."); System.err.println(" -h This help screen."); System.err.println(); System.err.println("defaults:"); System.err.println(" Parser: "+DEFAULT_PARSER_NAME); System.err.println(" Repetition: "+DEFAULT_REPETITION); System.err.print(" Namespaces: "); System.err.println(DEFAULT_NAMESPACES ? "on" : "off"); System.err.print(" Prefixes: "); System.err.println(DEFAULT_NAMESPACE_PREFIXES ? "on" : "off"); System.err.print(" Validation: "); System.err.println(DEFAULT_VALIDATION ? "on" : "off"); System.err.print(" Schema: "); System.err.println(DEFAULT_SCHEMA_VALIDATION ? "on" : "off"); System.err.print(" Dynamic: "); System.err.println(DEFAULT_DYNAMIC_VALIDATION ? "on" : "off"); System.err.print(" Memory: "); System.err.println(DEFAULT_MEMORY_USAGE ? "on" : "off"); System.err.print(" Tagginess: "); System.err.println(DEFAULT_TAGGINESS ? "on" : "off"); System.err.println(); System.err.println("notes:"); System.err.println(" The speed and memory results from this program should NOT be used as the"); System.err.println(" basis of parser performance comparison! Real analytical methods should be"); System.err.println(" used. For better results, perform multiple document parses within the same"); System.err.println(" virtual machine to remove class loading from parse time and memory usage."); System.err.println(); System.err.println(" The \"tagginess\" measurement gives a rough estimate of the percentage of"); System.err.println(" markup versus content in the XML document. The percent tagginess of a "); System.err.println(" document is equal to the minimum amount of tag characters required for "); System.err.println(" elements, attributes, and processing instructions divided by the total"); System.err.println(" amount of characters (characters, ignorable whitespace, and tag characters)"); System.err.println(" in the document."); System.err.println(); System.err.println(" Not all features are supported by different parsers."); } // printUsage() } // class Counter
package org.objectweb.asm.xml; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import junit.framework.TestCase; import junit.framework.TestSuite; import org.objectweb.asm.ClassReader; import org.objectweb.asm.util.TraceClassVisitor; import sun.misc.HexDumpEncoder; /** * RoundtripTest * * @author Eugene Kuleshov */ public class RoundtripTest extends TestCase { private String className; public RoundtripTest( String className) { super( "testRoundtrip"); this.className = className; } public static TestSuite suite() throws Exception { TestSuite suite = new TestSuite( RoundtripTest.class.getName()); Class c = RoundtripTest.class; String u = c.getResource( "/java/lang/String.class").toString(); int n = u.indexOf( '!'); ZipInputStream zis = new ZipInputStream( new URL( u.substring( 4, n)).openStream()); ZipEntry ze = null; while(( ze = zis.getNextEntry())!=null) { if( ze.getName().endsWith( ".class")) { suite.addTest( new RoundtripTest( u.substring( 0, n+2).concat( ze.getName()))); } } return suite; } public void testRoundtrip() throws Exception { byte[] classData = getCode( new URL( className).openStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SAXTransformerFactory saxtf = ( SAXTransformerFactory) TransformerFactory.newInstance(); // Templates templates = saxtf.newTemplates( new StreamSource( getClass().getResourceAsStream( "copy.xsl"))); // TransformerHandler handler = saxtf.newTransformerHandler( templates); TransformerHandler handler = saxtf.newTransformerHandler(); handler.setResult( new SAXResult( new ASMContentHandler( bos, true))); handler.startDocument(); ClassReader cr = new ClassReader( classData); cr.accept( new SAXClassAdapter( handler, cr.getVersion(), false), false); handler.endDocument(); byte[] newData = bos.toByteArray(); try { StringWriter sw1 = new StringWriter(); StringWriter sw2 = new StringWriter(); traceBytecode( classData, new PrintWriter( sw1)); traceBytecode( newData, new PrintWriter( sw2)); assertEquals( "different data", sw1.getBuffer().toString(), sw2.getBuffer().toString()); } catch( Exception ex) { HexDumpEncoder enc = new HexDumpEncoder(); assertEquals( "invaid data", enc.encode( classData), enc.encode( newData)); } } private static void traceBytecode( byte[] classData, PrintWriter pw) { ClassReader cr = new ClassReader( classData); // cr.accept( new TraceClassVisitor( cw, new PrintWriter( System.out)), cr.accept( new TraceClassVisitor( null, pw), false); } private static byte[] getCode( InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buff = new byte[ 1024]; int n = -1; while(( n = is.read( buff))>-1) bos.write( buff, 0, n); return bos.toByteArray(); } // workaround for Ant's JUnit test runner public String getName() { return super.getName()+" : "+className; } }
class E002_ModifiersMethodDeclatations { public int publicInt() { return 5; } protected int protectedInt() { return 5; } int defaultInt() { return 5; } private privateInt() { return 5; } public final int publicFinalInt() { return 5; } final int defaultFinalInt() { return 5; } public synchronized int publicSynchronizedInt() { return 5; } synchronized int defaultSynchronizedInt() { return 5; } public final synchronized int publicFinalSynchronizedInt() { return 5; } final synchronized int defaultFinalSynchronizedInt() { return 5; } public static int publicStaticInt() { return 5; } static int defaultStaticInt() { return 5; } public static final int publicStaticFinalInt() { return 5; } static final int defaultStaticFinalInt() { return 5; } public static final synchronized int publicStaticFinalSynchronizedInt() { return 5; } static final synchronized int defaultStaticFinalSynchronizedInt() { return 5; } public native int publicNativeInt(); native int defaultNativeInt(); public strictfp int publicStrictFpInt() { return 5; } strictfp int defaultStrictFpInt() { return 5; } public static final synchronized strictfp int publicLotsInt() { return 5; } static final synchronized strictfp int defaultLotsInt() { return 5; } }
package voldemort.performance; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import joptsimple.OptionParser; import joptsimple.OptionSet; import voldemort.ServerTestUtils; import voldemort.client.protocol.admin.AdminClient; import voldemort.cluster.Cluster; import voldemort.cluster.Node; import voldemort.utils.ByteArray; import voldemort.utils.Pair; import voldemort.versioning.Versioned; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; public class AdminTest { private final String storeName; private final AdminClient adminClient; public static interface Measurable { long apply(); } public static interface Timed { void apply(); } private static final String usageStr = "Usage: $VOLDEMORT_HOME/bin/admin-test.sh \\\n" + "\t [options] bootstrapUrl storeName"; public AdminTest(String bootstrapUrl, String storeName) { this(bootstrapUrl, storeName, false); } public AdminTest(String bootstrapUrl, String storeName, boolean useNative) { this.storeName = storeName; this.adminClient = ServerTestUtils.getAdminClient(bootstrapUrl); } public static void printUsage(PrintStream out, OptionParser parser, String msg) throws IOException { out.println(msg); out.println(usageStr); parser.printHelpOn(out); System.exit(1); } public static void printUsage(PrintStream out, OptionParser parser) throws IOException { out.println(usageStr); parser.printHelpOn(out); System.exit(1); } private List<Integer> getNodes(int partition) { List<Integer> rv = new LinkedList<Integer>(); Cluster cluster = adminClient.getCluster(); for(Node node: cluster.getNodes()) { if(node.getPartitionIds().contains(partition)) rv.add(node.getId()); } return rv; } private List<Integer> getPartitions(int nodeId) { Cluster cluster = adminClient.getCluster(); Node node = cluster.getNodeById(nodeId); return node.getPartitionIds(); } public static void measureFunction(Measurable fn, int count) { long ops = 0; long start = System.currentTimeMillis(); for(int i = 0; i < count; i++) { ops += fn.apply(); } long totalTime = System.currentTimeMillis() - start; System.out.println("Throughput: " + (ops / (double) totalTime * 1000) + " ops / sec."); System.out.println(ops + " ops carried out."); } public static void timeFunction(Timed fn, int count) { long start = System.currentTimeMillis(); for(int i = 0; i < count; i++) { fn.apply(); } long totalTime = System.currentTimeMillis() - start; System.out.println("Total time: " + totalTime / 1000); } protected SetMultimap<Integer, Integer> getNodePartitions(List<?> optNodes, List<?> optPartitions) { SetMultimap<Integer, Integer> nodePartitions = HashMultimap.create(); if(optPartitions != null && optNodes != null) { for(Object node: optNodes) { for(Object partition: optPartitions) nodePartitions.put((Integer) node, (Integer) partition); } } else if(optPartitions != null) { for(Object partition: optPartitions) { for(Integer node: getNodes((Integer) partition)) { nodePartitions.put(node, (Integer) partition); } } } else if(optNodes != null) { for(Object node: optNodes) { nodePartitions.putAll((Integer) node, getPartitions((Integer) node)); } } else throw new IllegalStateException(); return nodePartitions; } public void testFetch(final SetMultimap<Integer, Integer> nodePartitions) { for(final Integer node: nodePartitions.keySet()) { System.out.println("Testing fetch of node " + node + " partitions " + nodePartitions.get(node) + ": \n"); measureFunction(new Measurable() { public long apply() { long i = 0; Iterator<Pair<ByteArray, Versioned<byte[]>>> result = adminClient.fetchPartitionEntries(node, storeName, new ArrayList<Integer>(nodePartitions.get(node)), null); while(result.hasNext()) { i++; result.next(); } return i; } }, 1); } } public void testFetchAndUpdate(final SetMultimap<Integer, Integer> from, final int to) { for(final Integer node: from.keySet()) { timeFunction(new Timed() { public void apply() { adminClient.fetchAndUpdateStreams(node, to, storeName, new ArrayList<Integer>(from.get(node)), null); } }, 1); } } public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); parser.accepts("native", "use native admin client"); parser.accepts("f", "execute fetch operation"); parser.accepts("fu", "fetch and update").withRequiredArg().ofType(Integer.class); parser.accepts("n", "node id") .withRequiredArg() .ofType(Integer.class) .withValuesSeparatedBy(','); parser.accepts("p", "partition id") .withRequiredArg() .ofType(Integer.class) .withValuesSeparatedBy(','); OptionSet options = parser.parse(args); List<String> nonOptions = options.nonOptionArguments(); String bootstrapUrl = nonOptions.get(0); String storeName = nonOptions.get(1); if(!options.has("p") && !options.has("n")) { printUsage(System.err, parser, "One or more node and/or one or more partition has" + " to be specified"); } AdminTest adminTest; if(options.has("native")) adminTest = new AdminTest(bootstrapUrl, storeName, true); else adminTest = new AdminTest(bootstrapUrl, storeName); SetMultimap<Integer, Integer> nodePartitions = adminTest.getNodePartitions(options.has("n") ? options.valuesOf("n") : null, options.has("p") ? options.valuesOf("p") : null); if (options.has("f")) adminTest.testFetch(nodePartitions); if (options.has("fu")) adminTest.testFetchAndUpdate(nodePartitions, (Integer) options.valueOf("fu")); } }
package org.concurrentmockito; import static org.mockito.Mockito.*; import org.junit.Test; import org.mockitousage.IMethods; import org.mockitoutil.TestBase; //TODO make sure tests for mockito run quickly on slower machines //this test exposes the problem at least once in 10 runs public class ThreadsShareAMockTest extends TestBase { private IMethods mock; @Test public void testShouldAllowVerifyingInThreads() throws Exception { for(int i = 0; i < 100; i++) { performTest(); } } private void performTest() throws InterruptedException { mock = mock(IMethods.class); final Thread[] listeners = new Thread[3]; for (int i = 0; i < listeners.length; i++) { listeners[i] = new Thread() { @Override public void run() { mock.simpleMethod("foo"); } }; listeners[i].start(); } for (int i = 0; i < listeners.length; i++) { listeners[i].join(); } verify(mock, times(listeners.length)).simpleMethod("foo"); } }
package org.bouncycastle.asn1.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DERGeneralizedTime; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERPrintableString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.X509DefaultEntryConverter; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; public class X509NameTest extends SimpleTest { String[] subjects = { "C=AU,ST=Victoria,L=South Melbourne,O=Connect 4 Pty Ltd,OU=Webserver Team,CN=www2.connect4.com.au,E=webmaster@connect4.com.au", "C=AU,ST=Victoria,L=South Melbourne,O=Connect 4 Pty Ltd,OU=Certificate Authority,CN=Connect 4 CA,E=webmaster@connect4.com.au", "C=AU,ST=QLD,CN=SSLeay/rsa test cert", "C=US,O=National Aeronautics and Space Administration,SERIALNUMBER=16+CN=Steve Schoch", "E=cooke@issl.atl.hp.com,C=US,OU=Hewlett Packard Company (ISSL),CN=Paul A. Cooke", "O=Sun Microsystems Inc,CN=store.sun.com", "unstructuredAddress=192.168.1.33,unstructuredName=pixfirewall.ciscopix.com,CN=pixfirewall.ciscopix.com", "CN=*.canal-plus.com,OU=Provided by TBS INTERNET http: "O=Bouncy Castle,CN=www.bouncycastle.org\\ ", "O=Bouncy Castle,CN=c:\\\\fred\\\\bob" }; public String getName() { return "X509Name"; } private static X509Name fromBytes( byte[] bytes) throws IOException { return X509Name.getInstance(new ASN1InputStream(new ByteArrayInputStream(bytes)).readObject()); } private ASN1Encodable createEntryValue(DERObjectIdentifier oid, String value) { Hashtable attrs = new Hashtable(); attrs.put(oid, value); Vector order = new Vector(); order.addElement(oid); X509Name name = new X509Name(order, attrs); ASN1Sequence seq = (ASN1Sequence)name.toASN1Primitive(); ASN1Set set = (ASN1Set)seq.getObjectAt(0); seq = (ASN1Sequence)set.getObjectAt(0); return seq.getObjectAt(1); } private ASN1Encodable createEntryValueFromString(DERObjectIdentifier oid, String value) { Hashtable attrs = new Hashtable(); attrs.put(oid, value); Vector order = new Vector(); order.addElement(oid); X509Name name = new X509Name(new X509Name(order, attrs).toString()); ASN1Sequence seq = (ASN1Sequence)name.toASN1Primitive(); ASN1Set set = (ASN1Set)seq.getObjectAt(0); seq = (ASN1Sequence)set.getObjectAt(0); return seq.getObjectAt(1); } private void testEncodingPrintableString(DERObjectIdentifier oid, String value) { ASN1Encodable converted = createEntryValue(oid, value); if (!(converted instanceof DERPrintableString)) { fail("encoding for " + oid + " not printable string"); } } private void testEncodingIA5String(DERObjectIdentifier oid, String value) { ASN1Encodable converted = createEntryValue(oid, value); if (!(converted instanceof DERIA5String)) { fail("encoding for " + oid + " not IA5String"); } } private void testEncodingUTF8String(DERObjectIdentifier oid, String value) throws IOException { ASN1Encodable converted = createEntryValue(oid, value); if (!(converted instanceof DERUTF8String)) { fail("encoding for " + oid + " not IA5String"); } if (!value.equals((DERUTF8String.getInstance(converted.toASN1Primitive().getEncoded()).getString()))) { fail("decoding not correct"); } } private void testEncodingGeneralizedTime(DERObjectIdentifier oid, String value) { ASN1Encodable converted = createEntryValue(oid, value); if (!(converted instanceof DERGeneralizedTime)) { fail("encoding for " + oid + " not GeneralizedTime"); } converted = createEntryValueFromString(oid, value); if (!(converted instanceof DERGeneralizedTime)) { fail("encoding for " + oid + " not GeneralizedTime"); } } public void performTest() throws Exception { testEncodingPrintableString(X509Name.C, "AU"); testEncodingPrintableString(X509Name.SERIALNUMBER, "123456"); testEncodingPrintableString(X509Name.DN_QUALIFIER, "123456"); testEncodingIA5String(X509Name.EmailAddress, "test@test.com"); testEncodingIA5String(X509Name.DC, "test"); // correct encoding testEncodingGeneralizedTime(X509Name.DATE_OF_BIRTH, "#180F32303032303132323132323232305A"); // compatibility encoding testEncodingGeneralizedTime(X509Name.DATE_OF_BIRTH, "20020122122220Z"); testEncodingUTF8String(X509Name.CN, "Mörsky"); // composite Hashtable attrs = new Hashtable(); attrs.put(X509Name.C, "AU"); attrs.put(X509Name.O, "The Legion of the Bouncy Castle"); attrs.put(X509Name.L, "Melbourne"); attrs.put(X509Name.ST, "Victoria"); attrs.put(X509Name.E, "feedback-crypto@bouncycastle.org"); Vector order = new Vector(); order.addElement(X509Name.C); order.addElement(X509Name.O); order.addElement(X509Name.L); order.addElement(X509Name.ST); order.addElement(X509Name.E); X509Name name1 = new X509Name(order, attrs); if (!name1.equals(name1)) { fail("Failed same object test"); } if (!name1.equals(name1, true)) { fail("Failed same object test - in Order"); } X509Name name2 = new X509Name(order, attrs); if (!name1.equals(name2)) { fail("Failed same name test"); } if (!name1.equals(name2, true)) { fail("Failed same name test - in Order"); } if (name1.hashCode() != name2.hashCode()) { fail("Failed same name test - in Order"); } Vector ord1 = new Vector(); ord1.addElement(X509Name.C); ord1.addElement(X509Name.O); ord1.addElement(X509Name.L); ord1.addElement(X509Name.ST); ord1.addElement(X509Name.E); Vector ord2 = new Vector(); ord2.addElement(X509Name.E); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (!name1.equals(name2)) { fail("Failed reverse name test"); } if (name1.hashCode() != name2.hashCode()) { fail("Failed reverse name test hashCode"); } if (name1.equals(name2, true)) { fail("Failed reverse name test - in Order"); } if (!name1.equals(name2, false)) { fail("Failed reverse name test - in Order false"); } Vector oids = name1.getOIDs(); if (!compareVectors(oids, ord1)) { fail("oid comparison test"); } Vector val1 = new Vector(); val1.addElement("AU"); val1.addElement("The Legion of the Bouncy Castle"); val1.addElement("Melbourne"); val1.addElement("Victoria"); val1.addElement("feedback-crypto@bouncycastle.org"); name1 = new X509Name(ord1, val1); Vector values = name1.getValues(); if (!compareVectors(values, val1)) { fail("value comparison test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed different name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed subset name test"); } compositeTest(); ByteArrayOutputStream bOut; ASN1OutputStream aOut; ASN1InputStream aIn; // getValues test Vector v1 = name1.getValues(X509Name.O); if (v1.size() != 1 || !v1.elementAt(0).equals("The Legion of the Bouncy Castle")) { fail("O test failed"); } Vector v2 = name1.getValues(X509Name.L); if (v2.size() != 1 || !v2.elementAt(0).equals("Melbourne")) { fail("L test failed"); } // general subjects test for (int i = 0; i != subjects.length; i++) { X509Name name = new X509Name(subjects[i]); bOut = new ByteArrayOutputStream(); aOut = new ASN1OutputStream(bOut); aOut.writeObject(name); aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray())); name = X509Name.getInstance(aIn.readObject()); if (!name.toString().equals(subjects[i])) { fail("failed regeneration test " + i + " got " + name.toString()); } } // sort test X509Name unsorted = new X509Name("SERIALNUMBER=BBB + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SERIALNUMBER=BBB")) { fail("failed sort test 1"); } unsorted = new X509Name("CN=AA + SERIALNUMBER=BBB"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SERIALNUMBER=BBB")) { fail("failed sort test 2"); } unsorted = new X509Name("SERIALNUMBER=B + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SERIALNUMBER=B+CN=AA")) { fail("failed sort test 3"); } unsorted = new X509Name("CN=AA + SERIALNUMBER=B"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SERIALNUMBER=B+CN=AA")) { fail("failed sort test 4"); } // equality tests equalityTest(new X509Name("CN=The Legion"), new X509Name("CN=The Legion")); equalityTest(new X509Name("CN= The Legion"), new X509Name("CN=The Legion")); equalityTest(new X509Name("CN=The Legion "), new X509Name("CN=The Legion")); equalityTest(new X509Name("CN= The Legion "), new X509Name("CN=The Legion")); equalityTest(new X509Name("CN= the legion "), new X509Name("CN=The Legion")); // # test X509Name n1 = new X509Name("SERIALNUMBER=8,O=ABC,CN=ABC Class 3 CA,C=LT"); X509Name n2 = new X509Name("2.5.4.5=8,O=ABC,CN=ABC Class 3 CA,C=LT"); X509Name n3 = new X509Name("2.5.4.5=#130138,O=ABC,CN=ABC Class 3 CA,C=LT"); equalityTest(n1, n2); equalityTest(n2, n3); equalityTest(n3, n1); n1 = new X509Name(true, "2.5.4.5=#130138,CN=SSC Class 3 CA,O=UAB Skaitmeninio sertifikavimo centras,C=LT"); n2 = new X509Name(true, "SERIALNUMBER=#130138,CN=SSC Class 3 CA,O=UAB Skaitmeninio sertifikavimo centras,C=LT"); n3 = X509Name.getInstance(ASN1Primitive.fromByteArray(Hex.decode("3063310b3009060355040613024c54312f302d060355040a1326" + "55414220536b6169746d656e696e696f20736572746966696b6176696d6f2063656e74726173311730150603550403130e53534320436c6173732033204341310a30080603550405130138"))); equalityTest(n1, n2); equalityTest(n2, n3); equalityTest(n3, n1); n1 = new X509Name("SERIALNUMBER=8,O=XX,CN=ABC Class 3 CA,C=LT"); n2 = new X509Name("2.5.4.5=8,O=,CN=ABC Class 3 CA,C=LT"); if (n1.equals(n2)) { fail("empty inequality check failed"); } n1 = new X509Name("SERIALNUMBER=8,O=,CN=ABC Class 3 CA,C=LT"); n2 = new X509Name("2.5.4.5=8,O=,CN=ABC Class 3 CA,C=LT"); equalityTest(n1, n2); // inequality to sequences name1 = new X509Name("CN=The Legion"); if (name1.equals(new DERSequence())) { fail("inequality test with sequence"); } if (name1.equals(new DERSequence(new DERSet()))) { fail("inequality test with sequence and set"); } ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier("1.1")); v.add(new DERObjectIdentifier("1.1")); if (name1.equals(new DERSequence(new DERSet(new DERSet(v))))) { fail("inequality test with sequence and bad set"); } if (name1.equals(new DERSequence(new DERSet(new DERSet(v))), true)) { fail("inequality test with sequence and bad set"); } if (name1.equals(new DERSequence(new DERSet(new DERSequence())))) { fail("inequality test with sequence and short sequence"); } if (name1.equals(new DERSequence(new DERSet(new DERSequence())), true)) { fail("inequality test with sequence and short sequence"); } v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier("1.1")); v.add(new DERSequence()); if (name1.equals(new DERSequence(new DERSet(new DERSequence(v))))) { fail("inequality test with sequence and bad sequence"); } if (name1.equals(null)) { fail("inequality test with null"); } if (name1.equals(null, true)) { fail("inequality test with null"); } // this is contrived but it checks sorting of sets with equal elements unsorted = new X509Name("CN=AA + CN=AA + CN=AA"); // tagging test - only works if CHOICE implemented /* ASN1TaggedObject tag = new DERTaggedObject(false, 1, new X509Name("CN=AA")); if (!tag.isExplicit()) { fail("failed to explicitly tag CHOICE object"); } X509Name name = X509Name.getInstance(tag, false); if (!name.equals(new X509Name("CN=AA"))) { fail("failed to recover tagged name"); } */ DERUTF8String testString = new DERUTF8String("The Legion of the Bouncy Castle"); byte[] encodedBytes = testString.getEncoded(); byte[] hexEncodedBytes = Hex.encode(encodedBytes); String hexEncodedString = "#" + new String(hexEncodedBytes); DERUTF8String converted = (DERUTF8String) new X509DefaultEntryConverter().getConvertedValue( X509Name.L , hexEncodedString); if (!converted.equals(testString)) { fail("failed X509DefaultEntryConverter test"); } // try escaped. converted = (DERUTF8String) new X509DefaultEntryConverter().getConvertedValue( X509Name.L , "\\" + hexEncodedString); if (!converted.equals(new DERUTF8String(hexEncodedString))) { fail("failed X509DefaultEntryConverter test got " + converted + " expected: " + hexEncodedString); } // try a weird value X509Name n = new X509Name("CN=\\#nothex#string"); if (!n.toString().equals("CN=\\#nothex#string")) { fail("# string not properly escaped."); } Vector vls = n.getValues(X509Name.CN); if (vls.size() != 1 || !vls.elementAt(0).equals("#nothex#string")) { fail("escaped # not reduced properly"); } n = new X509Name("CN=\"a+b\""); vls = n.getValues(X509Name.CN); if (vls.size() != 1 || !vls.elementAt(0).equals("a+b")) { fail("escaped + not reduced properly"); } n = new X509Name("CN=a\\+b"); vls = n.getValues(X509Name.CN); if (vls.size() != 1 || !vls.elementAt(0).equals("a+b")) { fail("escaped + not reduced properly"); } if (!n.toString().equals("CN=a\\+b")) { fail("+ in string not properly escaped."); } n = new X509Name("CN=a\\=b"); vls = n.getValues(X509Name.CN); if (vls.size() != 1 || !vls.elementAt(0).equals("a=b")) { fail("escaped = not reduced properly"); } if (!n.toString().equals("CN=a\\=b")) { fail("= in string not properly escaped."); } n = new X509Name("TELEPHONENUMBER=\"+61999999999\""); vls = n.getValues(X509Name.TELEPHONE_NUMBER); if (vls.size() != 1 || !vls.elementAt(0).equals("+61999999999")) { fail("telephonenumber escaped + not reduced properly"); } n = new X509Name("TELEPHONENUMBER=\\+61999999999"); vls = n.getValues(X509Name.TELEPHONE_NUMBER); if (vls.size() != 1 || !vls.elementAt(0).equals("+61999999999")) { fail("telephonenumber escaped + not reduced properly"); } // migration X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addMultiValuedRDN(new ASN1ObjectIdentifier[] { BCStyle.CN, BCStyle.SN }, new String[] { "Thomas", "CVR:12341233-UID:1111" }); builder.addRDN(BCStyle.O, "Test"); builder.addRDN(BCStyle.C, "DK"); X500Name subject = builder.build(); ASN1Primitive derObject = subject.toASN1Primitive(); X509Name instance = X509Name.getInstance(derObject); } private boolean compareVectors(Vector a, Vector b) // for compatibility with early JDKs { if (a.size() != b.size()) { return false; } for (int i = 0; i != a.size(); i++) { if (!a.elementAt(i).equals(b.elementAt(i))) { return false; } } return true; } private void compositeTest() throws IOException { // composite test byte[] enc = Hex.decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65"); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(enc)); X509Name n = X509Name.getInstance(aIn.readObject()); if (!n.toString().equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale")) { fail("Failed composite to string test got: " + n.toString()); } if (!n.toString(true, X509Name.DefaultSymbols).equals("L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU")) { fail("Failed composite to string test got: " + n.toString(true, X509Name.DefaultSymbols)); } n = new X509Name(true, "L=Melbourne+OU=Ascot Vale,O=The Legion of the Bouncy Castle,C=AU"); if (!n.toString().equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale")) { fail("Failed composite to string reversal test got: " + n.toString()); } n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(n); byte[] enc2 = bOut.toByteArray(); if (!Arrays.areEqual(enc, enc2)) { //fail("Failed composite string to encoding test"); } // dud name test - handle empty DN without barfing. n = new X509Name("C=CH,O=,OU=dummy,CN=mail@dummy.com"); n = X509Name.getInstance(ASN1Primitive.fromByteArray(n.getEncoded())); } private void equalityTest(X509Name x509Name, X509Name x509Name1) { if (!x509Name.equals(x509Name1)) { fail("equality test failed for " + x509Name + " : " + x509Name1); } if (x509Name.hashCode() != x509Name1.hashCode()) { fail("hashCodeTest test failed for " + x509Name + " : " + x509Name1); } if (!x509Name.equals(x509Name1, true)) { fail("equality test failed for " + x509Name + " : " + x509Name1); } } public static void main( String[] args) { runTest(new X509NameTest()); } }
package com.ecyrd.jspwiki.plugin; import com.ecyrd.jspwiki.*; import junit.framework.*; import java.io.*; import java.util.*; public class PluginManagerTest extends TestCase { public static final String NAME1 = "Test1"; Properties props = new Properties(); WikiEngine engine; WikiContext context; PluginManager manager; public PluginManagerTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); engine = new TestEngine2(props); context = new WikiContext( engine, "testpage" ); manager = new PluginManager(); } public void tearDown() { } public void testSimpleInsert() throws Exception { String res = manager.execute( context, "{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text=foobar}"); assertEquals( "foobar", res ); } public void testSimpleInsertNoPackage() throws Exception { String res = manager.execute( context, "{INSERT SamplePlugin WHERE text=foobar}"); assertEquals( "foobar", res ); } public void testSimpleInsert2() throws Exception { String res = manager.execute( context, "{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text = foobar2, moo=blat}"); assertEquals( "foobar2", res ); } /** Missing closing brace */ public void testSimpleInsert3() throws Exception { String res = manager.execute( context, "{INSERT com.ecyrd.jspwiki.plugin.SamplePlugin WHERE text = foobar2, moo=blat"); assertEquals( "foobar2", res ); } public static Test suite() { return new TestSuite( PluginManagerTest.class ); } }
package org.jgroups.blocks; import org.jgroups.Address; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.View; import org.jgroups.protocols.FRAG; import org.jgroups.protocols.FRAG2; import org.jgroups.protocols.TP; import org.jgroups.stack.Protocol; import org.jgroups.tests.ChannelTestBase; import org.jgroups.util.Rsp; import org.jgroups.util.RspList; import org.jgroups.util.Util; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A collection of tests to test the RpcDispatcher. * * NOTE on processing return values: * * The method RspDispatcher.callRemoteMethods(...) returns an RspList, containing one Rsp * object for each group member receiving the RPC call. Rsp.getValue() returns the * value returned by the RPC call from the corresponding member. Rsp.getValue() may * contain several classes of values, depending on what happened during the call: * * (i) a value of the expected return data type, if the RPC call completed successfully * (ii) null, if the RPC call timed out before the value could be returned * (iii) an object of type java.lang.Throwable, if an exception (e.g. lava.lang.OutOfMemoryException) * was raised during the processing of the call * * It is wise to check for such cases when processing RpcDispatcher calls. * * This also applies to the return value of callRemoteMethod(...). * * @author Bela Ban * @version $Id: RpcDispatcherTest.java,v 1.26 2009/04/30 12:47:19 belaban Exp $ */ @Test(groups=Global.STACK_DEPENDENT,sequential=false) public class RpcDispatcherTest extends ChannelTestBase { RpcDispatcher disp1, disp2, disp3; JChannel c1, c2, c3; // specify return values sizes which should work correctly with 64Mb heap final static int[] SIZES={10000, 20000, 40000, 80000, 100000, 200000, 400000, 800000, 1000000, 2000000, 5000000}; // specify return value sizes which may generate timeouts or OOMEs with 64Mb heap final static int[] HUGESIZES={10000000, 20000000}; @BeforeMethod protected void setUp() throws Exception { c1=createChannel(true, 3); final String GROUP="RpcDispatcherTest"; disp1=new RpcDispatcher(c1, null, null, new ServerObject(1)); c1.connect(GROUP); c2=createChannel(c1); disp2=new RpcDispatcher(c2, null, null, new ServerObject(2)); c2.connect(GROUP); c3=createChannel(c1); disp3=new RpcDispatcher(c3, null, null, new ServerObject(3)); c3.connect(GROUP); System.out.println("c1.view=" + c1.getView() + "\nc2.view=" + c2.getView() + "\nc3.view=" + c3.getView()); View view=c3.getView(); assert view.size() == 3 : "view=" + view; } @AfterMethod protected void tearDown() throws Exception { disp3.stop(); disp2.stop(); disp1.stop(); Util.close(c3, c2, c1); } public void testEmptyConstructor() throws Exception { RpcDispatcher d1=new RpcDispatcher(), d2=new RpcDispatcher(); JChannel channel1=null, channel2=null; final String GROUP=getUniqueClusterName("RpcDispatcherTest"); try { channel1=createChannel(true, 2); channel2=createChannel(channel1); d1.setChannel(channel1); d2.setChannel(channel2); d1.setServerObject(new ServerObject(1)); d2.setServerObject(new ServerObject(2)); d1.start(); d2.start(); channel1.connect(GROUP); channel2.connect(GROUP); Util.sleep(500); View view=channel2.getView(); System.out.println("view channel 2= " + view); view=channel1.getView(); System.out.println("view channel 1= " + view); assert view.size() == 2; RspList rsps=d1.callRemoteMethods(null, "foo", null, (Class[])null, GroupRequest.GET_ALL, 5000); System.out.println("rsps:\n" + rsps); assert rsps.size() == 2; for(Rsp rsp: rsps.values()) { assert rsp.wasReceived(); assert !rsp.wasSuspected(); assert rsp.getValue() != null; } Object server_object=new Object() { public long foobar() { return System.currentTimeMillis(); } }; d1.setServerObject(server_object); d2.setServerObject(server_object); rsps=d2.callRemoteMethods(null, "foobar", null, (Class[])null, GroupRequest.GET_ALL, 5000); System.out.println("rsps:\n" + rsps); assert rsps.size() == 2; for(Rsp rsp: rsps.values()) { assert rsp.wasReceived(); assert !rsp.wasSuspected(); assert rsp.getValue() != null; } } finally { d2.stop(); d1.stop(); Util.close(channel2, channel1); } } /** * Test the response filter mechanism which can be used to filter responses received with * a call to RpcDispatcher. * * The test filters requests based on the id of the server object they were received * from, and only accept responses from servers with id > 1. * * The expected behaviour is that the response from server 1 is rejected, but the responses * from servers 2 and 3 are accepted. * */ public void testResponseFilter() { final long timeout = 10 * 1000 ; RspList rsps=disp1.callRemoteMethods(null, "foo", null, null,GroupRequest.GET_ALL, timeout, false, new RspFilter() { int num=0; public boolean isAcceptable(Object response, Address sender) { boolean retval=((Integer)response).intValue() > 1; // System.out.println("-- received " + response + " from " + // sender + ": " + (retval ? "OK" : "NOTOK")); if(retval) num++; return retval; } public boolean needMoreResponses() { return num < 2; } }); System.out.println("responses are:\n" + rsps); assertEquals("there should be three response values", 3, rsps.size()); assertEquals("number of responses received should be 2", 2, rsps.numReceived()); } public void testFuture() throws Exception { MethodCall sleep=new MethodCall("sleep", new Object[]{1000L}, new Class[]{long.class}); Future<RspList> future; future=disp1.callRemoteMethodsWithFuture(null, sleep, GroupRequest.GET_ALL, 5000L, false, false, null); assert !future.isDone(); assert !future.isCancelled(); try { future.get(300, TimeUnit.MILLISECONDS); assert false : "we should not get here, get(300) should have thrown a TimeoutException"; } catch(TimeoutException e) { System.out.println("got TimeoutException - as expected"); } assert !future.isDone(); RspList result=future.get(3000L, TimeUnit.MILLISECONDS); System.out.println("result:\n" + result); assert result != null; assert result.size() == 3; assert future.isDone(); } public void testMultipleFutures() throws Exception { MethodCall sleep=new MethodCall("sleep", new Object[]{100L}, new Class[]{long.class}); List<Future<RspList>> futures=new ArrayList<Future<RspList>>(); long target=System.currentTimeMillis() + 30000L; Future<RspList> future; for(int i=0; i < 10; i++) { future=disp1.callRemoteMethodsWithFuture(null, sleep, GroupRequest.GET_ALL, 30000L, false, false, null); futures.add(future); } List<Future<RspList>> rsps=new ArrayList<Future<RspList>>(); while(!futures.isEmpty() && System.currentTimeMillis() < target) { for(Iterator<Future<RspList>> it=futures.iterator(); it.hasNext();) { future=it.next(); if(future.isDone()) { it.remove(); rsps.add(future); } } System.out.println("pending responses: " + futures.size()); Util.sleep(200); } System.out.println("\n" + rsps.size() + " responses:\n"); for(Future<RspList> tmp: rsps) { System.out.println(tmp); } } public void testFutureCancel() throws Exception { MethodCall sleep=new MethodCall("sleep", new Object[]{1000L}, new Class[]{long.class}); Future<RspList> future; future=disp1.callRemoteMethodsWithFuture(null, sleep, GroupRequest.GET_ALL, 5000L, false, false, null); assert !future.isDone(); assert !future.isCancelled(); future.cancel(true); assert future.isDone(); assert future.isCancelled(); } /** * Test the ability of RpcDispatcher to handle large argument and return values * with multicast RPC calls. * * The test sends requests for return values (byte arrays) having increasing sizes, * which increase the processing time for requests as well as the amount of memory * required to process requests. * * The expected behaviour is that all RPC requests complete successfully. * */ public void testLargeReturnValue() { setProps(c1, c2, c3); for(int i=0; i < SIZES.length; i++) { _testLargeValue(SIZES[i]); } } /** * Test the ability of RpcDispatcher to handle huge argument and return values * with multicast RPC calls. * * The test sends requests for return values (byte arrays) having increasing sizes, * which increase the processing time for requests as well as the amount of memory * required to process requests. * * The expected behaviour is that RPC requests either timeout or trigger out of * memory exceptions. Huge return values extend the processing time required; but * the length of time depends upon the speed of the machine the test runs on. * */ /*@Test(groups="first") public void testHugeReturnValue() { setProps(c1, c2, c3); for(int i=0; i < HUGESIZES.length; i++) { _testHugeValue(HUGESIZES[i]); } }*/ public void testMethodInvocationToNonExistingMembers() { final int timeout = 5 * 1000 ; // get the current membership, as seen by C View view=c3.getView(); Vector<Address> members=view.getMembers(); System.out.println("list is " + members); // cause C to leave the group and close its channel System.out.println("closing c3"); c3.close(); Util.sleep(1000); // make an RPC call using C's now outdated view of membership System.out.println("calling method foo() in " + members + " (view=" + c2.getView() + ")"); RspList rsps=disp1.callRemoteMethods(members, "foo", null, (Class[])null, GroupRequest.GET_ALL, timeout); // all responses System.out.println("responses:\n" + rsps); for(Map.Entry<Address,Rsp> entry: rsps.entrySet()) { Rsp rsp=entry.getValue(); assertTrue("response from " + entry.getKey() + " was not received", rsp.wasReceived()); assertFalse(rsp.wasSuspected()); } } /** * Test the ability of RpcDispatcher to handle large argument and return values * with unicast RPC calls. * * The test sends requests for return values (byte arrays) having increasing sizes, * which increase the processing time for requests as well as the amount of memory * required to process requests. * * The expected behaviour is that all RPC requests complete successfully. * */ public void testLargeReturnValueUnicastCall() throws Throwable { setProps(c1, c2, c3); for(int i=0; i < SIZES.length; i++) { _testLargeValueUnicastCall(c1.getAddress(), SIZES[i]); } } private static void setProps(JChannel... channels) { for(JChannel ch: channels) { Protocol prot=ch.getProtocolStack().findProtocol("FRAG2"); if(prot != null) { ((FRAG2)prot).setFragSize(12000); } prot=ch.getProtocolStack().findProtocol("FRAG"); if(prot != null) { ((FRAG)prot).setFragSize(12000); } prot=ch.getProtocolStack().getTransport(); if(prot != null) ((TP)prot).setMaxBundleSize(14000); } } /** * Helper method to perform a RPC call on server method "returnValue(int size)" for * all group members. * * The method checks that each returned value is non-null and has the correct size. * */ void _testLargeValue(int size) { // 20 second timeout final long timeout = 20 * 1000 ; System.out.println("\ntesting with " + size + " bytes"); RspList rsps=disp1.callRemoteMethods(null, "largeReturnValue", new Object[]{size}, new Class[]{int.class}, GroupRequest.GET_ALL, timeout); System.out.println("rsps:"); assert rsps.size() == 3 : "there should be three responses to the RPC call but only " + rsps.size() + " were received: " + rsps; for(Map.Entry<Address,Rsp> entry: rsps.entrySet()) { // its possible that an exception was raised in processing Object obj = entry.getValue().getValue() ; // this should not happen assert !(obj instanceof Throwable) : "exception was raised in processing reasonably sized argument"; byte[] val=(byte[]) obj; assert val != null; System.out.println(val.length + " bytes from " + entry.getValue().getSender()); assert val.length == size : "return value does not match required size"; } } /** * Helper method to perform a RPC call on server method "returnValue(int size)" for * all group members. * * This method need to take into account that RPC calls can timeout with huge values, * and they can also trigger OOMEs. But if we are lucky, they can also return * reasonable values. * */ void _testHugeValue(int size) { // 20 second timeout final long timeout = 20 * 1000 ; System.out.println("\ntesting with " + size + " bytes"); RspList rsps=disp1.callRemoteMethods(null, "largeReturnValue", new Object[]{size}, new Class[]{int.class}, GroupRequest.GET_ALL, timeout); System.out.println("rsps:"); assert rsps != null; assert rsps.size() == 3 : "there should be three responses to the RPC call but only " + rsps.size() + " were received: " + rsps; // in checking the return values, we need to take account of timeouts (i.e. when // a null value is returned) and exceptions for(Map.Entry<Address,Rsp> entry: rsps.entrySet()) { Object obj = entry.getValue().getValue() ; // its possible that an exception was raised if (obj instanceof java.lang.Throwable) { Throwable t = (Throwable) obj ; System.out.println(t.toString() + " exception was raised processing argument from " + entry.getValue().getSender() + " -this is expected") ; continue ; } // its possible that the request timed out before the serve could reply if (obj == null) { System.out.println("request timed out processing argument from " + entry.getValue().getSender() + " - this is expected") ; continue ; } // if we reach here, we sould have a reasobable value byte[] val=(byte[]) obj; System.out.println(val.length + " bytes from " + entry.getValue().getSender()); assert val.length == size : "return value does not match required size"; } } /** * Helper method to perform a RPC call on server method "returnValue(int size)" for * an individual group member. * * The method checks that the returned value is non-null and has the correct size. * * @param dst the group member * @param size the size of the byte array to be returned * @throws Throwable */ void _testLargeValueUnicastCall(Address dst, int size) throws Throwable { // 20 second timeout final long timeout = 20 * 1000 ; System.out.println("\ntesting unicast call with " + size + " bytes"); assertNotNull(dst); Object retval=disp1.callRemoteMethod(dst, "largeReturnValue", new Object[]{size}, new Class[]{int.class}, GroupRequest.GET_ALL, timeout); // it's possible that an exception was raised if (retval instanceof java.lang.Throwable) { throw (Throwable)retval; } byte[] val=(byte[])retval; // check value is not null, otherwise fail the test assertNotNull("return value should be non-null", val); System.out.println("rsp: " + val.length + " bytes"); // returned value should have requested size assertEquals("return value does not match requested size", size, val.length); } /** * This class serves as a server obect to turn requests into replies. * It is initialised with an integer id value. * * It implements two functions: * function foo() returns the id of the server * function largeReturnValue(int size) returns a byte array of size 'size' * */ private static class ServerObject { int i; public ServerObject(int i) { this.i=i; } public int foo() {return i;} public static long sleep(long timeout) { // System.out.println("sleep()"); long start=System.currentTimeMillis(); Util.sleep(timeout); return System.currentTimeMillis() - start; } public static byte[] largeReturnValue(int size) { return new byte[size]; } } }
package org.jfree.chart.axis.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.SimpleDateFormat; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.PeriodAxis; import org.jfree.chart.axis.PeriodAxisLabelInfo; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Minute; import org.jfree.data.time.Month; import org.jfree.data.time.Quarter; import org.jfree.data.time.Second; import org.jfree.data.time.Year; /** * Tests for the {@link PeriodAxis} class. */ public class PeriodAxisTests extends TestCase implements AxisChangeListener { /** The last event received. */ private AxisChangeEvent lastEvent; /** * Receives and records an {@link AxisChangeEvent}. * * @param event the event. */ public void axisChanged(AxisChangeEvent event) { this.lastEvent = event; } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(PeriodAxisTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public PeriodAxisTests(String name) { super(name); } /** * Confirm that the equals() method can distinguish all the required fields. */ public void testEquals() { PeriodAxis a1 = new PeriodAxis("Test"); PeriodAxis a2 = new PeriodAxis("Test"); assertTrue(a1.equals(a2)); assertTrue(a2.equals(a1)); a1.setFirst(new Year(2000)); assertFalse(a1.equals(a2)); a2.setFirst(new Year(2000)); assertTrue(a1.equals(a2)); a1.setLast(new Year(2004)); assertFalse(a1.equals(a2)); a2.setLast(new Year(2004)); assertTrue(a1.equals(a2)); a1.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland")); assertFalse(a1.equals(a2)); a2.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland")); assertTrue(a1.equals(a2)); a1.setAutoRangeTimePeriodClass(Quarter.class); assertFalse(a1.equals(a2)); a2.setAutoRangeTimePeriodClass(Quarter.class); assertTrue(a1.equals(a2)); PeriodAxisLabelInfo info[] = new PeriodAxisLabelInfo[1]; info[0] = new PeriodAxisLabelInfo(Month.class, new SimpleDateFormat("MMM")); a1.setLabelInfo(info); assertFalse(a1.equals(a2)); a2.setLabelInfo(info); assertTrue(a1.equals(a2)); a1.setMajorTickTimePeriodClass(Minute.class); assertFalse(a1.equals(a2)); a2.setMajorTickTimePeriodClass(Minute.class); assertTrue(a1.equals(a2)); a1.setMinorTickMarksVisible(!a1.isMinorTickMarksVisible()); assertFalse(a1.equals(a2)); a2.setMinorTickMarksVisible(a1.isMinorTickMarksVisible()); assertTrue(a1.equals(a2)); a1.setMinorTickTimePeriodClass(Minute.class); assertFalse(a1.equals(a2)); a2.setMinorTickTimePeriodClass(Minute.class); assertTrue(a1.equals(a2)); Stroke s = new BasicStroke(1.23f); a1.setMinorTickMarkStroke(s); assertFalse(a1.equals(a2)); a2.setMinorTickMarkStroke(s); assertTrue(a1.equals(a2)); a1.setMinorTickMarkPaint(Color.blue); assertFalse(a1.equals(a2)); a2.setMinorTickMarkPaint(Color.blue); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { PeriodAxis a1 = new PeriodAxis("Test"); PeriodAxis a2 = new PeriodAxis("Test"); assertTrue(a1.equals(a2)); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { PeriodAxis a1 = new PeriodAxis("Test"); PeriodAxis a2 = null; try { a2 = (PeriodAxis) a1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(a1 != a2); assertTrue(a1.getClass() == a2.getClass()); assertTrue(a1.equals(a2)); // some checks that the clone is independent of the original a1.setLabel("New Label"); assertFalse(a1.equals(a2)); a2.setLabel("New Label"); assertTrue(a1.equals(a2)); a1.setFirst(new Year(1920)); assertFalse(a1.equals(a2)); a2.setFirst(new Year(1920)); assertTrue(a1.equals(a2)); a1.setLast(new Year(2020)); assertFalse(a1.equals(a2)); a2.setLast(new Year(2020)); assertTrue(a1.equals(a2)); PeriodAxisLabelInfo[] info = new PeriodAxisLabelInfo[2]; info[0] = new PeriodAxisLabelInfo(Day.class, new SimpleDateFormat("d")); info[1] = new PeriodAxisLabelInfo(Year.class, new SimpleDateFormat("yyyy")); a1.setLabelInfo(info); assertFalse(a1.equals(a2)); a2.setLabelInfo(info); assertTrue(a1.equals(a2)); a1.setAutoRangeTimePeriodClass(Second.class); assertFalse(a1.equals(a2)); a2.setAutoRangeTimePeriodClass(Second.class); assertTrue(a1.equals(a2)); a1.setTimeZone(new SimpleTimeZone(123, "Bogus")); assertFalse(a1.equals(a2)); a2.setTimeZone(new SimpleTimeZone(123, "Bogus")); assertTrue(a1.equals(a2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { PeriodAxis a1 = new PeriodAxis("Test Axis"); PeriodAxis a2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(a1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); a2 = (PeriodAxis) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } boolean b = a1.equals(a2); assertTrue(b); } /** * A test for bug 1932146. */ public void test1932146() { PeriodAxis axis = new PeriodAxis("TestAxis"); axis.addChangeListener(this); this.lastEvent = null; axis.setRange(new DateRange(0L, 1000L)); assertTrue(this.lastEvent != null); } }
package org.openspaces.dsl; import java.util.concurrent.Callable; public class CustomCommand { private String name; private Callable<Object> executeOnce; private Callable<Object> executeOnAllInstances; public String getName() { return name; } public void setName(String name) { this.name = name; } public Callable<Object> getExecuteOnce() { return executeOnce; } public void setExecuteOnce(Callable<Object> executeOnce) { this.executeOnce = executeOnce; } public Callable<Object> getExecuteOnAllInstances() { return executeOnAllInstances; } public void setExecuteOnAllInstances(Callable<Object> executeOnAllInstances) { this.executeOnAllInstances = executeOnAllInstances; } }
package vue.Jeu; import java.util.ArrayList; import org.lwjgl.util.Point; import org.lwjgl.util.Rectangle; import org.newdawn.slick.Animation; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; /** * * @author Christopher Desrosiers Mondor */ public class Ennemi { // Donnee membre private final String ID = "ENNEMI"; private int hp = 100; private float x = 500, y = 500; private float xDest = 300, yDest = 300; private float vitesse = 0.25f; private int direction = 0; private boolean moving = true; private Animation[] animations = new Animation[8]; private boolean onStair = false; private boolean isSelected = false; private Rectangle rectInteraction; private Carte carte; // Constructeur public Ennemi(Carte uneCarte) { this.carte = uneCarte; } // Initialisation public void init() throws SlickException { String file = "data/sprites/people/soldier.png"; SpriteSheet spriteSheet = new SpriteSheet(file, 64, 64); this.animations[0] = loadAnimation(spriteSheet, 0, 1, 0); this.animations[1] = loadAnimation(spriteSheet, 0, 1, 1); this.animations[2] = loadAnimation(spriteSheet, 0, 1, 2); this.animations[3] = loadAnimation(spriteSheet, 0, 1, 3); this.animations[4] = loadAnimation(spriteSheet, 1, 9, 0); this.animations[5] = loadAnimation(spriteSheet, 1, 9, 1); this.animations[6] = loadAnimation(spriteSheet, 1, 9, 2); this.animations[7] = loadAnimation(spriteSheet, 1, 9, 3); this.rectInteraction = new Rectangle(); this.rectInteraction.setHeight(64); this.rectInteraction.setWidth(64); } private Animation loadAnimation(SpriteSheet spriteSheet, int startX, int endX, int y) { Animation animation = new Animation(); for (int x = startX; x < endX; x++) { animation.addFrame(spriteSheet.getSprite(x, y), 100); } return animation; } // Affichage public void render(Graphics g) throws SlickException { g.setColor(new Color(0, 0, 0, .5f)); rectInteraction.setX((int) this.x - 32); rectInteraction.setY((int) this.y - 56); if (isSelected) { g.drawRect(rectInteraction.getX(), rectInteraction.getY(), rectInteraction.getWidth(), rectInteraction.getHeight()); } g.fillOval(x - 16, y - 8, 32, 16); g.drawAnimation(animations[direction + (moving ? 4 : 0)], x - 32, y - 60); } // Methodes specifiques public boolean selection(boolean laValeur) { isSelected = laValeur; return isSelected; } // Methodes de mise a jour public void update(int delta,Joueur unJoueur,ArrayList personnages) { if (this.x <= unJoueur.getCloser(personnages,this).getX() || this.x >= unJoueur.getCloser(personnages,this).getX() || this.y >= unJoueur.getCloser(personnages,this).getY() || this.y <= unJoueur.getCloser(personnages,this).getY()) { float futurX = getFuturX(delta); float futurY = getFuturY(delta); boolean collision = this.carte.isCollision(futurX, futurY); if (collision) { this.moving = false; } else { if (x < unJoueur.getCloser(personnages,this).getX()) { this.x += (int)1*vitesse; } else if (x > unJoueur.getCloser(personnages,this).getX()){ this.x -= (int)1*vitesse; } else if (x == unJoueur.getCloser(personnages,this).getX() && y < unJoueur.getCloser(personnages,this).getY()){ this.setDirection(2); } else if (x == unJoueur.getCloser(personnages,this).getX() && y > unJoueur.getCloser(personnages,this).getY()){ this.setDirection(0); } if (y < unJoueur.getCloser(personnages,this).getY()) { this.y += (int)1*vitesse; } else if (y > unJoueur.getCloser(personnages,this).getY()){ this.y -= (int)1*vitesse; } else if (y == unJoueur.getCloser(personnages,this).getY() && x < unJoueur.getCloser(personnages,this).getX()){ this.setDirection(3); } else if (y == unJoueur.getCloser(personnages,this).getY() && x > unJoueur.getCloser(personnages,this).getX()){ this.setDirection(1); } if (y == unJoueur.getCloser(personnages,this).getY() && x == unJoueur.getCloser(personnages,this).getX()) { this.moving = false; } } } else { this.moving = false; } } private float getFuturX(int delta) { float futurX = this.x; switch (this.direction) { case 1: futurX = this.x - vitesse * delta; break; case 3: futurX = this.x + vitesse * delta; break; } return futurX; } private float getFuturY(int delta) { float futurY = this.y; switch (this.direction) { case 0: futurY = this.y - vitesse * delta; break; case 2: futurY = this.y + vitesse * delta; break; case 1: if (this.onStair) { futurY = this.y + vitesse * delta; } break; case 3: if (this.onStair) { futurY = this.y - vitesse * delta; } break; } return futurY; } public Joueur getCloser(ArrayList listePersonnage,Ennemi unEnnemi){ int distanceActuelle=Integer.MAX_VALUE; Joueur unJoueur,joueurProche=null; for(Object j : listePersonnage){ unJoueur=(Joueur)j; Point joueur = new Point((int)unJoueur.getX(),(int)unJoueur.getY()); Point ennemi = new Point((int)unEnnemi.getX(),(int)unEnnemi.getY()); if(distancePoint(joueur,ennemi)<distanceActuelle){ distanceActuelle=distancePoint(joueur,ennemi); joueurProche=unJoueur; } } return joueurProche; } public int distancePoint(Point un,Point deux){ return (int)Math.sqrt(Math.pow(deux.getY()-un.getY(),2)+Math.pow(deux.getX()-un.getX(),2)); } // Accesseurs et mutateurs public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public void setxDest(int x) { this.xDest = x; } public void setyDest(int y) { this.yDest = y; } public boolean isMoving() { return moving; } public void setMoving(boolean moving) { this.moving = moving; } public boolean isOnStair() { return onStair; } public boolean isSelected() { return this.isSelected; } public void setOnStair(boolean onStair) { this.onStair = onStair; } public Rectangle getRectangle() { return this.rectInteraction; } public String getID(){ return ID; } public int getHP(){ return this.hp; } public void addHP(int amountOfHp){ this.hp += amountOfHp; } public void removeHP(int amountOfHp){ this.hp -= amountOfHp; } }
package vue.Jeu; import java.util.ArrayList; import org.lwjgl.util.Point; import org.lwjgl.util.Rectangle; import org.newdawn.slick.Animation; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; /** * * @author Christopher Desrosiers Mondor */ public class Ennemi { // Donnee membre private final String ID = "ENNEMI"; private int hp = 100; private float x = 500, y = 500; private float xDest = 300, yDest = 300; private float vitesse = 0.25f; private int direction = 0; private boolean moving = true; private Animation[] animations = new Animation[8]; private boolean onStair = false; private boolean isSelected = false; private Rectangle rectInteraction; private Carte carte; private int tempsAttaque = 10; private int nouvelleAttaque= 0; // Constructeur public Ennemi(Carte uneCarte) { this.carte = uneCarte; } // Initialisation public void init() throws SlickException { String file = "data/sprites/people/soldier.png"; SpriteSheet spriteSheet = new SpriteSheet(file, 64, 64); this.animations[0] = loadAnimation(spriteSheet, 0, 1, 0); this.animations[1] = loadAnimation(spriteSheet, 0, 1, 1); this.animations[2] = loadAnimation(spriteSheet, 0, 1, 2); this.animations[3] = loadAnimation(spriteSheet, 0, 1, 3); this.animations[4] = loadAnimation(spriteSheet, 1, 9, 0); this.animations[5] = loadAnimation(spriteSheet, 1, 9, 1); this.animations[6] = loadAnimation(spriteSheet, 1, 9, 2); this.animations[7] = loadAnimation(spriteSheet, 1, 9, 3); this.rectInteraction = new Rectangle(); this.rectInteraction.setHeight(64); this.rectInteraction.setWidth(64); } private Animation loadAnimation(SpriteSheet spriteSheet, int startX, int endX, int y) { Animation animation = new Animation(); for (int x = startX; x < endX; x++) { animation.addFrame(spriteSheet.getSprite(x, y), 100); } return animation; } // Affichage public void render(Graphics g) throws SlickException { g.setColor(new Color(0, 0, 0, .5f)); rectInteraction.setX((int) this.x - 32); rectInteraction.setY((int) this.y - 56); if (isSelected) { g.drawRect(rectInteraction.getX(), rectInteraction.getY(), rectInteraction.getWidth(), rectInteraction.getHeight()); } g.fillOval(x - 16, y - 8, 32, 16); g.drawAnimation(animations[direction + (moving ? 4 : 0)], x - 32, y - 60); } // Methodes specifiques public boolean selection(boolean laValeur) { isSelected = laValeur; return isSelected; } // Methodes de mise a jour public void update(int delta, Joueur unJoueur, ArrayList personnages) { if (!personnages.isEmpty()) { if (this.x <= unJoueur.getCloser(personnages, this).getX() || this.x >= unJoueur.getCloser(personnages, this).getX() || this.y >= unJoueur.getCloser(personnages, this).getY() || this.y <= unJoueur.getCloser(personnages, this).getY()) { float futurX = getFuturX(delta); float futurY = getFuturY(delta); boolean collision = this.carte.isCollision(futurX, futurY); if (collision) { this.moving = false; } else { if (x < unJoueur.getCloser(personnages, this).getX()) { this.x += (int) 1 * vitesse; } else if (x > unJoueur.getCloser(personnages, this).getX()) { this.x -= (int) 1 * vitesse; } else if (x == unJoueur.getCloser(personnages, this).getX() && y < unJoueur.getCloser(personnages, this).getY()) { this.setDirection(2); } else if (x == unJoueur.getCloser(personnages, this).getX() && y > unJoueur.getCloser(personnages, this).getY()) { this.setDirection(0); } if (y < unJoueur.getCloser(personnages, this).getY()) { this.y += (int) 1 * vitesse; } else if (y > unJoueur.getCloser(personnages, this).getY()) { this.y -= (int) 1 * vitesse; } else if (y == unJoueur.getCloser(personnages, this).getY() && x < unJoueur.getCloser(personnages, this).getX()) { this.setDirection(3); } else if (y == unJoueur.getCloser(personnages, this).getY() && x > unJoueur.getCloser(personnages, this).getX()) { this.setDirection(1); } if (y == unJoueur.getCloser(personnages, this).getY() && x == unJoueur.getCloser(personnages, this).getX()) { this.moving = false; } } } else { this.moving = false; } }else this.moving=false; } private float getFuturX(int delta) { float futurX = this.x; switch (this.direction) { case 1: futurX = this.x - vitesse * delta; break; case 3: futurX = this.x + vitesse * delta; break; } return futurX; } private float getFuturY(int delta) { float futurY = this.y; switch (this.direction) { case 0: futurY = this.y - vitesse * delta; break; case 2: futurY = this.y + vitesse * delta; break; case 1: if (this.onStair) { futurY = this.y + vitesse * delta; } break; case 3: if (this.onStair) { futurY = this.y - vitesse * delta; } break; } return futurY; } public Joueur getCloser(ArrayList listePersonnage, Ennemi unEnnemi) { int distanceActuelle = Integer.MAX_VALUE; Joueur unJoueur, joueurProche = null; for (Object j : listePersonnage) { unJoueur = (Joueur) j; Point joueur = new Point((int) unJoueur.getX(), (int) unJoueur.getY()); Point ennemi = new Point((int) unEnnemi.getX(), (int) unEnnemi.getY()); if (distancePoint(joueur, ennemi) < distanceActuelle) { distanceActuelle = distancePoint(joueur, ennemi); joueurProche = unJoueur; } } return joueurProche; } public int distancePoint(Point un, Point deux) { return (int) Math.sqrt(Math.pow(deux.getY() - un.getY(), 2) + Math.pow(deux.getX() - un.getX(), 2)); } // Accesseurs et mutateurs public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public void setxDest(int x) { this.xDest = x; } public void setyDest(int y) { this.yDest = y; } public boolean isMoving() { return moving; } public void setMoving(boolean moving) { this.moving = moving; } public boolean isOnStair() { return onStair; } public boolean isSelected() { return this.isSelected; } public void setOnStair(boolean onStair) { this.onStair = onStair; } public Rectangle getRectangle() { return this.rectInteraction; } public String getID() { return ID; } public int getHP() { return this.hp; } public void addHP(int amountOfHp) { this.hp += amountOfHp; } public void removeHP(int amountOfHp) { this.hp -= amountOfHp; } public void attaque(Joueur unJoueur, int amoutOfHp, int tempsJeu){ if(tempsJeu > nouvelleAttaque){ unJoueur.removeHP(amoutOfHp); this.setNouvelleAttaque(tempsJeu); } } public void setNouvelleAttaque(int tempsJeu){ this.nouvelleAttaque = tempsJeu + this.tempsAttaque; } }
package org.bimserver; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.bimserver.database.DatabaseSession; import org.bimserver.database.actions.ProgressListener; import org.bimserver.database.queries.QueryObjectProvider; import org.bimserver.database.queries.om.Include; import org.bimserver.database.queries.om.JsonQueryObjectModelConverter; import org.bimserver.database.queries.om.Query; import org.bimserver.database.queries.om.QueryPart; import org.bimserver.emf.PackageMetaData; import org.bimserver.emf.Schema; import org.bimserver.geometry.Matrix; import org.bimserver.models.geometry.GeometryPackage; import org.bimserver.models.store.RenderEnginePluginConfiguration; import org.bimserver.models.store.User; import org.bimserver.models.store.UserSettings; import org.bimserver.plugins.PluginConfiguration; import org.bimserver.plugins.renderengine.EntityNotFoundException; import org.bimserver.plugins.renderengine.IndexFormat; import org.bimserver.plugins.renderengine.Precision; import org.bimserver.plugins.renderengine.RenderEngine; import org.bimserver.plugins.renderengine.RenderEngineException; import org.bimserver.plugins.renderengine.RenderEngineFilter; import org.bimserver.plugins.renderengine.RenderEngineGeometry; import org.bimserver.plugins.renderengine.RenderEngineInstance; import org.bimserver.plugins.renderengine.RenderEngineModel; import org.bimserver.plugins.renderengine.RenderEngineSettings; import org.bimserver.plugins.serializers.ObjectProvider; import org.bimserver.plugins.serializers.OidConvertingSerializer; import org.bimserver.plugins.serializers.StreamingSerializer; import org.bimserver.plugins.serializers.StreamingSerializerPlugin; import org.bimserver.renderengine.RenderEnginePool; import org.bimserver.shared.HashMapVirtualObject; import org.bimserver.shared.HashMapWrappedVirtualObject; import org.bimserver.shared.QueryContext; import org.bimserver.shared.VirtualObject; import org.bimserver.shared.WrappedVirtualObject; import org.bimserver.shared.exceptions.UserException; import org.bimserver.utils.Formatters; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EStructuralFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StreamingGeometryGenerator extends GenericGeometryGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(StreamingGeometryGenerator.class); private final BimServer bimServer; private final Map<Integer, Long> hashes = new ConcurrentHashMap<>(); private EClass productClass; private EStructuralFeature geometryFeature; private EStructuralFeature representationFeature; private PackageMetaData packageMetaData; private AtomicLong bytesSaved = new AtomicLong(); private AtomicLong totalBytes = new AtomicLong(); private AtomicLong saveableColorBytes = new AtomicLong(); private AtomicInteger jobsDone = new AtomicInteger(); private AtomicInteger jobsTotal = new AtomicInteger(); private ProgressListener progressListener; private volatile boolean allJobsPushed; private int maxObjectsPerFile = 10; private volatile boolean running = true; public StreamingGeometryGenerator(final BimServer bimServer, ProgressListener progressListener) { this.bimServer = bimServer; this.progressListener = progressListener; } public class Runner implements Runnable { private EClass eClass; private RenderEngineSettings renderEngineSettings; private RenderEngineFilter renderEngineFilter; private RenderEngineFilter renderEngineFilterTransformed = new RenderEngineFilter(true); private StreamingSerializerPlugin ifcSerializerPlugin; private GenerateGeometryResult generateGeometryResult; private ObjectProvider objectProvider; private QueryContext queryContext; private DatabaseSession databaseSession; private RenderEnginePool renderEnginePool; private Query originalQuery; public Runner(EClass eClass, RenderEnginePool renderEnginePool, DatabaseSession databaseSession, RenderEngineSettings renderEngineSettings, ObjectProvider objectProvider, StreamingSerializerPlugin ifcSerializerPlugin, RenderEngineFilter renderEngineFilter, GenerateGeometryResult generateGeometryResult, QueryContext queryContext, Query originalQuery) { this.eClass = eClass; this.renderEnginePool = renderEnginePool; this.databaseSession = databaseSession; this.renderEngineSettings = renderEngineSettings; this.objectProvider = objectProvider; this.ifcSerializerPlugin = ifcSerializerPlugin; this.renderEngineFilter = renderEngineFilter; this.generateGeometryResult = generateGeometryResult; this.queryContext = queryContext; this.originalQuery = originalQuery; } @Override public void run() { try { HashMapVirtualObject next; next = objectProvider.next(); Query query = new Query("test", packageMetaData); QueryPart queryPart = query.createQueryPart(); while (next != null) { queryPart.addOid(next.getOid()); // for (EReference eReference : next.eClass().getEAllReferences()) { // Object ref = next.eGet(eReference); // if (ref != null) { // if (eReference.isMany()) { // List<?> list = (List<?>)ref; // int index = 0; // for (Object o : list) { // if (o != null) { // if (o instanceof Long) { // if (next.useFeatureForSerialization(eReference, index)) { // queryPart.addOid((Long)o); // } else { // System.out.println(); // index++; // } else { // if (ref instanceof Long) { // if (next.useFeatureForSerialization(eReference)) { // queryPart.addOid((Long)ref); next = objectProvider.next(); } objectProvider = new QueryObjectProvider(databaseSession, bimServer, query, Collections.singleton(queryContext.getRoid()), packageMetaData); StreamingSerializer ifcSerializer = ifcSerializerPlugin.createSerializer(new PluginConfiguration()); RenderEngine renderEngine = null; byte[] bytes = null; try { final Set<HashMapVirtualObject> objects = new HashSet<>(); ObjectProviderProxy proxy = new ObjectProviderProxy(objectProvider, new ObjectListener() { @Override public void newObject(HashMapVirtualObject next) { if (eClass.isSuperTypeOf(next.eClass())) { if (next.eGet(representationFeature) != null) { objects.add(next); } } } }); ifcSerializer.init(proxy, null, null, bimServer.getPluginManager(), packageMetaData); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(ifcSerializer.getInputStream(), baos); bytes = baos.toByteArray(); InputStream in = new ByteArrayInputStream(bytes); boolean notFoundsObjects = false; try { if (!objects.isEmpty()) { renderEngine = renderEnginePool.borrowObject(); try (RenderEngineModel renderEngineModel = renderEngine.openModel(in, bytes.length)) { renderEngineModel.setSettings(renderEngineSettings); renderEngineModel.setFilter(renderEngineFilter); try { renderEngineModel.generateGeneralGeometry(); } catch (RenderEngineException e) { if (e.getCause() instanceof java.io.EOFException) { if (objects.isEmpty() || eClass.getName().equals("IfcAnnotation")) { // SKIP } else { LOGGER.error("Error in " + eClass.getName(), e); } } } OidConvertingSerializer oidConvertingSerializer = (OidConvertingSerializer)ifcSerializer; Map<Long, Integer> oidToEid = oidConvertingSerializer.getOidToEid(); for (HashMapVirtualObject ifcProduct : objects) { if (!running) { return; } Integer expressId = oidToEid.get(ifcProduct.getOid()); try { RenderEngineInstance renderEngineInstance = renderEngineModel.getInstanceFromExpressId(expressId); RenderEngineGeometry geometry = renderEngineInstance.generateGeometry(); boolean translate = true; // if (geometry == null || geometry.getIndices().length == 0) { // LOGGER.info("Running again..."); // renderEngineModel.setFilter(renderEngineFilterTransformed); // geometry = renderEngineInstance.generateGeometry(); // if (geometry != null) { // translate = false; // renderEngineModel.setFilter(renderEngineFilter); if (geometry != null && geometry.getNrIndices() > 0) { VirtualObject geometryInfo = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryInfo()); WrappedVirtualObject minBounds = new HashMapWrappedVirtualObject(queryContext, GeometryPackage.eINSTANCE.getVector3f()); WrappedVirtualObject maxBounds = new HashMapWrappedVirtualObject(queryContext, GeometryPackage.eINSTANCE.getVector3f()); minBounds.set("x", Double.POSITIVE_INFINITY); minBounds.set("y", Double.POSITIVE_INFINITY); minBounds.set("z", Double.POSITIVE_INFINITY); maxBounds.set("x", -Double.POSITIVE_INFINITY); maxBounds.set("y", -Double.POSITIVE_INFINITY); maxBounds.set("z", -Double.POSITIVE_INFINITY); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_MinBounds(), minBounds); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_MaxBounds(), maxBounds); // try { // double area = renderEngineInstance.getArea(); // geometryInfo.setArea(area); // double volume = renderEngineInstance.getVolume(); // if (volume < 0d) { // volume = -volume; // geometryInfo.setVolume(volume); // } catch (NotImplementedException e) { VirtualObject geometryData = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryData()); int[] indices = geometry.getIndices(); geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Indices(), intArrayToByteArray(indices)); float[] vertices = geometry.getVertices(); geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Vertices(), floatArrayToByteArray(vertices)); // geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_MaterialIndices(), intArrayToByteArray(geometry.getMaterialIndices())); geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Normals(), floatArrayToByteArray(geometry.getNormals())); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), indices.length / 3); Set<Color4f> usedColors = new HashSet<>(); int saveableColorBytes = 0; if (geometry.getMaterialIndices() != null && geometry.getMaterialIndices().length > 0) { boolean hasMaterial = false; float[] vertex_colors = new float[vertices.length / 3 * 4]; for (int i = 0; i < geometry.getMaterialIndices().length; ++i) { int c = geometry.getMaterialIndices()[i]; for (int j = 0; j < 3; ++j) { int k = indices[i * 3 + j]; if (c > -1) { hasMaterial = true; Color4f color = new Color4f(); for (int l = 0; l < 4; ++l) { float val = geometry.getMaterials()[4 * c + l]; vertex_colors[4 * k + l] = val; color.set(l, val); } usedColors.add(color); } } } if (!usedColors.isEmpty()) { if (usedColors.size() == 1) { saveableColorBytes = (4 * vertex_colors.length) - 16; } } if (hasMaterial) { geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Materials(), floatArrayToByteArray(vertex_colors)); } } double[] tranformationMatrix = new double[16]; if (translate && renderEngineInstance.getTransformationMatrix() != null) { tranformationMatrix = renderEngineInstance.getTransformationMatrix(); } else { Matrix.setIdentityM(tranformationMatrix, 0); } for (int i = 0; i < indices.length; i++) { processExtends(geometryInfo, tranformationMatrix, vertices, indices[i] * 3, generateGeometryResult); } calculateObb(geometryInfo, tranformationMatrix, indices, vertices, generateGeometryResult); geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), geometryData.getOid(), 0); long size = getSize(geometryData); setTransformationMatrix(geometryInfo, tranformationMatrix); if (bimServer.getServerSettingsCache().getServerSettings().isReuseGeometry()) { int hash = hash(geometryData); if (hashes.containsKey(hash)) { geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), hashes.get(hash), 0); bytesSaved.addAndGet(size); } else { // if (sizes.containsKey(size) && sizes.get(size).eClass() == ifcProduct.eClass()) { // LOGGER.info("More reuse might be possible " + size + " " + ifcProduct.eClass().getName() + ":" + ifcProduct.getOid() + " / " + sizes.get(size).eClass().getName() + ":" + sizes.get(size).getOid()); hashes.put(hash, geometryData.getOid()); StreamingGeometryGenerator.this.saveableColorBytes.addAndGet(saveableColorBytes); geometryData.save(); // sizes.put(size, ifcProduct); } } else { geometryData.save(); } geometryInfo.save(); totalBytes.addAndGet(size); ifcProduct.setReference(geometryFeature, geometryInfo.getOid(), 0); ifcProduct.saveOverwrite(); } else { // TODO } } catch (EntityNotFoundException e) { // e.printStackTrace(); // As soon as we find a representation that is not Curve2D, then we should show a "INFO" message in the log to indicate there could be something wrong boolean ignoreNotFound = eClass.getName().equals("IfcAnnotation"); // for (Object rep : representations) { // if (rep instanceof IfcShapeRepresentation) { // IfcShapeRepresentation ifcShapeRepresentation = (IfcShapeRepresentation)rep; // if (!"Curve2D".equals(ifcShapeRepresentation.getRepresentationType())) { // ignoreNotFound = false; if (!ignoreNotFound) { notFoundsObjects = true; LOGGER.info("Entity not found " + ifcProduct.eClass().getName() + " " + (expressId) + "/" + ifcProduct.getOid()); } } catch (BimserverDatabaseException | RenderEngineException e) { LOGGER.error("", e); } } } } } finally { try { // if (notFoundsObjects) { // writeDebugFile(bytes, false); // Thread.sleep(60000); in.close(); } catch (Throwable e) { } if (renderEngine != null) { renderEnginePool.returnObject(renderEngine); } jobsDone.incrementAndGet(); updateProgress(); } } catch (Exception e) { LOGGER.error("", e); writeDebugFile(bytes, true); // LOGGER.error("Original query: " + originalQuery, e); } } catch (Exception e) { LOGGER.error("", e); // LOGGER.error("Original query: " + originalQuery, e); } } private void writeDebugFile(byte[] bytes, boolean error) throws FileNotFoundException, IOException { boolean debug = true; if (debug) { Path debugPath = bimServer.getHomeDir().resolve("debug"); if (!Files.exists(debugPath)) { Files.createDirectories(debugPath); } String basefilenamename = "all"; if (eClass != null) { basefilenamename = eClass.getName(); } if (error) { basefilenamename += "-error"; } Path file = debugPath.resolve(basefilenamename + ".ifc"); int i=0; while (Files.exists((file))) { file = debugPath.resolve(basefilenamename + "-" + i + ".ifc"); i++; } LOGGER.info("Writing debug file to " + file.toAbsolutePath().toString()); FileUtils.writeByteArrayToFile(file.toFile(), bytes); } } private void calculateObb(VirtualObject geometryInfo, double[] tranformationMatrix, int[] indices, float[] vertices, GenerateGeometryResult generateGeometryResult2) { } } private void updateProgress() { if (allJobsPushed) { progressListener.updateProgress("Generating geometry...", (int) (100.0 * jobsDone.get() / jobsTotal.get())); } } public GenerateGeometryResult generateGeometry(long uoid, final DatabaseSession databaseSession, QueryContext queryContext) throws BimserverDatabaseException, GeometryGeneratingException { GenerateGeometryResult generateGeometryResult = new GenerateGeometryResult(); packageMetaData = queryContext.getPackageMetaData(); productClass = packageMetaData.getEClass("IfcProduct"); geometryFeature = productClass.getEStructuralFeature("geometry"); representationFeature = productClass.getEStructuralFeature("Representation"); long start = System.nanoTime(); String pluginName = ""; if (queryContext.getPackageMetaData().getSchema() == Schema.IFC4) { pluginName = "org.bimserver.ifc.step.serializer.Ifc4StepStreamingSerializerPlugin"; } else if (queryContext.getPackageMetaData().getSchema() == Schema.IFC2X3TC1) { pluginName = "org.bimserver.ifc.step.serializer.Ifc2x3tc1StepStreamingSerializerPlugin"; } try { final StreamingSerializerPlugin ifcSerializerPlugin = (StreamingSerializerPlugin) bimServer.getPluginManager().getPlugin(pluginName, true); if (ifcSerializerPlugin == null) { throw new UserException("No IFC serializer found"); } User user = (User) databaseSession.get(uoid, org.bimserver.database.OldQuery.getDefault()); UserSettings userSettings = user.getUserSettings(); RenderEnginePluginConfiguration defaultRenderEngine = userSettings.getDefaultRenderEngine(); if (defaultRenderEngine == null) { throw new UserException("No default render engine has been selected for this user"); } int maxSimultanousThreads = Math.min(bimServer.getServerSettingsCache().getServerSettings().getRenderEngineProcesses(), Runtime.getRuntime().availableProcessors()); if (maxSimultanousThreads < 1) { maxSimultanousThreads = 1; } final RenderEngineSettings settings = new RenderEngineSettings(); settings.setPrecision(Precision.SINGLE); settings.setIndexFormat(IndexFormat.AUTO_DETECT); settings.setGenerateNormals(true); settings.setGenerateTriangles(true); settings.setGenerateWireFrame(false); final RenderEngineFilter renderEngineFilter = new RenderEngineFilter(); RenderEnginePool renderEnginePool = bimServer.getRenderEnginePools().getRenderEnginePool(packageMetaData.getSchema(), defaultRenderEngine.getPluginDescriptor().getPluginClassName(), new PluginConfiguration(defaultRenderEngine.getSettings())); ThreadPoolExecutor executor = new ThreadPoolExecutor(maxSimultanousThreads, maxSimultanousThreads, 24, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(10000000)); for (EClass eClass : queryContext.getOidCounters().keySet()) { if (packageMetaData.getEClass("IfcProduct").isSuperTypeOf(eClass)) { Query query2 = new Query("test", packageMetaData); QueryPart queryPart2 = query2.createQueryPart(); queryPart2.addType(eClass, false); Include include = queryPart2.createInclude(); include.addType(eClass, false); include.addFieldDirect("Representation"); QueryObjectProvider queryObjectProvider2 = new QueryObjectProvider(databaseSession, bimServer, query2, Collections.singleton(queryContext.getRoid()), packageMetaData); HashMapVirtualObject next = queryObjectProvider2.next(); while (next != null) { if (next.eClass() == eClass) { HashMapVirtualObject representation = next.getDirectFeature(representationFeature); if (representation != null) { List<Long> representations = (List<Long>) representation.get("Representations"); if (representations != null && !representations.isEmpty()) { Query query = new Query("test", packageMetaData); QueryPart queryPart = query.createQueryPart(); queryPart.addType(eClass, false); int x = 0; queryPart.addOid(next.getOid()); while (next != null && x < maxObjectsPerFile) { next = queryObjectProvider2.next(); if (next != null) { if (next.eClass() == eClass) { representation = next.getDirectFeature(representationFeature); if (representation != null) { representations = (List<Long>) representation.get("Representations"); if (representations != null && !representations.isEmpty()) { queryPart.addOid(next.getOid()); x++; } } } } } JsonQueryObjectModelConverter jsonQueryObjectModelConverter = new JsonQueryObjectModelConverter(packageMetaData); String queryNameSpace = "validifc"; if (packageMetaData.getSchema() == Schema.IFC4) { queryNameSpace = "ifc4stdlib"; } if (eClass.getName().equals("IfcAnnotation")) { // IfcAnnotation also has the field ContainedInStructure, but that is it's own field (looks like a hack on the IFC-spec side) queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":IfcAnnotationContainedInStructure")); } else { queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":ContainedInStructure")); } queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":Decomposes")); queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":OwnerHistory")); Include representationInclude = jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":Representation"); queryPart.addInclude(representationInclude); Include objectPlacement = jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":ObjectPlacement"); queryPart.addInclude(objectPlacement); if (packageMetaData.getEClass("IfcElement").isSuperTypeOf(eClass)) { Include openingsInclude = queryPart.createInclude(); openingsInclude.addType(packageMetaData.getEClass(eClass.getName()), false); openingsInclude.addField("HasOpenings"); Include hasOpenings = openingsInclude.createInclude(); hasOpenings.addType(packageMetaData.getEClass("IfcRelVoidsElement"), false); hasOpenings.addField("RelatedOpeningElement"); hasOpenings.addInclude(representationInclude); hasOpenings.addInclude(objectPlacement); // Include relatedOpeningElement = hasOpenings.createInclude(); // relatedOpeningElement.addType(packageMetaData.getEClass("IfcOpeningElement"), false); // relatedOpeningElement.addField("HasFillings"); // Include hasFillings = relatedOpeningElement.createInclude(); // hasFillings.addType(packageMetaData.getEClass("IfcRelFillsElement"), false); // hasFillings.addField("RelatedBuildingElement"); } QueryObjectProvider queryObjectProvider = new QueryObjectProvider(databaseSession, bimServer, query, Collections.singleton(queryContext.getRoid()), packageMetaData); Runner runner = new Runner(eClass, renderEnginePool, databaseSession, settings, queryObjectProvider, ifcSerializerPlugin, renderEngineFilter, generateGeometryResult, queryContext, query); executor.submit(runner); jobsTotal.incrementAndGet(); } } } next = queryObjectProvider2.next(); } } } allJobsPushed = true; executor.shutdown(); executor.awaitTermination(24, TimeUnit.HOURS); long end = System.nanoTime(); LOGGER.info("Rendertime: " + ((end - start) / 1000000) + "ms, " + "Reused: " + Formatters.bytesToString(bytesSaved.get()) + ", Total: " + Formatters.bytesToString(totalBytes.get()) + ", Final: " + Formatters.bytesToString(totalBytes.get() - bytesSaved.get())); LOGGER.info("Saveable color data: " + Formatters.bytesToString(saveableColorBytes.get())); } catch (Exception e) { running = false; LOGGER.error("", e); throw new GeometryGeneratingException(e); } return generateGeometryResult; } private long getSize(VirtualObject geometryData) { long size = 0; if (geometryData.has("indices")) { size += ((byte[])geometryData.get("vertices")).length; } if (geometryData.has("vertices")) { size += ((byte[])geometryData.get("vertices")).length; } if (geometryData.has("normals")) { size += ((byte[])geometryData.get("normals")).length; } if (geometryData.has("materialIndices")) { size += ((byte[])geometryData.get("materialIndices")).length; } if (geometryData.has("materials")) { size += ((byte[])geometryData.get("materials")).length; } return size; } private int hash(VirtualObject geometryData) { int hashCode = 0; if (geometryData.has("indices")) { hashCode += Arrays.hashCode((byte[])geometryData.get("vertices")); } if (geometryData.has("vertices")) { hashCode += Arrays.hashCode((byte[])geometryData.get("vertices")); } if (geometryData.has("normals")) { hashCode += Arrays.hashCode((byte[])geometryData.get("normals")); } if (geometryData.has("materialIndices")) { hashCode += Arrays.hashCode((byte[])geometryData.get("materialIndices")); } if (geometryData.has("materials")) { hashCode += Arrays.hashCode((byte[])geometryData.get("materials")); } return hashCode; } private void processExtends(VirtualObject geometryInfo, double[] transformationMatrix, float[] vertices, int index, GenerateGeometryResult generateGeometryResult) throws BimserverDatabaseException { double x = vertices[index]; double y = vertices[index + 1]; double z = vertices[index + 2]; double[] result = new double[4]; Matrix.multiplyMV(result, 0, transformationMatrix, 0, new double[] { x, y, z, 1 }, 0); x = result[0]; y = result[1]; z = result[2]; HashMapWrappedVirtualObject minBounds = (HashMapWrappedVirtualObject) geometryInfo.eGet(GeometryPackage.eINSTANCE.getGeometryInfo_MinBounds()); HashMapWrappedVirtualObject maxBounds = (HashMapWrappedVirtualObject) geometryInfo.eGet(GeometryPackage.eINSTANCE.getGeometryInfo_MaxBounds()); minBounds.set("x", Math.min(x, (double)minBounds.eGet("x"))); minBounds.set("y", Math.min(y, (double)minBounds.eGet("y"))); minBounds.set("z", Math.min(z, (double)minBounds.eGet("z"))); maxBounds.set("x", Math.max(x, (double)maxBounds.eGet("x"))); maxBounds.set("y", Math.max(y, (double)maxBounds.eGet("y"))); maxBounds.set("z", Math.max(z, (double)maxBounds.eGet("z"))); generateGeometryResult.setMinX(Math.min(x, generateGeometryResult.getMinX())); generateGeometryResult.setMinY(Math.min(y, generateGeometryResult.getMinY())); generateGeometryResult.setMinZ(Math.min(z, generateGeometryResult.getMinZ())); generateGeometryResult.setMaxX(Math.max(x, generateGeometryResult.getMaxX())); generateGeometryResult.setMaxY(Math.max(y, generateGeometryResult.getMaxY())); generateGeometryResult.setMaxZ(Math.max(z, generateGeometryResult.getMaxZ())); } private float[] doubleToFloat(double[] tranformationMatrix) { float[] result = new float[tranformationMatrix.length]; for (int i=0; i<tranformationMatrix.length; i++) { result[i] = (float) tranformationMatrix[i]; } return result; } private void setTransformationMatrix(VirtualObject geometryInfo, double[] transformationMatrix) throws BimserverDatabaseException { ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 8); byteBuffer.order(ByteOrder.nativeOrder()); DoubleBuffer asDoubleBuffer = byteBuffer.asDoubleBuffer(); for (double d : transformationMatrix) { asDoubleBuffer.put(d); } geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Transformation(), byteBuffer.array()); } }
package org.bimserver; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; 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.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.io.IOUtils; import org.bimserver.database.DatabaseSession; import org.bimserver.database.actions.ProgressListener; import org.bimserver.database.queries.QueryObjectProvider; import org.bimserver.database.queries.om.Include; import org.bimserver.database.queries.om.JsonQueryObjectModelConverter; import org.bimserver.database.queries.om.Query; import org.bimserver.database.queries.om.QueryPart; import org.bimserver.emf.PackageMetaData; import org.bimserver.emf.Schema; import org.bimserver.geometry.Matrix; import org.bimserver.models.geometry.GeometryPackage; import org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package; import org.bimserver.models.store.RenderEnginePluginConfiguration; import org.bimserver.models.store.User; import org.bimserver.models.store.UserSettings; import org.bimserver.plugins.PluginConfiguration; import org.bimserver.plugins.renderengine.EntityNotFoundException; import org.bimserver.plugins.renderengine.IndexFormat; import org.bimserver.plugins.renderengine.Precision; import org.bimserver.plugins.renderengine.RenderEngine; import org.bimserver.plugins.renderengine.RenderEngineException; import org.bimserver.plugins.renderengine.RenderEngineFilter; import org.bimserver.plugins.renderengine.RenderEngineGeometry; import org.bimserver.plugins.renderengine.RenderEngineInstance; import org.bimserver.plugins.renderengine.RenderEngineModel; import org.bimserver.plugins.renderengine.RenderEngineSettings; import org.bimserver.plugins.serializers.ObjectProvider; import org.bimserver.plugins.serializers.OidConvertingSerializer; import org.bimserver.plugins.serializers.StreamingSerializer; import org.bimserver.plugins.serializers.StreamingSerializerPlugin; import org.bimserver.renderengine.RenderEnginePool; import org.bimserver.shared.HashMapVirtualObject; import org.bimserver.shared.HashMapWrappedVirtualObject; import org.bimserver.shared.QueryContext; import org.bimserver.shared.VirtualObject; import org.bimserver.shared.WrappedVirtualObject; import org.bimserver.shared.exceptions.UserException; import org.bimserver.utils.Formatters; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EStructuralFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StreamingGeometryGenerator extends GenericGeometryGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(StreamingGeometryGenerator.class); private final BimServer bimServer; private final Map<Integer, Long> hashes = new ConcurrentHashMap<>(); private EClass productClass; private EStructuralFeature geometryFeature; private EStructuralFeature representationFeature; private PackageMetaData packageMetaData; private AtomicLong bytesSaved = new AtomicLong(); private AtomicLong totalBytes = new AtomicLong(); private AtomicInteger jobsDone = new AtomicInteger(); private AtomicInteger jobsTotal = new AtomicInteger(); private ProgressListener progressListener; private volatile boolean allJobsPushed; private Object representationsFeature; private EClass productRepresentationClass; public StreamingGeometryGenerator(final BimServer bimServer, ProgressListener progressListener) { this.bimServer = bimServer; this.progressListener = progressListener; } public class Runner implements Runnable { private EClass eClass; private RenderEngineSettings renderEngineSettings; private RenderEngineFilter renderEngineFilter; private RenderEngineFilter renderEngineFilterTransformed = new RenderEngineFilter(true); private StreamingSerializerPlugin ifcSerializerPlugin; private GenerateGeometryResult generateGeometryResult; private ObjectProvider objectProvider; private QueryContext queryContext; private DatabaseSession databaseSession; private RenderEnginePool renderEnginePool; private Query originalQuery; public Runner(EClass eClass, RenderEnginePool renderEnginePool, DatabaseSession databaseSession, RenderEngineSettings renderEngineSettings, ObjectProvider objectProvider, StreamingSerializerPlugin ifcSerializerPlugin, RenderEngineFilter renderEngineFilter, GenerateGeometryResult generateGeometryResult, QueryContext queryContext, Query originalQuery) { this.eClass = eClass; this.renderEnginePool = renderEnginePool; this.databaseSession = databaseSession; this.renderEngineSettings = renderEngineSettings; this.objectProvider = objectProvider; this.ifcSerializerPlugin = ifcSerializerPlugin; this.renderEngineFilter = renderEngineFilter; this.generateGeometryResult = generateGeometryResult; this.queryContext = queryContext; this.originalQuery = originalQuery; } @Override public void run() { try { HashMapVirtualObject next; next = objectProvider.next(); Query query = new Query("test", packageMetaData); QueryPart queryPart = query.createQueryPart(); while (next != null) { queryPart.addOid(next.getOid()); // for (EReference eReference : next.eClass().getEAllReferences()) { // Object ref = next.eGet(eReference); // if (ref != null) { // if (eReference.isMany()) { // List<?> list = (List<?>)ref; // int index = 0; // for (Object o : list) { // if (o != null) { // if (o instanceof Long) { // if (next.useFeatureForSerialization(eReference, index)) { // queryPart.addOid((Long)o); // } else { // System.out.println(); // index++; // } else { // if (ref instanceof Long) { // if (next.useFeatureForSerialization(eReference)) { // queryPart.addOid((Long)ref); next = objectProvider.next(); } objectProvider = new QueryObjectProvider(databaseSession, bimServer, query, Collections.singleton(queryContext.getRoid()), packageMetaData); StreamingSerializer ifcSerializer = ifcSerializerPlugin.createSerializer(new PluginConfiguration()); RenderEngine renderEngine = null; byte[] bytes = null; try { final Set<HashMapVirtualObject> objects = new HashSet<>(); ObjectProviderProxy proxy = new ObjectProviderProxy(objectProvider, new ObjectListener() { @Override public void newObject(HashMapVirtualObject next) { if (eClass.isSuperTypeOf(next.eClass())) { if (next.eGet(representationFeature) != null) { objects.add(next); } } } }); ifcSerializer.init(proxy, null, null, bimServer.getPluginManager(), packageMetaData); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(ifcSerializer.getInputStream(), baos); bytes = baos.toByteArray(); InputStream in = new ByteArrayInputStream(bytes); boolean notFoundsObjects = false; try { if (!objects.isEmpty()) { renderEngine = renderEnginePool.borrowObject(); try (RenderEngineModel renderEngineModel = renderEngine.openModel(in, bytes.length)) { renderEngineModel.setSettings(renderEngineSettings); renderEngineModel.setFilter(renderEngineFilter); try { renderEngineModel.generateGeneralGeometry(); } catch (RenderEngineException e) { if (e.getCause() instanceof java.io.EOFException) { if (objects.isEmpty() || eClass.getName().equals("IfcAnnotation")) { // SKIP } else { LOGGER.error("Error in " + eClass.getName(), e); } } } OidConvertingSerializer oidConvertingSerializer = (OidConvertingSerializer)ifcSerializer; Map<Long, Integer> oidToEid = oidConvertingSerializer.getOidToEid(); for (HashMapVirtualObject ifcProduct : objects) { Integer expressId = oidToEid.get(ifcProduct.getOid()); try { RenderEngineInstance renderEngineInstance = renderEngineModel.getInstanceFromExpressId(expressId); RenderEngineGeometry geometry = renderEngineInstance.generateGeometry(); boolean translate = true; // if (geometry == null || geometry.getIndices().length == 0) { // LOGGER.info("Running again..."); // renderEngineModel.setFilter(renderEngineFilterTransformed); // geometry = renderEngineInstance.generateGeometry(); // if (geometry != null) { // translate = false; // renderEngineModel.setFilter(renderEngineFilter); if (geometry != null && geometry.getNrIndices() > 0) { VirtualObject geometryInfo = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryInfo()); WrappedVirtualObject minBounds = new HashMapWrappedVirtualObject(queryContext, GeometryPackage.eINSTANCE.getVector3f()); WrappedVirtualObject maxBounds = new HashMapWrappedVirtualObject(queryContext, GeometryPackage.eINSTANCE.getVector3f()); minBounds.set("x", Double.POSITIVE_INFINITY); minBounds.set("y", Double.POSITIVE_INFINITY); minBounds.set("z", Double.POSITIVE_INFINITY); maxBounds.set("x", -Double.POSITIVE_INFINITY); maxBounds.set("y", -Double.POSITIVE_INFINITY); maxBounds.set("z", -Double.POSITIVE_INFINITY); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_MinBounds(), minBounds); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_MaxBounds(), maxBounds); // try { // double area = renderEngineInstance.getArea(); // geometryInfo.setArea(area); // double volume = renderEngineInstance.getVolume(); // if (volume < 0d) { // volume = -volume; // geometryInfo.setVolume(volume); // } catch (NotImplementedException e) { VirtualObject geometryData = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryData()); int[] indices = geometry.getIndices(); geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Indices(), intArrayToByteArray(indices)); float[] vertices = geometry.getVertices(); geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Vertices(), floatArrayToByteArray(vertices)); // geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_MaterialIndices(), intArrayToByteArray(geometry.getMaterialIndices())); geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Normals(), floatArrayToByteArray(geometry.getNormals())); geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), indices.length / 3); // Set<Color4f> usedColors = new HashSet<>(); if (geometry.getMaterialIndices() != null && geometry.getMaterialIndices().length > 0) { boolean hasMaterial = false; float[] vertex_colors = new float[vertices.length / 3 * 4]; for (int i = 0; i < geometry.getMaterialIndices().length; ++i) { int c = geometry.getMaterialIndices()[i]; for (int j = 0; j < 3; ++j) { int k = indices[i * 3 + j]; if (c > -1) { hasMaterial = true; Color4f color = new Color4f(); for (int l = 0; l < 4; ++l) { float val = geometry.getMaterials()[4 * c + l]; vertex_colors[4 * k + l] = val; color.set(l, val); } // usedColors.add(color); } } } // System.out.println(usedColors.size() + " different colors"); // if (!usedColors.isEmpty()) { // for (Color4f c : usedColors) { if (hasMaterial) { geometryData.setAttribute(GeometryPackage.eINSTANCE.getGeometryData_Materials(), floatArrayToByteArray(vertex_colors)); } } double[] tranformationMatrix = new double[16]; if (translate && renderEngineInstance.getTransformationMatrix() != null) { tranformationMatrix = renderEngineInstance.getTransformationMatrix(); } else { Matrix.setIdentityM(tranformationMatrix, 0); } for (int i = 0; i < indices.length; i++) { processExtends(geometryInfo, tranformationMatrix, vertices, indices[i] * 3, generateGeometryResult); } calculateObb(geometryInfo, tranformationMatrix, indices, vertices, generateGeometryResult); geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), geometryData.getOid(), 0); long size = getSize(geometryData); setTransformationMatrix(geometryInfo, tranformationMatrix); if (bimServer.getServerSettingsCache().getServerSettings().isReuseGeometry()) { int hash = hash(geometryData); if (hashes.containsKey(hash)) { geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), hashes.get(hash), 0); bytesSaved.addAndGet(size); } else { // if (sizes.containsKey(size) && sizes.get(size).eClass() == ifcProduct.eClass()) { // LOGGER.info("More reuse might be possible " + size + " " + ifcProduct.eClass().getName() + ":" + ifcProduct.getOid() + " / " + sizes.get(size).eClass().getName() + ":" + sizes.get(size).getOid()); hashes.put(hash, geometryData.getOid()); geometryData.save(); // sizes.put(size, ifcProduct); } } else { geometryData.save(); } geometryInfo.save(); totalBytes.addAndGet(size); ifcProduct.setReference(geometryFeature, geometryInfo.getOid(), 0); ifcProduct.saveOverwrite(); } else { // TODO } } catch (EntityNotFoundException e) { // e.printStackTrace(); // As soon as we find a representation that is not Curve2D, then we should show a "INFO" message in the log to indicate there could be something wrong boolean ignoreNotFound = eClass.getName().equals("IfcAnnotation"); // for (Object rep : representations) { // if (rep instanceof IfcShapeRepresentation) { // IfcShapeRepresentation ifcShapeRepresentation = (IfcShapeRepresentation)rep; // if (!"Curve2D".equals(ifcShapeRepresentation.getRepresentationType())) { // ignoreNotFound = false; if (!ignoreNotFound) { notFoundsObjects = true; LOGGER.info("Entity not found " + ifcProduct.eClass().getName() + " " + (expressId) + "/" + ifcProduct.getOid()); } } catch (BimserverDatabaseException | RenderEngineException e) { LOGGER.error("", e); } } } } } finally { // if (notFoundsObjects) { writeDebugFile(bytes); // Thread.sleep(60000); in.close(); if (renderEngine != null) { renderEnginePool.returnObject(renderEngine); } jobsDone.incrementAndGet(); updateProgress(); } } catch (Exception e) { LOGGER.error("", e); writeDebugFile(bytes); // LOGGER.error("Original query: " + originalQuery, e); } } catch (Exception e) { LOGGER.error("", e); // LOGGER.error("Original query: " + originalQuery, e); } } private void writeDebugFile(byte[] bytes) throws FileNotFoundException, IOException { boolean debug = false; if (debug) { Path debugPath = Paths.get("debug"); if (!Files.exists(debugPath)) { Files.createDirectories(debugPath); } String basefilenamename = "all"; if (eClass != null) { basefilenamename = eClass.getName(); } Path file = debugPath.resolve(basefilenamename + ".ifc"); int i=0; while (Files.exists((file))) { file = debugPath.resolve(basefilenamename + "-" + i + ".ifc"); i++; } LOGGER.info("Writing debug file to " + file.toAbsolutePath().toString()); FileOutputStream fos = new FileOutputStream(file.toFile()); IOUtils.copy(new ByteArrayInputStream(bytes), fos); fos.close(); } } private void calculateObb(VirtualObject geometryInfo, double[] tranformationMatrix, int[] indices, float[] vertices, GenerateGeometryResult generateGeometryResult2) { } } private void updateProgress() { if (allJobsPushed) { progressListener.updateProgress("Generating geometry...", (int) (100.0 * jobsDone.get() / jobsTotal.get())); } } public GenerateGeometryResult generateGeometry(long uoid, final DatabaseSession databaseSession, QueryContext queryContext) throws BimserverDatabaseException, GeometryGeneratingException { GenerateGeometryResult generateGeometryResult = new GenerateGeometryResult(); packageMetaData = queryContext.getPackageMetaData(); productClass = packageMetaData.getEClass("IfcProduct"); geometryFeature = productClass.getEStructuralFeature("geometry"); representationFeature = productClass.getEStructuralFeature("Representation"); productRepresentationClass = packageMetaData.getEClass("IfcProductRepresentation"); representationsFeature = productRepresentationClass.getEStructuralFeature("Representations"); long start = System.nanoTime(); String pluginName = ""; if (queryContext.getPackageMetaData().getSchema() == Schema.IFC4) { pluginName = "org.bimserver.ifc.step.serializer.Ifc4StepStreamingSerializerPlugin"; } else if (queryContext.getPackageMetaData().getSchema() == Schema.IFC2X3TC1) { pluginName = "org.bimserver.ifc.step.serializer.Ifc2x3tc1StepStreamingSerializerPlugin"; } try { final StreamingSerializerPlugin ifcSerializerPlugin = (StreamingSerializerPlugin) bimServer.getPluginManager().getPlugin(pluginName, true); if (ifcSerializerPlugin == null) { throw new UserException("No IFC serializer found"); } User user = (User) databaseSession.get(uoid, org.bimserver.database.OldQuery.getDefault()); UserSettings userSettings = user.getUserSettings(); RenderEnginePluginConfiguration defaultRenderEngine = userSettings.getDefaultRenderEngine(); if (defaultRenderEngine == null) { throw new UserException("No default render engine has been selected for this user"); } int maxSimultanousThreads = Math.min(bimServer.getServerSettingsCache().getServerSettings().getRenderEngineProcesses(), Runtime.getRuntime().availableProcessors()); if (maxSimultanousThreads < 1) { maxSimultanousThreads = 1; } final RenderEngineSettings settings = new RenderEngineSettings(); settings.setPrecision(Precision.SINGLE); settings.setIndexFormat(IndexFormat.AUTO_DETECT); settings.setGenerateNormals(true); settings.setGenerateTriangles(true); settings.setGenerateWireFrame(false); final RenderEngineFilter renderEngineFilter = new RenderEngineFilter(); RenderEnginePool renderEnginePool = bimServer.getRenderEnginePools().getRenderEnginePool(packageMetaData.getSchema(), defaultRenderEngine.getPluginDescriptor().getPluginClassName(), new PluginConfiguration(defaultRenderEngine.getSettings())); ThreadPoolExecutor executor = new ThreadPoolExecutor(maxSimultanousThreads, maxSimultanousThreads, 24, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(10000000)); for (EClass eClass : queryContext.getOidCounters().keySet()) { if (packageMetaData.getEClass("IfcProduct").isSuperTypeOf(eClass)) { Query query2 = new Query("test", packageMetaData); QueryPart queryPart2 = query2.createQueryPart(); queryPart2.addType(eClass, false); Include include = queryPart2.createInclude(); include.addType(eClass, false); include.addFieldDirect("Representation"); QueryObjectProvider queryObjectProvider2 = new QueryObjectProvider(databaseSession, bimServer, query2, Collections.singleton(queryContext.getRoid()), packageMetaData); HashMapVirtualObject next = queryObjectProvider2.next(); while (next != null) { if (next.eClass() == eClass) { HashMapVirtualObject representation = next.getDirectFeature(representationFeature); if (representation != null) { List<Long> representations = (List<Long>) representation.get("Representations"); if (representations != null && !representations.isEmpty()) { Query query = new Query("test", packageMetaData); QueryPart queryPart = query.createQueryPart(); queryPart.addType(eClass, false); int x = 0; queryPart.addOid(next.getOid()); while (next != null && x < 10) { next = queryObjectProvider2.next(); if (next != null) { if (next.eClass() == eClass) { representation = next.getDirectFeature(representationFeature); if (representation != null) { representations = (List<Long>) representation.get("Representations"); if (!representations.isEmpty()) { queryPart.addOid(next.getOid()); x++; } } } } } JsonQueryObjectModelConverter jsonQueryObjectModelConverter = new JsonQueryObjectModelConverter(packageMetaData); String queryNameSpace = "validifc"; if (packageMetaData.getSchema() == Schema.IFC4) { queryNameSpace = "ifc4stdlib"; } if (eClass.getName().equals("IfcAnnotation")) { // IfcAnnotation also has the field ContainedInStructure, but that is it's own field (looks like a hack on the IFC-spec side) queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":IfcAnnotationContainedInStructure")); } else { queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":ContainedInStructure")); } queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":Decomposes")); queryPart.addInclude(jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":OwnerHistory")); Include representationInclude = jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":Representation"); queryPart.addInclude(representationInclude); Include objectPlacement = jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":ObjectPlacement"); queryPart.addInclude(objectPlacement); if (packageMetaData.getEClass("IfcWall").isSuperTypeOf(eClass)) { Include ifcWall = queryPart.createInclude(); ifcWall.addType(packageMetaData.getEClass(eClass.getName()), false); ifcWall.addField("HasOpenings"); Include hasOpenings = ifcWall.createInclude(); hasOpenings.addType(packageMetaData.getEClass("IfcRelVoidsElement"), false); hasOpenings.addField("RelatedOpeningElement"); hasOpenings.addInclude(representationInclude); hasOpenings.addInclude(objectPlacement); // Include relatedOpeningElement = hasOpenings.createInclude(); // relatedOpeningElement.addType(packageMetaData.getEClass("IfcOpeningElement"), false); // relatedOpeningElement.addField("HasFillings"); // Include hasFillings = relatedOpeningElement.createInclude(); // hasFillings.addType(packageMetaData.getEClass("IfcRelFillsElement"), false); // hasFillings.addField("RelatedBuildingElement"); } QueryObjectProvider queryObjectProvider = new QueryObjectProvider(databaseSession, bimServer, query, Collections.singleton(queryContext.getRoid()), packageMetaData); Runner runner = new Runner(eClass, renderEnginePool, databaseSession, settings, queryObjectProvider, ifcSerializerPlugin, renderEngineFilter, generateGeometryResult, queryContext, query); executor.submit(runner); jobsTotal.incrementAndGet(); } } } next = queryObjectProvider2.next(); } } } allJobsPushed = true; executor.shutdown(); executor.awaitTermination(24, TimeUnit.HOURS); long end = System.nanoTime(); LOGGER.info("Rendertime: " + ((end - start) / 1000000) + "ms, " + "Reused: " + Formatters.bytesToString(bytesSaved.get()) + ", Total: " + Formatters.bytesToString(totalBytes.get()) + ", Final: " + Formatters.bytesToString(totalBytes.get() - bytesSaved.get())); } catch (Exception e) { LOGGER.error("", e); throw new GeometryGeneratingException(e); } return generateGeometryResult; } private long getSize(VirtualObject geometryData) { long size = 0; if (geometryData.has("indices")) { size += ((byte[])geometryData.get("vertices")).length; } if (geometryData.has("vertices")) { size += ((byte[])geometryData.get("vertices")).length; } if (geometryData.has("normals")) { size += ((byte[])geometryData.get("normals")).length; } if (geometryData.has("materialIndices")) { size += ((byte[])geometryData.get("materialIndices")).length; } if (geometryData.has("materials")) { size += ((byte[])geometryData.get("materials")).length; } return size; } private int hash(VirtualObject geometryData) { int hashCode = 0; if (geometryData.has("indices")) { hashCode += Arrays.hashCode((byte[])geometryData.get("vertices")); } if (geometryData.has("vertices")) { hashCode += Arrays.hashCode((byte[])geometryData.get("vertices")); } if (geometryData.has("normals")) { hashCode += Arrays.hashCode((byte[])geometryData.get("normals")); } if (geometryData.has("materialIndices")) { hashCode += Arrays.hashCode((byte[])geometryData.get("materialIndices")); } if (geometryData.has("materials")) { hashCode += Arrays.hashCode((byte[])geometryData.get("materials")); } return hashCode; } private void processExtends(VirtualObject geometryInfo, double[] transformationMatrix, float[] vertices, int index, GenerateGeometryResult generateGeometryResult) throws BimserverDatabaseException { double x = vertices[index]; double y = vertices[index + 1]; double z = vertices[index + 2]; double[] result = new double[4]; Matrix.multiplyMV(result, 0, transformationMatrix, 0, new double[] { x, y, z, 1 }, 0); x = result[0]; y = result[1]; z = result[2]; HashMapWrappedVirtualObject minBounds = (HashMapWrappedVirtualObject) geometryInfo.eGet(GeometryPackage.eINSTANCE.getGeometryInfo_MinBounds()); HashMapWrappedVirtualObject maxBounds = (HashMapWrappedVirtualObject) geometryInfo.eGet(GeometryPackage.eINSTANCE.getGeometryInfo_MaxBounds()); minBounds.set("x", Math.min(x, (double)minBounds.eGet("x"))); minBounds.set("y", Math.min(y, (double)minBounds.eGet("y"))); minBounds.set("z", Math.min(z, (double)minBounds.eGet("z"))); maxBounds.set("x", Math.max(x, (double)maxBounds.eGet("x"))); maxBounds.set("y", Math.max(y, (double)maxBounds.eGet("y"))); maxBounds.set("z", Math.max(z, (double)maxBounds.eGet("z"))); generateGeometryResult.setMinX(Math.min(x, generateGeometryResult.getMinX())); generateGeometryResult.setMinY(Math.min(y, generateGeometryResult.getMinY())); generateGeometryResult.setMinZ(Math.min(z, generateGeometryResult.getMinZ())); generateGeometryResult.setMaxX(Math.max(x, generateGeometryResult.getMaxX())); generateGeometryResult.setMaxY(Math.max(y, generateGeometryResult.getMaxY())); generateGeometryResult.setMaxZ(Math.max(z, generateGeometryResult.getMaxZ())); } private float[] doubleToFloat(double[] tranformationMatrix) { float[] result = new float[tranformationMatrix.length]; for (int i=0; i<tranformationMatrix.length; i++) { result[i] = (float) tranformationMatrix[i]; } return result; } private void setTransformationMatrix(VirtualObject geometryInfo, double[] transformationMatrix) throws BimserverDatabaseException { ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 8); byteBuffer.order(ByteOrder.nativeOrder()); DoubleBuffer asDoubleBuffer = byteBuffer.asDoubleBuffer(); for (double d : transformationMatrix) { asDoubleBuffer.put(d); } geometryInfo.setAttribute(GeometryPackage.eINSTANCE.getGeometryInfo_Transformation(), byteBuffer.array()); } }
package com.almasb.breakout; import com.almasb.breakout.control.BallControl; import com.almasb.breakout.control.BatControl; import com.almasb.breakout.control.BrickControl; import com.almasb.ents.Entity; import com.almasb.fxgl.app.ApplicationMode; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.audio.Music; import com.almasb.fxgl.effect.ParticleControl; import com.almasb.fxgl.effect.ParticleEmitter; import com.almasb.fxgl.entity.Entities; import com.almasb.fxgl.entity.EntityView; import com.almasb.fxgl.entity.RenderLayer; import com.almasb.fxgl.entity.component.PositionComponent; import com.almasb.fxgl.gameplay.Level; import com.almasb.fxgl.input.UserAction; import com.almasb.fxgl.parser.TextLevelParser; import com.almasb.fxgl.physics.CollisionHandler; import com.almasb.fxgl.settings.GameSettings; import com.almasb.gameutils.math.GameMath; import javafx.animation.PathTransition; import javafx.geometry.Point2D; import javafx.scene.effect.BlendMode; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Stop; import javafx.scene.shape.QuadCurve; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.util.Duration; /** * @author Almas Baimagambetov (almaslvl@gmail.com) */ public class BreakoutApp extends GameApplication { private BatControl getBatControl() { return getGameWorld().getEntitiesByType(EntityType.BAT).get(0).getControlUnsafe(BatControl.class); } private BallControl getBallControl() { return getGameWorld().getEntitiesByType(EntityType.BALL).get(0).getControlUnsafe(BallControl.class); } @Override protected void initSettings(GameSettings settings) { settings.setTitle("Breakout Underwater"); settings.setVersion("0.1"); settings.setWidth(600); settings.setHeight(800); settings.setIntroEnabled(false); settings.setMenuEnabled(false); settings.setProfilingEnabled(false); settings.setCloseConfirmation(false); settings.setApplicationMode(ApplicationMode.DEVELOPER); } @Override protected void initInput() { getInput().addAction(new UserAction("Move Left") { @Override protected void onAction() { getBatControl().left(); } }, KeyCode.A); getInput().addAction(new UserAction("Move Right") { @Override protected void onAction() { getBatControl().right(); } }, KeyCode.D); } @Override protected void initAssets() {} @Override protected void initGame() { Music music = getAssetLoader().loadMusic("BGM01.wav"); music.setCycleCount(Integer.MAX_VALUE); getAudioPlayer().playMusic(music); TextLevelParser parser = new TextLevelParser(new BreakoutFactory()); Level level = parser.parse("levels/level1.txt"); getGameWorld().setLevel(level); getGameWorld().addEntity(Entities.makeScreenBounds(40)); Rectangle bg0 = new Rectangle(getWidth(), getHeight()); LinearGradient gradient = new LinearGradient(getWidth() / 2, 0, getWidth() / 2, getHeight(), false, CycleMethod.NO_CYCLE, new Stop(0.2, Color.AQUA), new Stop(0.8, Color.BLACK)); bg0.setFill(gradient); Rectangle bg1 = new Rectangle(getWidth(), getHeight(), Color.color(0, 0, 0, 0.2)); bg1.setBlendMode(BlendMode.DARKEN); Pane bg = new Pane(); bg.getChildren().addAll(bg0, bg1); Entities.builder() .viewFromNode(new EntityView(bg, RenderLayer.BACKGROUND)) .buildAndAttach(getGameWorld()); ParticleEmitter emitter = new ParticleEmitter(); emitter.setSourceImage(getAssetLoader().loadTexture("bubble.png").getImage()); emitter.setBlendFunction((i, x, y) -> BlendMode.SRC_OVER); emitter.setEmissionRate(0.25); emitter.setExpireFunction((i, x, y) -> Duration.seconds(3)); emitter.setVelocityFunction((i, x, y) -> new Point2D(0, -GameMath.random(2f, 4f))); emitter.setSpawnPointFunction((i, x, y) -> new Point2D(GameMath.random(0, (float)getWidth()), y + GameMath.random(50))); emitter.setScaleFunction((i, x, y) -> new Point2D(GameMath.random(-0.05f, 0), GameMath.random(-0.05f, 0))); Entity bubbles = new Entity(); bubbles.addComponent(new PositionComponent(0, getHeight())); bubbles.addControl(new ParticleControl(emitter)); getGameWorld().addEntity(bubbles); // Level info } @Override protected void initPhysics() { getPhysicsWorld().setGravity(0, 0); getPhysicsWorld().addCollisionHandler(new CollisionHandler(EntityType.BALL, EntityType.BRICK) { @Override protected void onCollisionBegin(Entity ball, Entity brick) { brick.getControlUnsafe(BrickControl.class).onHit(); } }); } @Override protected void initUI() { Text text = getUIFactory().newText("Level 1", Color.WHITE, 48); QuadCurve curve = new QuadCurve(-100, 0, getWidth() / 2, getHeight(), getWidth() + 100, 0); PathTransition transition = new PathTransition(Duration.seconds(4), curve, text); transition.setOnFinished(e -> { getGameScene().removeUINode(text); getBallControl().release(); }); getGameScene().addUINode(text); transition.play(); } @Override protected void onUpdate(double tpf) {} public static void main(String[] args) { launch(args); } }
package cl.mastercode.DamageIndicator; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Animals; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.MagmaCube; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Slime; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; public class Main extends JavaPlugin implements Listener { public Main plugin; static public Main splugin; File file; YamlConfiguration cfg; static public Map<ArmorStand, Long> armorStands; public static final ConsoleCommandSender console = Bukkit.getConsoleSender(); public void reload() { this.file = new File(this.getDataFolder() + "/", "settings.yml"); this.cfg = YamlConfiguration.loadConfiguration((File)this.file); armorStands = new HashMap<>(); if (!this.file.exists()) { this.saveResource("settings.yml", false); } System.out.println("Load Complete"); } @Override public void onEnable() { this.plugin = this; splugin= this; reload(); this.getServer().getPluginManager().registerEvents((Listener)this, (Plugin)this); getCommand("damageindicator").setExecutor(new CommandHandler()); Bukkit.getScheduler().runTaskTimer((Plugin)this.plugin, new Runnable(){ @Override public void run() { if(armorStands.size()>0){ List<ArmorStand> asl = new ArrayList<ArmorStand>(); for(Entry<ArmorStand, Long> entry : armorStands.entrySet()) { if(entry.getValue()+1500 < System.currentTimeMillis()){ entry.getKey().remove(); asl.add(entry.getKey()); } else{ entry.getKey().teleport(entry.getKey().getLocation().add(0.0, 0.07, 0.0)); } } for(ArmorStand as : asl) { armorStands.remove(as); } } } }, 6,1); } @Override public void onDisable() { for(Entry<ArmorStand, Long> entry : armorStands.entrySet()) { entry.getKey().remove(); } int c = 0; for(World world: Bukkit.getWorlds()){ for(ArmorStand as : world.getEntitiesByClass(org.bukkit.entity.ArmorStand.class)) { if(Main.splugin.isDamageIndicator(as)){ as.remove(); c++; } } } console.sendMessage("§c"+c+" Damage Indicators were removed in plugin unload"+""); } public static ArmorStand getDefaultArmorStand(Location loc) { ArmorStand as; Location spawnLoc = new Location(loc.getWorld(),loc.getX(),500,loc.getZ()); as = (ArmorStand)loc.getWorld().spawnEntity(spawnLoc, EntityType.ARMOR_STAND); as.setVisible(false); as.setCustomNameVisible(false); as.setInvulnerable(true); as.setSmall(true); as.setRemoveWhenFarAway(true); as.setMetadata("Mastercode-DamageIndicator",new FixedMetadataValue(splugin, 1)); as.setGravity(false); as.setCollidable(false); as.setMarker(true); as.teleport(loc.add(0.0, 1.6, 0.0)); Bukkit.getScheduler().scheduleSyncDelayedTask((Plugin)Main.splugin, new Runnable(){ @Override public void run() { as.setCustomNameVisible(true); } },7); return as; } public boolean isDamageIndicator(ArmorStand as){ if(as.hasMetadata("Mastercode-DamageIndicator")){ return true; } return as.isInvulnerable() && as.isSmall() && !as.hasGravity() && as.isMarker() && !as.isVisible(); } public boolean isOldDamageIndicator(ArmorStand as){ if(as.isCustomNameVisible() &&!as.hasGravity() &&!as.isVisible() &&as.getCustomName()!=null &&(as.getCustomName().contains("-")||as.getCustomName().contains("+"))) { return true; } return false; } @EventHandler() public void RemoveArmorStandsOnChunkUnload(ChunkUnloadEvent event) { for(Entity entity : event.getChunk().getEntities()){ if(entity.getType().equals(EntityType.ARMOR_STAND)){ ArmorStand as = (ArmorStand)entity; if(isDamageIndicator(as)){ armorStands.remove(as); as.remove(); } } } } @EventHandler() public void RemoveArmorStandsOnChunkload(ChunkLoadEvent event) { for(Entity entity : event.getChunk().getEntities()){ if(entity.getType().equals(EntityType.ARMOR_STAND)){ ArmorStand as = (ArmorStand)entity; if(isDamageIndicator(as)){ armorStands.remove(as); as.remove(); } } } } @EventHandler(priority=EventPriority.HIGHEST) public void onEntityRegenrateHealth(EntityRegainHealthEvent e) { ArmorStand as; String cfgFormat = this.cfg.getString("Format.EntityRegain"); String displayFormat = cfgFormat.replace("&", "§").replace("%health%", "" + (int)e.getAmount()); boolean enablePlayer = this.cfg.getBoolean("UseAt.Player"); boolean enableMonster = this.cfg.getBoolean("UseAt.Monster"); boolean enableAnimal = this.cfg.getBoolean("UseAt.Animals"); if (e.getEntity() instanceof Player && enablePlayer && !e.isCancelled() && e.getAmount() < 1.0) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } as = getDefaultArmorStand(e.getEntity().getLocation()); as.setCustomName("" + displayFormat); armorStands.put(as, System.currentTimeMillis()); } if (e.getEntity() instanceof Monster || e.getEntity() instanceof Slime || e.getEntity() instanceof MagmaCube) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } if (enableMonster) { as = getDefaultArmorStand(e.getEntity().getLocation()); as.setCustomName("" + displayFormat); armorStands.put(as, System.currentTimeMillis()); } } if (e.getEntity() instanceof Animals && enableAnimal) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } as = getDefaultArmorStand(e.getEntity().getLocation()); as.setCustomName("" + displayFormat); armorStands.put(as, System.currentTimeMillis()); } } @EventHandler(priority=EventPriority.HIGHEST) public void onEntityDamageEvent(EntityDamageEvent e) { if (e.getDamage()<1 || e.isCancelled()) { return; } ArmorStand as; String cfgFormat = this.cfg.getString("Format.EntityDamage"); String displayFormat = cfgFormat.replace("&", "§").replace("%damage%", "" + (int)e.getDamage()); boolean enablePlayer = this.cfg.getBoolean("UseAt.Player"); boolean enableMonster = this.cfg.getBoolean("UseAt.Monster"); boolean enableAnimal = this.cfg.getBoolean("UseAt.Animals"); boolean enableBlood = this.cfg.getBoolean("BloodEffect"); if (enableBlood && !e.isCancelled() && e.getDamage() < 1.0 && (e.getEntity().getType() != EntityType.ARMOR_STAND || e.getEntity().getType() != EntityType.PAINTING || e.getEntity().getType() != EntityType.ITEM_FRAME) && (e.getEntity() instanceof Player || e.getEntity() instanceof Monster || e.getEntity() instanceof Animals || e.getEntity() instanceof Slime || e.getEntity() instanceof MagmaCube)) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } e.getEntity().getLocation().getWorld().playEffect(e.getEntity().getLocation().add(0.0, 1.0, 0.0), Effect.STEP_SOUND, 152); } if (e.getEntity() instanceof Player && enablePlayer) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } as = getDefaultArmorStand(e.getEntity().getLocation()); as.setCustomName("" + displayFormat); armorStands.put(as, System.currentTimeMillis()); } if (e.getEntity() instanceof Monster || e.getEntity() instanceof Slime || e.getEntity() instanceof MagmaCube) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } if (enableMonster) { as = getDefaultArmorStand(e.getEntity().getLocation()); as.setCustomName("" + displayFormat); armorStands.put(as, System.currentTimeMillis()); } } if (e.getEntity() instanceof Animals && enableAnimal) { if (e.getEntity().hasMetadata("NPC")) { return; } if (e.getEntity() instanceof ArmorStand) { return; } as = getDefaultArmorStand(e.getEntity().getLocation()); as.setCustomName("" + displayFormat); armorStands.put(as, System.currentTimeMillis()); } } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class MainRobot extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { RobotActuators.initialize(); RobotSensors.initialize(); //RobotPickup.initialize(); //RobotDrive.initialize(); RobotPickup.initialize(); //RobotDrive.initialize(); //RobotShoot.initialize(); //RobotShoot.initialize(); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { //runCompressor(); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { RobotPickup.update(); //runCompressor(); // RobotDrive.update(); // RobotDrive.driveStraight(0.5); //RobotDrive.update(); // RobotDrive.test(); // RobotDrive.drive(0.5, 1); //RobotDrive.joystickDrive(); //HOLD X -> HIGH GEAR, HOLD Y -> STOP //runCompressor(); // RobotDrive.update(); // RobotDrive.driveStraight(0.5); //RobotShoot.update(); //RobotShoot.automatedShoot(); //RobotPickUp.update(); //RobotPickUp.test(true, false, false); //RobotPickUp.update(); //RobotPickUp.test(false, false, true); //RobotShoot.manualWind(FancyJoystick.primary.getRawButton(FancyJoystick.BUTTON_A), FancyJoystick.primary.getRawButton(FancyJoystick.BUTTON_B)); } /** * This function is called periodically during test mode */ public void testPeriodic() { } private void runCompressor() { if (!RobotSensors.pressureSwitch.get()) { RobotActuators.compressor.set(Relay.Value.kOn); System.out.println("Setting the compressor to ON"); } else { RobotActuators.compressor.set(Relay.Value.kOff); } System.out.println("runCompressor finished"); } }
package net.simonvt.menudrawer; import net.simonvt.menudrawer.compat.ActionBarHelper; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.ViewTreeObserver; import android.view.animation.AccelerateInterpolator; import android.view.animation.Interpolator; public abstract class MenuDrawer extends ViewGroup { /** * Callback interface for changing state of the drawer. */ public interface OnDrawerStateChangeListener { /** * Called when the drawer state changes. * * @param oldState The old drawer state. * @param newState The new drawer state. */ void onDrawerStateChange(int oldState, int newState); /** * Called when the drawer slides. * * @param openRatio Ratio for how open the menu is. * @param offsetPixels Current offset of the menu in pixels. */ void onDrawerSlide(float openRatio, int offsetPixels); } /** * Callback that is invoked when the drawer is in the process of deciding whether it should intercept the touch * event. This lets the listener decide if the pointer is on a view that would disallow dragging of the drawer. * This is only called when the touch mode is {@link #TOUCH_MODE_FULLSCREEN}. */ public interface OnInterceptMoveEventListener { /** * Called for each child the pointer i on when the drawer is deciding whether to intercept the touch event. * * @param v View to test for draggability * @param delta Delta drag in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if view is draggable by delta dx. */ boolean isViewDraggable(View v, int delta, int x, int y); } public enum Type { /** * Positions the drawer behind the content. */ BEHIND, /** * A static drawer that can not be dragged. */ STATIC, /** * Positions the drawer on top of the content. */ OVERLAY, } /** * Tag used when logging. */ private static final String TAG = "MenuDrawer"; /** * Indicates whether debug code should be enabled. */ private static final boolean DEBUG = false; /** * The time between each frame when animating the drawer. */ protected static final int ANIMATION_DELAY = 1000 / 60; /** * The default touch bezel size of the drawer in dp. */ private static final int DEFAULT_DRAG_BEZEL_DP = 24; /** * The default drop shadow size in dp. */ private static final int DEFAULT_DROP_SHADOW_DP = 6; /** * Drag mode for sliding only the content view. */ public static final int MENU_DRAG_CONTENT = 0; /** * Drag mode for sliding the entire window. */ public static final int MENU_DRAG_WINDOW = 1; /** * Disallow opening the drawer by dragging the screen. */ public static final int TOUCH_MODE_NONE = 0; /** * Allow opening drawer only by dragging on the edge of the screen. */ public static final int TOUCH_MODE_BEZEL = 1; /** * Allow opening drawer by dragging anywhere on the screen. */ public static final int TOUCH_MODE_FULLSCREEN = 2; /** * Indicates that the drawer is currently closed. */ public static final int STATE_CLOSED = 0; /** * Indicates that the drawer is currently closing. */ public static final int STATE_CLOSING = 1; /** * Indicates that the drawer is currently being dragged by the user. */ public static final int STATE_DRAGGING = 2; /** * Indicates that the drawer is currently opening. */ public static final int STATE_OPENING = 4; /** * Indicates that the drawer is currently open. */ public static final int STATE_OPEN = 8; /** * Indicates whether to use {@link View#setTranslationX(float)} when positioning views. */ static final boolean USE_TRANSLATIONS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; /** * Time to animate the indicator to the new active view. */ static final int INDICATOR_ANIM_DURATION = 800; /** * The maximum animation duration. */ private static final int DEFAULT_ANIMATION_DURATION = 600; /** * Interpolator used when animating the drawer open/closed. */ protected static final Interpolator SMOOTH_INTERPOLATOR = new SmoothInterpolator(); /** * Interpolator used for stretching/retracting the active indicator. */ protected static final Interpolator INDICATOR_INTERPOLATOR = new AccelerateInterpolator(); /** * Drawable used as menu overlay. */ protected Drawable mMenuOverlay; /** * Defines whether the drop shadow is enabled. */ protected boolean mDropShadowEnabled; /** * The color of the drop shadow. */ protected int mDropShadowColor; /** * Drawable used as content drop shadow onto the menu. */ protected Drawable mDropShadowDrawable; /** * The size of the content drop shadow. */ protected int mDropShadowSize; /** * Bitmap used to indicate the active view. */ protected Bitmap mActiveIndicator; /** * The currently active view. */ protected View mActiveView; /** * Position of the active view. This is compared to View#getTag(R.id.mdActiveViewPosition) when drawing the * indicator. */ protected int mActivePosition; /** * Whether the indicator should be animated between positions. */ private boolean mAllowIndicatorAnimation; /** * Used when reading the position of the active view. */ protected final Rect mActiveRect = new Rect(); /** * Temporary {@link Rect} used for deciding whether the view should be invalidated so the indicator can be redrawn. */ private final Rect mTempRect = new Rect(); /** * The custom menu view set by the user. */ private View mMenuView; /** * The parent of the menu view. */ protected BuildLayerFrameLayout mMenuContainer; /** * The parent of the content view. */ protected BuildLayerFrameLayout mContentContainer; /** * The size of the menu (width or height depending on the gravity). */ protected int mMenuSize; /** * Indicates whether the menu is currently visible. */ protected boolean mMenuVisible; /** * The drag mode of the drawer. Can be either {@link #MENU_DRAG_CONTENT} or {@link #MENU_DRAG_WINDOW}. */ private int mDragMode = MENU_DRAG_CONTENT; /** * The current drawer state. * * @see #STATE_CLOSED * @see #STATE_CLOSING * @see #STATE_DRAGGING * @see #STATE_OPENING * @see #STATE_OPEN */ protected int mDrawerState = STATE_CLOSED; /** * The touch bezel size of the drawer in px. */ protected int mTouchBezelSize; /** * The touch area size of the drawer in px. */ protected int mTouchSize; /** * Listener used to dispatch state change events. */ private OnDrawerStateChangeListener mOnDrawerStateChangeListener; /** * Touch mode for the Drawer. * Possible values are {@link #TOUCH_MODE_NONE}, {@link #TOUCH_MODE_BEZEL} or {@link #TOUCH_MODE_FULLSCREEN} * Default: {@link #TOUCH_MODE_BEZEL} */ protected int mTouchMode = TOUCH_MODE_BEZEL; /** * Indicates whether to use {@link View#LAYER_TYPE_HARDWARE} when animating the drawer. */ protected boolean mHardwareLayersEnabled = true; /** * The Activity the drawer is attached to. */ private Activity mActivity; /** * Scroller used when animating the indicator to a new position. */ private FloatScroller mIndicatorScroller; /** * Runnable used when animating the indicator to a new position. */ private Runnable mIndicatorRunnable = new Runnable() { @Override public void run() { animateIndicatorInvalidate(); } }; /** * The start position of the indicator when animating it to a new position. */ protected int mIndicatorStartPos; /** * [0..1] value indicating the current progress of the animation. */ protected float mIndicatorOffset; /** * Whether the indicator is currently animating. */ protected boolean mIndicatorAnimating; /** * Bundle used to hold the drawers state. */ protected Bundle mState; /** * The maximum duration of open/close animations. */ protected int mMaxAnimationDuration = DEFAULT_ANIMATION_DURATION; /** * Callback that lets the listener override intercepting of touch events. */ protected OnInterceptMoveEventListener mOnInterceptMoveEventListener; protected SlideDrawable mSlideDrawable; protected Drawable mThemeUpIndicator; protected boolean mDrawerIndicatorEnabled; private ActionBarHelper mActionBarHelper; private int mCurrentUpContentDesc; private int mDrawerOpenContentDesc; private int mDrawerClosedContentDesc; /** * The position of the drawer. */ protected Position mPosition; private final Rect mIndicatorClipRect = new Rect(); protected boolean mIsStatic; protected final Rect mDropShadowRect = new Rect(); /** * Current offset. */ protected float mOffsetPixels; /** * Whether an overlay should be drawn as the drawer is opened and closed. */ protected boolean mDrawOverlay; /** * Attaches the MenuDrawer to the Activity. * * @param activity The activity that the MenuDrawer will be attached to. * @return The created MenuDrawer instance. */ public static MenuDrawer attach(Activity activity) { return attach(activity, Type.BEHIND); } /** * Attaches the MenuDrawer to the Activity. * * @param activity The activity the menu drawer will be attached to. * @param type The {@link Type} of the drawer. * @return The created MenuDrawer instance. */ public static MenuDrawer attach(Activity activity, Type type) { return attach(activity, type, Position.LEFT); } /** * Attaches the MenuDrawer to the Activity. * * @param activity The activity the menu drawer will be attached to. * @param position Where to position the menu. * @return The created MenuDrawer instance. */ public static MenuDrawer attach(Activity activity, Position position) { return attach(activity, Type.BEHIND, position); } /** * Attaches the MenuDrawer to the Activity. * * @param activity The activity the menu drawer will be attached to. * @param type The {@link Type} of the drawer. * @param position Where to position the menu. * @return The created MenuDrawer instance. */ public static MenuDrawer attach(Activity activity, Type type, Position position) { return attach(activity, type, position, MENU_DRAG_CONTENT); } /** * Attaches the MenuDrawer to the Activity. * * @param activity The activity the menu drawer will be attached to. * @param type The {@link Type} of the drawer. * @param position Where to position the menu. * @param dragMode The drag mode of the drawer. Can be either {@link MenuDrawer#MENU_DRAG_CONTENT} * or {@link MenuDrawer#MENU_DRAG_WINDOW}. * @return The created MenuDrawer instance. */ public static MenuDrawer attach(Activity activity, Type type, Position position, int dragMode) { MenuDrawer menuDrawer = createMenuDrawer(activity, dragMode, position, type); menuDrawer.setId(R.id.md__drawer); switch (dragMode) { case MenuDrawer.MENU_DRAG_CONTENT: attachToContent(activity, menuDrawer); break; case MenuDrawer.MENU_DRAG_WINDOW: attachToDecor(activity, menuDrawer); break; default: throw new RuntimeException("Unknown menu mode: " + dragMode); } return menuDrawer; } /** * Constructs the appropriate MenuDrawer based on the position. */ private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) { MenuDrawer drawer; if (type == Type.STATIC) { drawer = new StaticDrawer(activity); } else if (type == Type.OVERLAY) { drawer = new OverlayDrawer(activity, dragMode); if (position == Position.LEFT) { drawer.setupUpIndicator(activity); } } else { drawer = new SlidingDrawer(activity, dragMode); if (position == Position.LEFT) { drawer.setupUpIndicator(activity); } } drawer.mDragMode = dragMode; drawer.mPosition = position; return drawer; } /** * Attaches the menu drawer to the content view. */ private static void attachToContent(Activity activity, MenuDrawer menuDrawer) { /** * Do not call mActivity#setContentView. * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to * MenuDrawer#setContentView, which then again would call Activity#setContentView. */ ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content); content.removeAllViews(); content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } /** * Attaches the menu drawer to the window. */ private static void attachToDecor(Activity activity, MenuDrawer menuDrawer) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0); decorView.removeAllViews(); decorView.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); menuDrawer.mContentContainer.addView(decorChild, decorChild.getLayoutParams()); } MenuDrawer(Activity activity, int dragMode) { this(activity); mActivity = activity; mDragMode = dragMode; } public MenuDrawer(Context context) { this(context, null); } public MenuDrawer(Context context, AttributeSet attrs) { this(context, attrs, R.attr.menuDrawerStyle); } public MenuDrawer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initDrawer(context, attrs, defStyle); } protected void initDrawer(Context context, AttributeSet attrs, int defStyle) { setWillNotDraw(false); setFocusable(false); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MenuDrawer, R.attr.menuDrawerStyle, R.style.Widget_MenuDrawer); final Drawable contentBackground = a.getDrawable(R.styleable.MenuDrawer_mdContentBackground); final Drawable menuBackground = a.getDrawable(R.styleable.MenuDrawer_mdMenuBackground); mMenuSize = a.getDimensionPixelSize(R.styleable.MenuDrawer_mdMenuSize, dpToPx(240)); final int indicatorResId = a.getResourceId(R.styleable.MenuDrawer_mdActiveIndicator, 0); if (indicatorResId != 0) { mActiveIndicator = BitmapFactory.decodeResource(getResources(), indicatorResId); } mDropShadowEnabled = a.getBoolean(R.styleable.MenuDrawer_mdDropShadowEnabled, true); mDropShadowDrawable = a.getDrawable(R.styleable.MenuDrawer_mdDropShadow); if (mDropShadowDrawable == null) { mDropShadowColor = a.getColor(R.styleable.MenuDrawer_mdDropShadowColor, 0xFF000000); } mDropShadowSize = a.getDimensionPixelSize(R.styleable.MenuDrawer_mdDropShadowSize, dpToPx(DEFAULT_DROP_SHADOW_DP)); mTouchBezelSize = a.getDimensionPixelSize(R.styleable.MenuDrawer_mdTouchBezelSize, dpToPx(DEFAULT_DRAG_BEZEL_DP)); mAllowIndicatorAnimation = a.getBoolean(R.styleable.MenuDrawer_mdAllowIndicatorAnimation, false); mMaxAnimationDuration = a.getInt(R.styleable.MenuDrawer_mdMaxAnimationDuration, DEFAULT_ANIMATION_DURATION); final int slideDrawableResId = a.getResourceId(R.styleable.MenuDrawer_mdSlideDrawable, -1); if (slideDrawableResId != -1) { setSlideDrawable(slideDrawableResId); } mDrawerOpenContentDesc = a.getResourceId(R.styleable.MenuDrawer_mdDrawerOpenUpContentDescription, 0); mDrawerClosedContentDesc = a.getResourceId(R.styleable.MenuDrawer_mdDrawerClosedUpContentDescription, 0); mDrawOverlay = a.getBoolean(R.styleable.MenuDrawer_mdDrawOverlay, true); final int position = a.getInt(R.styleable.MenuDrawer_mdPosition, 0); mPosition = Position.fromValue(position); a.recycle(); mMenuContainer = new NoClickThroughFrameLayout(context); mMenuContainer.setId(R.id.md__menu); mMenuContainer.setBackgroundDrawable(menuBackground); mContentContainer = new NoClickThroughFrameLayout(context); mContentContainer.setId(R.id.md__content); mContentContainer.setBackgroundDrawable(contentBackground); mMenuOverlay = new ColorDrawable(0xFF000000); mIndicatorScroller = new FloatScroller(SMOOTH_INTERPOLATOR); } @Override protected void onFinishInflate() { super.onFinishInflate(); View menu = findViewById(R.id.mdMenu); if (menu != null) { removeView(menu); setMenuView(menu); } View content = findViewById(R.id.mdContent); if (content != null) { removeView(content); setContentView(content); } if (getChildCount() > 2) { throw new IllegalStateException( "Menu and content view added in xml must have id's @id/mdMenu and @id/mdContent"); } } protected int dpToPx(int dp) { return (int) (getResources().getDisplayMetrics().density * dp + 0.5f); } protected boolean isViewDescendant(View v) { ViewParent parent = v.getParent(); while (parent != null) { if (parent == this) { return true; } parent = parent.getParent(); } return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); getViewTreeObserver().addOnScrollChangedListener(mScrollListener); } @Override protected void onDetachedFromWindow() { getViewTreeObserver().removeOnScrollChangedListener(mScrollListener); super.onDetachedFromWindow(); } private boolean shouldDrawIndicator() { return mActiveView != null && mActiveIndicator != null && isViewDescendant(mActiveView); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); final int offsetPixels = (int) mOffsetPixels; if (mDrawOverlay && offsetPixels != 0) { drawOverlay(canvas); } if (mDropShadowEnabled && (offsetPixels != 0 || mIsStatic)) { drawDropShadow(canvas); } if (shouldDrawIndicator() && offsetPixels != 0) { drawIndicator(canvas); } } protected abstract void drawOverlay(Canvas canvas); private void drawDropShadow(Canvas canvas) { // Can't pass the position to the constructor, so wait with loading the drawable until the drop shadow is // actually drawn. if (mDropShadowDrawable == null) { setDropShadowColor(mDropShadowColor); } updateDropShadowRect(); mDropShadowDrawable.setBounds(mDropShadowRect); mDropShadowDrawable.draw(canvas); } protected void updateDropShadowRect() { // This updates the rect for the static and sliding drawer. The overlay drawer has its own implementation. switch (mPosition) { case LEFT: mDropShadowRect.top = 0; mDropShadowRect.bottom = getHeight(); mDropShadowRect.right = ViewHelper.getLeft(mContentContainer); mDropShadowRect.left = mDropShadowRect.right - mDropShadowSize; break; case TOP: mDropShadowRect.left = 0; mDropShadowRect.right = getWidth(); mDropShadowRect.bottom = ViewHelper.getTop(mContentContainer); mDropShadowRect.top = mDropShadowRect.bottom - mDropShadowSize; break; case RIGHT: mDropShadowRect.top = 0; mDropShadowRect.bottom = getHeight(); mDropShadowRect.left = ViewHelper.getRight(mContentContainer); mDropShadowRect.right = mDropShadowRect.left + mDropShadowSize; break; case BOTTOM: mDropShadowRect.left = 0; mDropShadowRect.right = getWidth(); mDropShadowRect.top = ViewHelper.getBottom(mContentContainer); mDropShadowRect.bottom = mDropShadowRect.top + mDropShadowSize; break; } } private void drawIndicator(Canvas canvas) { Integer position = (Integer) mActiveView.getTag(R.id.mdActiveViewPosition); final int pos = position == null ? 0 : position; if (pos == mActivePosition) { updateIndicatorClipRect(); canvas.save(); canvas.clipRect(mIndicatorClipRect); int drawLeft = 0; int drawTop = 0; switch (mPosition) { case LEFT: case TOP: drawLeft = mIndicatorClipRect.left; drawTop = mIndicatorClipRect.top; break; case RIGHT: drawLeft = mIndicatorClipRect.right - mActiveIndicator.getWidth(); drawTop = mIndicatorClipRect.top; break; case BOTTOM: drawLeft = mIndicatorClipRect.left; drawTop = mIndicatorClipRect.bottom - mActiveIndicator.getHeight(); } canvas.drawBitmap(mActiveIndicator, drawLeft, drawTop, null); canvas.restore(); } } /** * Update the {@link Rect} where the indicator is drawn. */ protected void updateIndicatorClipRect() { mActiveView.getDrawingRect(mActiveRect); offsetDescendantRectToMyCoords(mActiveView, mActiveRect); final float openRatio = mIsStatic ? 1.0f : Math.abs(mOffsetPixels) / mMenuSize; final float interpolatedRatio = 1.f - INDICATOR_INTERPOLATOR.getInterpolation((1.f - openRatio)); final int indicatorWidth = mActiveIndicator.getWidth(); final int indicatorHeight = mActiveIndicator.getHeight(); final int interpolatedWidth = (int) (indicatorWidth * interpolatedRatio); final int interpolatedHeight = (int) (indicatorHeight * interpolatedRatio); final int startPos = mIndicatorStartPos; int left = 0; int top = 0; int right = 0; int bottom = 0; switch (mPosition) { case LEFT: case RIGHT: final int finalTop = mActiveRect.top + ((mActiveRect.height() - indicatorHeight) / 2); if (mIndicatorAnimating) { top = (int) (startPos + ((finalTop - startPos) * mIndicatorOffset)); } else { top = finalTop; } bottom = top + indicatorHeight; break; case TOP: case BOTTOM: final int finalLeft = mActiveRect.left + ((mActiveRect.width() - indicatorWidth) / 2); if (mIndicatorAnimating) { left = (int) (startPos + ((finalLeft - startPos) * mIndicatorOffset)); } else { left = finalLeft; } right = left + indicatorWidth; break; } switch (mPosition) { case LEFT: { right = ViewHelper.getLeft(mContentContainer); left = right - interpolatedWidth; break; } case TOP: { bottom = ViewHelper.getTop(mContentContainer); top = bottom - interpolatedHeight; break; } case RIGHT: { left = ViewHelper.getRight(mContentContainer); right = left + interpolatedWidth; break; } case BOTTOM: { top = ViewHelper.getBottom(mContentContainer); bottom = top + interpolatedHeight; break; } } mIndicatorClipRect.left = left; mIndicatorClipRect.top = top; mIndicatorClipRect.right = right; mIndicatorClipRect.bottom = bottom; } /** * Toggles the menu open and close with animation. */ public void toggleMenu() { toggleMenu(true); } /** * Toggles the menu open and close. * * @param animate Whether open/close should be animated. */ public abstract void toggleMenu(boolean animate); /** * Animates the menu open. */ public void openMenu() { openMenu(true); } /** * Opens the menu. * * @param animate Whether open/close should be animated. */ public abstract void openMenu(boolean animate); /** * Animates the menu closed. */ public void closeMenu() { closeMenu(true); } /** * Closes the menu. * * @param animate Whether open/close should be animated. */ public abstract void closeMenu(boolean animate); /** * Indicates whether the menu is currently visible. * * @return True if the menu is open, false otherwise. */ public abstract boolean isMenuVisible(); /** * Set the size of the menu drawer when open. * * @param size The size of the menu. */ public abstract void setMenuSize(int size); /** * Returns the size of the menu. * * @return The size of the menu. */ public int getMenuSize() { return mMenuSize; } /** * Set the active view. * If the mdActiveIndicator attribute is set, this View will have the indicator drawn next to it. * * @param v The active view. */ public void setActiveView(View v) { setActiveView(v, 0); } /** * Set the active view. * If the mdActiveIndicator attribute is set, this View will have the indicator drawn next to it. * * @param v The active view. * @param position Optional position, usually used with ListView. v.setTag(R.id.mdActiveViewPosition, position) * must be called first. */ public void setActiveView(View v, int position) { final View oldView = mActiveView; mActiveView = v; mActivePosition = position; if (mAllowIndicatorAnimation && oldView != null) { startAnimatingIndicator(); } invalidate(); } /** * Sets whether the indicator should be animated between active views. * * @param animate Whether the indicator should be animated between active views. */ public void setAllowIndicatorAnimation(boolean animate) { if (animate != mAllowIndicatorAnimation) { mAllowIndicatorAnimation = animate; completeAnimatingIndicator(); } } /** * Indicates whether the indicator should be animated between active views. * * @return Whether the indicator should be animated between active views. */ public boolean getAllowIndicatorAnimation() { return mAllowIndicatorAnimation; } /** * Scroll listener that checks whether the active view has moved before the drawer is invalidated. */ private ViewTreeObserver.OnScrollChangedListener mScrollListener = new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (mActiveView != null && isViewDescendant(mActiveView)) { mActiveView.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(mActiveView, mTempRect); if (mTempRect.left != mActiveRect.left || mTempRect.top != mActiveRect.top || mTempRect.right != mActiveRect.right || mTempRect.bottom != mActiveRect.bottom) { invalidate(); } } } }; /** * Starts animating the indicator to a new position. */ private void startAnimatingIndicator() { mIndicatorStartPos = getIndicatorStartPos(); mIndicatorAnimating = true; mIndicatorScroller.startScroll(0.0f, 1.0f, INDICATOR_ANIM_DURATION); animateIndicatorInvalidate(); } /** * Returns the start position of the indicator. * * @return The start position of the indicator. */ private int getIndicatorStartPos() { switch (mPosition) { case TOP: return mIndicatorClipRect.left; case RIGHT: return mIndicatorClipRect.top; case BOTTOM: return mIndicatorClipRect.left; default: return mIndicatorClipRect.top; } } /** * Compute the touch area based on the touch mode. */ protected void updateTouchAreaSize() { if (mTouchMode == TOUCH_MODE_BEZEL) { mTouchSize = mTouchBezelSize; } else if (mTouchMode == TOUCH_MODE_FULLSCREEN) { mTouchSize = getMeasuredWidth(); } else { mTouchSize = 0; } } /** * Callback when each frame in the indicator animation should be drawn. */ private void animateIndicatorInvalidate() { if (mIndicatorScroller.computeScrollOffset()) { mIndicatorOffset = mIndicatorScroller.getCurr(); invalidate(); if (!mIndicatorScroller.isFinished()) { postOnAnimation(mIndicatorRunnable); return; } } completeAnimatingIndicator(); } /** * Called when the indicator animation has completed. */ private void completeAnimatingIndicator() { mIndicatorOffset = 1.0f; mIndicatorAnimating = false; invalidate(); } /** * Enables or disables offsetting the menu when dragging the drawer. * * @param offsetMenu True to offset the menu, false otherwise. */ public abstract void setOffsetMenuEnabled(boolean offsetMenu); /** * Indicates whether the menu is being offset when dragging the drawer. * * @return True if the menu is being offset, false otherwise. */ public abstract boolean getOffsetMenuEnabled(); /** * Get the current state of the drawer. * * @return The state of the drawer. */ public int getDrawerState() { return mDrawerState; } /** * Register a callback to be invoked when the drawer state changes. * * @param listener The callback that will run. */ public void setOnDrawerStateChangeListener(OnDrawerStateChangeListener listener) { mOnDrawerStateChangeListener = listener; } /** * Register a callback that will be invoked when the drawer is about to intercept touch events. * * @param listener The callback that will be invoked. */ public void setOnInterceptMoveEventListener(OnInterceptMoveEventListener listener) { mOnInterceptMoveEventListener = listener; } /** * Defines whether the drop shadow is enabled. * * @param enabled Whether the drop shadow is enabled. */ public void setDropShadowEnabled(boolean enabled) { mDropShadowEnabled = enabled; invalidate(); } protected GradientDrawable.Orientation getDropShadowOrientation() { // Gets the orientation for the static and sliding drawer. The overlay drawer provides its own implementation. switch (mPosition) { case TOP: return GradientDrawable.Orientation.BOTTOM_TOP; case RIGHT: return GradientDrawable.Orientation.LEFT_RIGHT; case BOTTOM: return GradientDrawable.Orientation.TOP_BOTTOM; default: return GradientDrawable.Orientation.RIGHT_LEFT; } } /** * Sets the color of the drop shadow. * * @param color The color of the drop shadow. */ public void setDropShadowColor(int color) { GradientDrawable.Orientation orientation = getDropShadowOrientation(); final int endColor = color & 0x00FFFFFF; mDropShadowDrawable = new GradientDrawable(orientation, new int[] { color, endColor, }); invalidate(); } /** * Sets the drawable of the drop shadow. * * @param drawable The drawable of the drop shadow. */ public void setDropShadow(Drawable drawable) { mDropShadowDrawable = drawable; invalidate(); } /** * Sets the drawable of the drop shadow. * * @param resId The resource identifier of the the drawable. */ public void setDropShadow(int resId) { setDropShadow(getResources().getDrawable(resId)); } /** * Returns the drawable of the drop shadow. */ public Drawable getDropShadow() { return mDropShadowDrawable; } /** * Sets the size of the drop shadow. * * @param size The size of the drop shadow in px. */ public void setDropShadowSize(int size) { mDropShadowSize = size; invalidate(); } /** * Animates the drawer slightly open until the user opens the drawer. */ public abstract void peekDrawer(); /** * Animates the drawer slightly open. If delay is larger than 0, this happens until the user opens the drawer. * * @param delay The delay (in milliseconds) between each run of the animation. If 0, this animation is only run * once. */ public abstract void peekDrawer(long delay); /** * Animates the drawer slightly open. If delay is larger than 0, this happens until the user opens the drawer. * * @param startDelay The delay (in milliseconds) until the animation is first run. * @param delay The delay (in milliseconds) between each run of the animation. If 0, this animation is only run * once. */ public abstract void peekDrawer(long startDelay, long delay); /** * Enables or disables the user of {@link View#LAYER_TYPE_HARDWARE} when animations views. * * @param enabled Whether hardware layers are enabled. */ public abstract void setHardwareLayerEnabled(boolean enabled); /** * Sets the maximum duration of open/close animations. * * @param duration The maximum duration in milliseconds. */ public void setMaxAnimationDuration(int duration) { mMaxAnimationDuration = duration; } /** * Sets whether an overlay should be drawn when sliding the drawer. * * @param drawOverlay Whether an overlay should be drawn when sliding the drawer. */ public void setDrawOverlay(boolean drawOverlay) { mDrawOverlay = drawOverlay; } /** * Gets whether an overlay is drawn when sliding the drawer. * * @return Whether an overlay is drawn when sliding the drawer. */ public boolean getDrawOverlay() { return mDrawOverlay; } protected void updateUpContentDescription() { final int upContentDesc = isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc; if (mDrawerIndicatorEnabled && mActionBarHelper != null && upContentDesc != mCurrentUpContentDesc) { mCurrentUpContentDesc = upContentDesc; mActionBarHelper.setActionBarDescription(upContentDesc); } } /** * Sets the drawable used as the drawer indicator. * * @param drawable The drawable used as the drawer indicator. */ public void setSlideDrawable(int drawableRes) { setSlideDrawable(getResources().getDrawable(drawableRes)); } /** * Sets the drawable used as the drawer indicator. * * @param drawable The drawable used as the drawer indicator. */ public void setSlideDrawable(Drawable drawable) { mSlideDrawable = new SlideDrawable(drawable); if (mActionBarHelper != null) { mActionBarHelper.setDisplayShowHomeAsUpEnabled(true); if (mDrawerIndicatorEnabled) { mActionBarHelper.setActionBarUpIndicator(mSlideDrawable, isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc); } } } /** * Sets up the drawer indicator. It cna then be shown with {@link #setDrawerIndicatorEnabled(boolean)}. * * @param activity The activity the drawer is attached to. */ public void setupUpIndicator(Activity activity) { if (mActionBarHelper == null) { mActionBarHelper = new ActionBarHelper(activity); mThemeUpIndicator = mActionBarHelper.getThemeUpIndicator(); if (mDrawerIndicatorEnabled) { mActionBarHelper.setActionBarUpIndicator(mSlideDrawable, isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc); } } } /** * Sets whether the drawer indicator should be enabled. {@link #setupUpIndicator(android.app.Activity)} must be * called first. * * @param enabled Whether the drawer indicator should enabled. */ public void setDrawerIndicatorEnabled(boolean enabled) { if (mActionBarHelper == null) { throw new IllegalStateException("setupUpIndicator(Activity) has not been called"); } mDrawerIndicatorEnabled = enabled; if (enabled) { mActionBarHelper.setActionBarUpIndicator(mSlideDrawable, isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc); } else { mActionBarHelper.setActionBarUpIndicator(mThemeUpIndicator, 0); } } /** * Indicates whether the drawer indicator is currently enabled. * * @return Whether the drawer indicator is enabled. */ public boolean isDrawerIndicatorEnabled() { return mDrawerIndicatorEnabled; } /** * Returns the ViewGroup used as a parent for the menu view. * * @return The menu view's parent. */ public ViewGroup getMenuContainer() { return mMenuContainer; } /** * Returns the ViewGroup used as a parent for the content view. * * @return The content view's parent. */ public ViewGroup getContentContainer() { if (mDragMode == MENU_DRAG_CONTENT) { return mContentContainer; } else { return (ViewGroup) findViewById(android.R.id.content); } } /** * Set the menu view from a layout resource. * * @param layoutResId Resource ID to be inflated. */ public void setMenuView(int layoutResId) { mMenuContainer.removeAllViews(); mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false); mMenuContainer.addView(mMenuView); } /** * Set the menu view to an explicit view. * * @param view The menu view. */ public void setMenuView(View view) { setMenuView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /** * Set the menu view to an explicit view. * * @param view The menu view. * @param params Layout parameters for the view. */ public void setMenuView(View view, LayoutParams params) { mMenuView = view; mMenuContainer.removeAllViews(); mMenuContainer.addView(view, params); } /** * Returns the menu view. * * @return The menu view. */ public View getMenuView() { return mMenuView; } /** * Set the content from a layout resource. * * @param layoutResId Resource ID to be inflated. */ public void setContentView(int layoutResId) { switch (mDragMode) { case MenuDrawer.MENU_DRAG_CONTENT: mContentContainer.removeAllViews(); LayoutInflater.from(getContext()).inflate(layoutResId, mContentContainer, true); break; case MenuDrawer.MENU_DRAG_WINDOW: mActivity.setContentView(layoutResId); break; } } /** * Set the content to an explicit view. * * @param view The desired content to display. */ public void setContentView(View view) { setContentView(view, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /** * Set the content to an explicit view. * * @param view The desired content to display. * @param params Layout parameters for the view. */ public void setContentView(View view, LayoutParams params) { switch (mDragMode) { case MenuDrawer.MENU_DRAG_CONTENT: mContentContainer.removeAllViews(); mContentContainer.addView(view, params); break; case MenuDrawer.MENU_DRAG_WINDOW: mActivity.setContentView(view, params); break; } } protected void setDrawerState(int state) { if (state != mDrawerState) { final int oldState = mDrawerState; mDrawerState = state; if (mOnDrawerStateChangeListener != null) mOnDrawerStateChangeListener.onDrawerStateChange(oldState, state); if (DEBUG) logDrawerState(state); } } protected void logDrawerState(int state) { switch (state) { case STATE_CLOSED: Log.d(TAG, "[DrawerState] STATE_CLOSED"); break; case STATE_CLOSING: Log.d(TAG, "[DrawerState] STATE_CLOSING"); break; case STATE_DRAGGING: Log.d(TAG, "[DrawerState] STATE_DRAGGING"); break; case STATE_OPENING: Log.d(TAG, "[DrawerState] STATE_OPENING"); break; case STATE_OPEN: Log.d(TAG, "[DrawerState] STATE_OPEN"); break; default: Log.d(TAG, "[DrawerState] Unknown: " + state); } } /** * Returns the touch mode. */ public abstract int getTouchMode(); /** * Sets the drawer touch mode. Possible values are {@link #TOUCH_MODE_NONE}, {@link #TOUCH_MODE_BEZEL} or * {@link #TOUCH_MODE_FULLSCREEN}. * * @param mode The touch mode. */ public abstract void setTouchMode(int mode); /** * Sets the size of the touch bezel. * * @param size The touch bezel size in px. */ public abstract void setTouchBezelSize(int size); /** * Returns the size of the touch bezel in px. */ public abstract int getTouchBezelSize(); @Override public void postOnAnimation(Runnable action) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { super.postOnAnimation(action); } else { postDelayed(action, ANIMATION_DELAY); } } @Override protected boolean fitSystemWindows(Rect insets) { if (mDragMode == MENU_DRAG_WINDOW) { mMenuContainer.setPadding(0, insets.top, 0, 0); } return super.fitSystemWindows(insets); } protected void dispatchOnDrawerSlide(float openRatio, int offsetPixels) { if (mOnDrawerStateChangeListener != null) { mOnDrawerStateChangeListener.onDrawerSlide(openRatio, offsetPixels); } } /** * Saves the state of the drawer. * * @return Returns a Parcelable containing the drawer state. */ public final Parcelable saveState() { if (mState == null) mState = new Bundle(); saveState(mState); return mState; } void saveState(Bundle state) { // State saving isn't required for subclasses. } /** * Restores the state of the drawer. * * @param in A parcelable containing the drawer state. */ public void restoreState(Parcelable in) { mState = (Bundle) in; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState state = new SavedState(superState); if (mState == null) mState = new Bundle(); saveState(mState); state.mState = mState; return state; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); restoreState(savedState.mState); } static class SavedState extends BaseSavedState { Bundle mState; public SavedState(Parcelable superState) { super(superState); } public SavedState(Parcel in) { super(in); mState = in.readBundle(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeBundle(mState); } @SuppressWarnings("UnusedDeclaration") public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package ru.otus.cache.impl; import ru.otus.cache.CacheEngine; import ru.otus.cache.IdleManager; import ru.otus.cache.MyElement; import ru.otus.observable.ObservableVariable; import ru.otus.observable.ObserverManager; import ru.otus.observable.ObserverManagerImpl; import java.lang.ref.SoftReference; import java.util.*; import java.util.function.Function; public class CacheEngineImpl<K, V> implements CacheEngine<K, V> { private static final int TIME_THRESHOLD_MS = 5; private final ObservableVariable<Long> maxElements; private final ObservableVariable<Long> lifeTimeMs; private final ObservableVariable<Long> idleTimeMs; private final boolean isEternal; private final Map<K, SoftReference<MyElement<K, V>>> elements = new LinkedHashMap<>(); private final Timer timer = new Timer(); private final ObservableVariable<Long> hit; private final ObservableVariable<Long> miss; private final ObservableVariable<Long> elementsCountSnapshot; private final ObserverManager<Long> observerManager; @SuppressWarnings("WeakerAccess") public CacheEngineImpl(int maxElements, long lifeTimeMs, long idleTimeMs, boolean isEternal) { observerManager = new ObserverManagerImpl<>(); this.maxElements = observerManager.createNewObservableVariable("maxElements", (long)maxElements); this.lifeTimeMs = observerManager.createNewObservableVariable("lifeTime", lifeTimeMs > 0 ? lifeTimeMs : 0); this.idleTimeMs = observerManager.createNewObservableVariable("idleTime", idleTimeMs > 0 ? idleTimeMs : 0); this.isEternal = lifeTimeMs == 0 && idleTimeMs == 0 || isEternal; hit = observerManager.createNewObservableVariable("hitCount", 0L); miss = observerManager.createNewObservableVariable("missCount", 0L); elementsCountSnapshot = observerManager.createNewObservableVariable("elementsCountSnapshot", 0L); } public void put(K key, V value) { if (elements.size() == maxElements.getValue()) { K firstKey = elements.keySet().iterator().next(); elements.remove(firstKey); } IdleManager idleManager = new EmptyIdleManager(); if (!isEternal) { long lifeTimeMsVal = lifeTimeMs.getValue(); if (lifeTimeMsVal != 0) { TimerTask lifeTimerTask = getTimerTask(key, lifeElement -> lifeElement.getCreationTime() + lifeTimeMsVal); timer.schedule(lifeTimerTask, lifeTimeMsVal); } long idleTimeMsVal = idleTimeMs.getValue(); if (idleTimeMsVal != 0) { idleManager = new TimerIdleManager( timerTask -> timer.schedule(timerTask, idleTimeMsVal), () -> getTimerTask(key, idleElement -> idleElement.getCreationTime() + idleTimeMsVal) ); } } elements.put(key, new SoftReference<>(new MyElement<>(key, value, idleManager))); } private MyElement<K, V> getFromMap(K key) { SoftReference<MyElement<K, V>> ref = elements.get(key); if (ref != null) return ref.get(); return null; } public MyElement<K, V> get(K key) { MyElement<K, V> element = getFromMap(key); if (element != null) { hit.setValue(hit.getValue() + 1); element.setAccessed(); } else { miss.setValue(miss.getValue() + 1); } return element; } public int getHitCount() { return (int)(long)hit.getValue(); } public int getMissCount() { return (int)(long)miss.getValue(); } @Override public void dispose() { timer.cancel(); } @Override public void clear() { elements.clear(); dispose(); } private TimerTask getTimerTask(final K key, Function<MyElement<K, V>, Long> timeFunction) { return new TimerTask() { @Override public void run() { MyElement<K, V> checkedElement = getFromMap(key); if (checkedElement == null || isT1BeforeT2(timeFunction.apply(checkedElement), System.currentTimeMillis())) { elements.remove(key); } } }; } private boolean isT1BeforeT2(long t1, long t2) { return t1 < t2 + TIME_THRESHOLD_MS; } @Override public int getMaxElements() { return (int)(long)maxElements.getValue(); } @Override public int getElementsCount() { elementsCountSnapshot.setValue( elements.values().stream() .filter(myElementSoftReference -> myElementSoftReference.get() != null) .count() ); return (int)(long) elementsCountSnapshot.getValue(); } @Override public long getLifeTimeMs() { return lifeTimeMs.getValue(); } @Override public long getIdleTimeMs() { return idleTimeMs.getValue(); } @Override public boolean isEternal() { return isEternal; } }
package nerd.tuxmobil.fahrplan.camp11; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.text.util.Linkify.TransformFilter; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class EventDetail extends Activity { private final String LOG_TAG = "Detail"; private String event_id; private String title; private int startTime; private static String feedbackURL = "https://cccv.pentabarf.org/feedback/Camp 2011/event/"; // + 4302.en.html private Locale locale; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail); Intent intent = getIntent(); locale = getResources().getConfiguration().locale; event_id = intent.getStringExtra("eventid"); startTime = intent.getIntExtra("time", 0); TextView t = (TextView)findViewById(R.id.title); title = intent.getStringExtra("title"); t.setText(title); t = (TextView)findViewById(R.id.subtitle); t.setText(intent.getStringExtra("subtitle")); t = (TextView)findViewById(R.id.speakers); t.setText(intent.getStringExtra("spkr")); t = (TextView)findViewById(R.id.abstractt); String s = intent.getStringExtra("abstract"); s = s.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(s), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); t = (TextView)findViewById(R.id.description); s = intent.getStringExtra("descr"); s = s.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(s), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); TextView l = (TextView)findViewById(R.id.linksSection); String links = intent.getStringExtra("links"); t = (TextView)findViewById(R.id.links); if (links.length() > 0) { Log.d(LOG_TAG, "show links"); l.setVisibility(View.VISIBLE); t.setVisibility(View.VISIBLE); links = links.replaceAll("\\),", ")<br>"); links = links.replaceAll("\\[(.*?)\\]\\(([^ \\)]+).*?\\)", "<a href=\"$2\">$1</a>"); t.setText(Html.fromHtml(links), TextView.BufferType.SPANNABLE); t.setMovementMethod(new LinkMovementMethod()); } else { l.setVisibility(View.GONE); t.setVisibility(View.GONE); } } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater mi = new MenuInflater(getApplication()); mi.inflate(R.menu.detailmenu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.item_feedback: StringBuilder sb = new StringBuilder(); sb.append(feedbackURL); sb.append(event_id).append("."); if (locale.getLanguage().equals("de")) { sb.append("de"); } else { sb.append("en"); } sb.append(".html"); Uri uri = Uri.parse(sb.toString()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } }
package net.domesdaybook.reader.cache; import net.domesdaybook.reader.Window; /** * * @author matt */ public interface WindowCache { /** * * @param position * @return */ public Window getWindow(final long position); /** * * @param window */ public void addWindow(final Window window); public void clear(); /** * * @param observer */ public void subscribe(final CacheObserver observer); /** * * @param observer * @return */ public boolean unsubscribe(final CacheObserver observer); public interface CacheObserver { /** * * @param window * @param toCache */ public void windowAdded(final Window window, final WindowCache toCache); /** * * @param window * @param fromCache */ public void windowRemoved(final Window window, final WindowCache fromCache); } }
package ludumdare32mapeditor; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.Action; import static javax.swing.JComponent.WHEN_FOCUSED; import static javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW; import javax.swing.JPanel; import javax.swing.KeyStroke; public class MapPanel extends JPanel { static Camera camera = new Camera(800, 608); Point lastPoint; boolean mouseDown = false; boolean draggingWorld = false; boolean ctrlDown = false; int showLayers = 3; public MapPanel() { addKeyBindings(); MouseAdapter ma = mouseAdapter(); addMouseListener(ma); addMouseMotionListener(ma); addMouseWheelListener(ma); addComponentListener(componentAdapterMap()); } @Override protected void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; camera.clearScreen(g, Color.BLACK); camera.transformGraphics(g); if ((showLayers & 1) == 1) { for (int i = 0; i < MapEditor.worlds.size(); i++) { MapEditor.worlds.get(i).paintLayer1(g); } } if (((showLayers >> 1) & 1) == 1) { for (int i = 0; i < MapEditor.worlds.size(); i++) { MapEditor.worlds.get(i).paintLayer2(g); } } for (int i = 0; i < MapEditor.worlds.size(); i++) { MapEditor.worlds.get(i).drawBorder(g, Color.WHITE); } MapEditor.worlds.get(MapEditor.selectedWorld).drawBorder(g, Color.RED); // if (mouseDown) { // Point.Double worldPoint = camera.windowToWorldCoordinates(lastPoint.x, lastPoint.y); // g.fillOval((int)(worldPoint.x-5), (int)(worldPoint.y-5), 10, 10); camera.resetTransform(g); } private void addKeyBindings() { getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "exit"); getActionMap().put("exit", exit()); getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, InputEvent.CTRL_DOWN_MASK), "ctrl_down"); getActionMap().put("ctrl_down", ctrl_down()); getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released CONTROL"), "ctrl_up"); getActionMap().put("ctrl_up", ctrl_up()); getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke("1"), "one"); getActionMap().put("one", one()); getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke("2"), "two"); getActionMap().put("two", two()); getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke("3"), "three"); getActionMap().put("three", three()); getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke("4"), "four"); getActionMap().put("four", four()); } private Action ctrl_down() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ctrlDown = true; } }; } private Action ctrl_up() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ctrlDown = false; } }; } private Action exit() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }; } private Action one() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { MapEditor.tileSet = new TileSet("img/Spritesheet/sunny.png", 16, 1); MapEditor.worlds.get(MapEditor.selectedWorld).changeTileSet(MapEditor.tileSet); repaint(); } }; } private Action two() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { MapEditor.worlds.get(MapEditor.selectedWorld).expand(1, 1, 1, 1); repaint(); } }; } private Action three() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { MapEditor.worlds.get(MapEditor.selectedWorld).contract(1, 1, 1, 1); repaint(); } }; } private Action four() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { showLayers = (showLayers) % 3 + 1; repaint(); } }; } int button; public void changeTile(Point screenPoint) { Point.Double p = camera.windowToWorldCoordinates(screenPoint.x, screenPoint.y); MapEditor.worlds.get(MapEditor.selectedWorld).changeTileWorldCoordinates((int) (p.x), (int) (p.y), ToolPanel.tile); repaint(); } private MouseAdapter mouseAdapter() { return new MouseAdapter() { @Override public void mouseWheelMoved(MouseWheelEvent e) { int scrolls = e.getWheelRotation(); //negative if scroll upwards camera.zoomOnWindowPoint(Math.pow(1.1, -scrolls), e.getPoint()); //camera.constrainToWorld(LudumDare32MapEditor.worlds[LudumDare32MapEditor.selectedWorld]); repaint(); } @Override public void mouseReleased(MouseEvent me) { if (button == 1) { changeTile(me.getPoint()); } mouseDown = false; draggingWorld = false; } @Override public void mouseDragged(MouseEvent me) { if (mouseDown && button == 3) { Point newPoint = me.getPoint(); if (draggingWorld) { Point.Double np = camera.windowToWorldCoordinates(newPoint); Point.Double lp = camera.windowToWorldCoordinates(lastPoint); MapEditor.worlds.get(MapEditor.selectedWorld).move(np.x - lp.x, np.y - lp.y); } else { camera.moveWindowPixels(lastPoint.x - newPoint.x, lastPoint.y - newPoint.y); } //camera.constrainToWorld(LudumDare32MapEditor.worlds[LudumDare32MapEditor.selectedWorld]); lastPoint = newPoint; repaint(); } else if (button == 1) { changeTile(me.getPoint()); } } @Override public void mouseMoved(MouseEvent me) { requestFocus(); } @Override public void mousePressed(MouseEvent me) { if (!mouseDown) { button = me.getButton(); lastPoint = me.getPoint(); mouseDown = true; Point.Double p = camera.windowToWorldCoordinates(lastPoint); for (int i = 0; i < MapEditor.worlds.size(); i++) { if (MapEditor.worlds.get(i).worldPointInWorld(p)) { MapEditor.selectedWorld = i; repaint(); if (button == 3 && ctrlDown) { draggingWorld = true; } break; } } } } }; } private ComponentAdapter componentAdapterMap() { return new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { Component component = e.getComponent(); int h = component.getHeight(); int w = component.getWidth(); camera.changeSize(w, h); repaint(); } }; } }
package org.apache.xerces.framework; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLMessages; import org.xml.sax.Locator; import org.xml.sax.SAXParseException; /** * Default implementation of an XML DTD scanner. * * Clients who wish to scan a DTD should implement * XMLDTDScanner.EventHandler to provide the desired behavior * when various DTD components are encountered. * * To process the DTD, the client application should follow the * following sequence: * <ol> * <li>call scanDocTypeDecl() to scan the DOCTYPE declaration * <li>call getReadingExternalEntity() to determine if scanDocTypeDecl found an * external subset * <li>if scanning an external subset, call scanDecls(true) to process the external subset * </ol> * * @see XMLDTDScanner.EventHandler * @version */ public final class XMLDTDScanner { // Constants // [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ") private static final char[] version_string = { 'v','e','r','s','i','o','n' }; // [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>' private static final char[] element_string = { 'E','L','E','M','E','N','T' }; // [46] contentspec ::= 'EMPTY' | 'ANY' | Mixed | children private static final char[] empty_string = { 'E','M','P','T','Y' }; private static final char[] any_string = { 'A','N','Y' }; // [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' // | '(' S? '#PCDATA' S? ')' private static final char[] pcdata_string = { '#','P','C','D','A','T','A' }; // [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>' private static final char[] attlist_string = { 'A','T','T','L','I','S','T' }; // [55] StringType ::= 'CDATA' private static final char[] cdata_string = { 'C','D','A','T','A' }; // [56] TokenizedType ::= 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' // | 'NMTOKEN' | 'NMTOKENS' // Note: We search for common substrings always trying to move forward // 'ID' - Common prefix of ID, IDREF and IDREFS // 'REF' - Common substring of IDREF and IDREFS after matching ID prefix // 'ENTIT' - Common prefix of ENTITY and ENTITIES // 'IES' - Suffix of ENTITIES // 'NMTOKEN' - Common prefix of NMTOKEN and NMTOKENS private static final char[] id_string = { 'I','D' }; private static final char[] ref_string = { 'R','E','F' }; private static final char[] entit_string = { 'E','N','T','I','T' }; private static final char[] ies_string = { 'I','E','S' }; private static final char[] nmtoken_string = { 'N','M','T','O','K','E','N' }; // [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' // [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' private static final char[] notation_string = { 'N','O','T','A','T','I','O','N' }; // [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue) private static final char[] required_string = { '#','R','E','Q','U','I','R','E','D' }; private static final char[] implied_string = { '#','I','M','P','L','I','E','D' }; private static final char[] fixed_string = { '#','F','I','X','E','D' }; // [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' private static final char[] include_string = { 'I','N','C','L','U','D','E' }; // [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>' private static final char[] ignore_string = { 'I','G','N','O','R','E' }; // [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>' // [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>' private static final char[] entity_string = { 'E','N','T','I','T','Y' }; // [75] ExternalID ::= 'SYSTEM' S SystemLiteral // | 'PUBLIC' S PubidLiteral S SystemLiteral // [83] PublicID ::= 'PUBLIC' S PubidLiteral private static final char[] system_string = { 'S','Y','S','T','E','M' }; private static final char[] public_string = { 'P','U','B','L','I','C' }; // [76] NDataDecl ::= S 'NDATA' S Name private static final char[] ndata_string = { 'N','D','A','T','A' }; // [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) private static final char[] encoding_string = { 'e','n','c','o','d','i','n','g' }; // Instance Variables private EventHandler fEventHandler = null; private StringPool fStringPool = null; private XMLErrorReporter fErrorReporter = null; private XMLEntityHandler fEntityHandler = null; private XMLEntityHandler.EntityReader fEntityReader = null; private XMLEntityHandler.CharBuffer fLiteralData = null; private int fReaderId = -1; private int fSystemLiteral = -1; private int fPubidLiteral = -1; private int[] opStack = null; private int[] nodeIndexStack = null; private int[] prevNodeIndexStack = null; private int fScannerState = SCANNER_STATE_INVALID; private int fIncludeSectDepth = 0; private int fDoctypeReader = -1; private int fExternalSubsetReader = -1; private int fDefaultAttValueReader = -1; private int fDefaultAttValueElementType = -1; private int fDefaultAttValueAttrName = -1; private int fDefaultAttValueOffset = -1; private int fDefaultAttValueMark = -1; private int fEntityValueReader = -1; private int fEntityValueMark = -1; private int fEMPTY = -1; private int fANY = -1; private int fMIXED = -1; private int fCHILDREN = -1; private int fCDATA = -1; private int fID = -1; private int fIDREF = -1; private int fIDREFS = -1; private int fENTITY = -1; private int fENTITIES = -1; private int fNMTOKEN = -1; private int fNMTOKENS = -1; private int fNOTATION = -1; private int fENUMERATION = -1; private int fREQUIRED = -1; private int fIMPLIED = -1; private int fFIXED = -1; private int fDEFAULT = -1; private int fXMLSpace = -1; private int fDefault = -1; private int fPreserve = -1; private int fScannerMarkupDepth = 0; private int fScannerParenDepth = 0; // Constructors public XMLDTDScanner(EventHandler eventHandler, StringPool stringPool, XMLErrorReporter errorReporter, XMLEntityHandler entityHandler, XMLEntityHandler.CharBuffer literalData) { fEventHandler = eventHandler; fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fLiteralData = literalData; init(); } /** * Is the XMLDTDScanner reading from an external entity? * * This will be true, in particular if there was an external subset * * @return true if the XMLDTDScanner is reading from an external entity. */ public boolean getReadingExternalEntity() { return fReaderId != fDoctypeReader; } /** * Is the scanner reading a ContentSpec? * * @return true if the scanner is reading a ContentSpec */ public boolean getReadingContentSpec() { return getScannerState() == SCANNER_STATE_CONTENTSPEC; } /** * Report the markup nesting depth. This allows a client to * perform validation checks for correct markup nesting. This keeps * scanning and validation separate. * * @return the markup nesting depth */ public int markupDepth() { return fScannerMarkupDepth; } private int increaseMarkupDepth() { return fScannerMarkupDepth++; } private int decreaseMarkupDepth() { return fScannerMarkupDepth } /** * Report the parenthesis nesting depth. This allows a client to * perform validation checks for correct parenthesis balancing. This keeps * scanning and validation separate. * * @return the parenthesis depth */ public int parenDepth() { return fScannerParenDepth; } private void setParenDepth(int parenDepth) { fScannerParenDepth = parenDepth; } private void increaseParenDepth() { fScannerParenDepth++; } private void decreaseParenDepth() { fScannerParenDepth } /** * Allow XMLDTDScanner to be reused. This method is called from an * XMLParser reset method, which passes the StringPool to be used * by the reset DTD scanner instance. * * @param stringPool the string pool to be used by XMLDTDScanner. */ public void reset(StringPool stringPool, XMLEntityHandler.CharBuffer literalData) throws Exception { fStringPool = stringPool; fLiteralData = literalData; fEntityReader = null; fReaderId = -1; fSystemLiteral = -1; fPubidLiteral = -1; opStack = null; nodeIndexStack = null; prevNodeIndexStack = null; fScannerState = SCANNER_STATE_INVALID; fIncludeSectDepth = 0; fDoctypeReader = -1; fExternalSubsetReader = -1; fDefaultAttValueReader = -1; fDefaultAttValueElementType = -1; fDefaultAttValueAttrName = -1; fDefaultAttValueOffset = -1; fDefaultAttValueMark = -1; fEntityValueReader = -1; fEntityValueMark = -1; fScannerMarkupDepth = 0; fScannerParenDepth = 0; init(); } private void init() { fEMPTY = fStringPool.addSymbol("EMPTY"); fANY = fStringPool.addSymbol("ANY"); fMIXED = fStringPool.addSymbol("MIXED"); fCHILDREN = fStringPool.addSymbol("CHILDREN"); fCDATA = fStringPool.addSymbol("CDATA"); fID = fStringPool.addSymbol("ID"); fIDREF = fStringPool.addSymbol("IDREF"); fIDREFS = fStringPool.addSymbol("IDREFS"); fENTITY = fStringPool.addSymbol("ENTITY"); fENTITIES = fStringPool.addSymbol("ENTITIES"); fNMTOKEN = fStringPool.addSymbol("NMTOKEN"); fNMTOKENS = fStringPool.addSymbol("NMTOKENS"); fNOTATION = fStringPool.addSymbol("NOTATION"); fENUMERATION = fStringPool.addSymbol("ENUMERATION"); fREQUIRED = fStringPool.addSymbol("#REQUIRED"); fIMPLIED = fStringPool.addSymbol("#IMPLIED"); fFIXED = fStringPool.addSymbol("#FIXED"); fDEFAULT = fStringPool.addSymbol(""); fXMLSpace = fStringPool.addSymbol("xml:space"); fDefault = fStringPool.addSymbol("default"); fPreserve = fStringPool.addSymbol("preserve"); } // Interfaces /** * This interface must be implemented by the users of the XMLDTDScanner class. * These methods form the abstraction between the implementation semantics and the * more generic task of scanning the DTD-specific XML grammar. */ public interface EventHandler { /** * REVISIT - does this really do anything -- can we kill it? * * @return the current location * @exception java.lang.Exception */ public int saveCurrentLocation() throws Exception; /** * Determine whether a string is a valid XML version number * * @param version string to be checked * @return true if version is a valid XML version number * @exception java.lang.Exception */ public boolean validVersionNum(String version) throws Exception; /** * Determine whether a string is a valid encoding name * * @param encoding string to be checked * @return true if encoding is a valid encoding name * @exception java.lang.Exception */ public boolean validEncName(String encoding) throws Exception; /** * Determine if a string is a valid public identifier * * @param publicId string to be checked * @return true if publicId is a valid public identifier * @exception java.lang.Exception */ public int validPublicId(String publicId) throws Exception; /** * Called when the doctype decl is scanned * * @param rootElementType handle of the rootElement * @param publicId StringPool handle of the public id * @param systemId StringPool handle of the system id * @exception java.lang.Exception */ public void doctypeDecl(int rootElementType, int publicId, int systemId) throws Exception; /** * Called when the DTDScanner starts reading from the external subset * * @param publicId StringPool handle of the public id * @param systemId StringPool handle of the system id * @exception java.lang.Exception */ public void startReadingFromExternalSubset(int publicId, int systemId) throws Exception; /** * Called when the DTDScanner stop reading from the external subset * * @exception java.lang.Exception */ public void stopReadingFromExternalSubset() throws Exception; /** * Add an element declaration (forward reference) * * @param handle to the name of the element being declared * @return handle to the element whose declaration was added * @exception java.lang.Exception */ public int addElementDecl(int elementType) throws Exception; /** * Add an element declaration * * @param handle to the name of the element being declared * @param contentSpecType handle to the type name of the content spec * @param ContentSpec handle to the content spec node for the contentSpecType * @return handle to the element declaration that was added * @exception java.lang.Exception */ public int addElementDecl(int elementType, int contentSpecType, int contentSpec) throws Exception; /** * Add an attribute definition * * @param handle to the element whose attribute is being declared * @param attName StringPool handle to the attribute name being declared * @param attType type of the attribute * @param enumeration StringPool handle of the attribute's enumeration list (if any) * @param attDefaultType an integer value denoting the DefaultDecl value * @param attDefaultValue StringPool handle of this attribute's default value * @return handle to the attribute definition * @exception java.lang.Exception */ public int addAttDef(int elementIndex, int attName, int attType, int enumeration, int attDefaultType, int attDefaultValue) throws Exception; /** * create an XMLContentSpecNode for a leaf * * @param nameIndex StringPool handle to the name (Element) for the node * @return handle to the newly create XMLContentSpecNode * @exception java.lang.Exception */ public int addUniqueLeafNode(int nameIndex) throws Exception; /** * Create an XMLContentSpecNode for a single non-leaf * * @param nodeType the type of XMLContentSpecNode to create - from XMLContentSpecNode.CONTENTSPECNODE_* * @param nodeValue handle to an XMLContentSpecNode * @return handle to the newly create XMLContentSpecNode * @exception java.lang.Exception */ public int addContentSpecNode(int nodeType, int nodeValue) throws Exception; /** * Create an XMLContentSpecNode for a two child leaf * * @param nodeType the type of XMLContentSpecNode to create - from XMLContentSpecNode.CONTENTSPECNODE_* * @param leftNodeIndex handle to an XMLContentSpecNode * @param rightNodeIndex handle to an XMLContentSpecNode * @return handle to the newly create XMLContentSpecNode * @exception java.lang.Exception */ public int addContentSpecNode(int nodeType, int leftNodeIndex, int rightNodeIndex) throws Exception; /** * Create a string representation of an XMLContentSpecNode tree * * @param handle to an XMLContentSpecNode * @return String representation of the content spec tree * @exception java.lang.Exception */ public String getContentSpecNodeAsString(int nodeIndex) throws Exception; /** * Add a declaration for an internal parameter entity * * @param name StringPool handle of the parameter entity name * @param value StringPool handle of the parameter entity value * @param location location in the containing entity * @return handle to the parameter entity declaration * @exception java.lang.Exception */ public int addInternalPEDecl(int name, int value, int location) throws Exception; /** * Add a declaration for an external parameter entity * * @param name StringPool handle of the parameter entity name * @param publicId StringPool handle of the publicId * @param systemId StringPool handle of the systemId * @return handle to the parameter entity declaration * @exception java.lang.Exception */ public int addExternalPEDecl(int name, int publicId, int systemId) throws Exception; /** * Add a declaration for an internal entity * * @param name StringPool handle of the entity name * @param value StringPool handle of the entity value * @param location location in the containing entity * @return handle to the entity declaration * @exception java.lang.Exception */ public int addInternalEntityDecl(int name, int value, int location) throws Exception; /** * Add a declaration for an entity * * @param name StringPool handle of the entity name * @param publicId StringPool handle of the publicId * @param systemId StringPool handle of the systemId * @return handle to the entity declaration * @exception java.lang.Exception */ public int addExternalEntityDecl(int name, int publicId, int systemId) throws Exception; /** * Add a declaration for an unparsed entity * * @param name StringPool handle of the entity name * @param publicId StringPool handle of the publicId * @param systemId StringPool handle of the systemId * @param notationName StringPool handle of the notationName * @return handle to the entity declaration * @exception java.lang.Exception */ public int addUnparsedEntityDecl(int name, int publicId, int systemId, int notationName) throws Exception; /** * Called when the scanner start scanning an enumeration * @return StringPool handle to a string list that will hold the enumeration names * @exception java.lang.Exception */ public int startEnumeration() throws Exception; /** * Add a name to an enumeration * @param enumIndex StringPool handle to the string list for the enumeration * @param elementType handle to the element that owns the attribute with the enumeration * @param attrName StringPool handle to the name of the attribut with the enumeration * @param nameIndex StringPool handle to the name to be added to the enumeration * @param isNotationType true if the enumeration is an enumeration of NOTATION names * @exception java.lang.Exception */ public void addNameToEnumeration(int enumIndex, int elementType, int attrName, int nameIndex, boolean isNotationType) throws Exception; /** * Finish processing an enumeration * * @param enumIndex handle to the string list which holds the enumeration to be finshed. * @exception java.lang.Exception */ public void endEnumeration(int enumIndex) throws Exception; /** * Add a declaration for a notation * * @param notationName * @param publicId * @param systemId * @return handle to the notation declaration * @exception java.lang.Exception */ public int addNotationDecl(int notationName, int publicId, int systemId) throws Exception; /** * Called when a comment has been scanned * * @param data StringPool handle of the comment text * @exception java.lang.Exception */ public void callComment(int data) throws Exception; /** * Called when a processing instruction has been scanned * @param piTarget StringPool handle of the PI target * @param piData StringPool handle of the PI data * @exception java.lang.Exception */ public void callProcessingInstruction(int piTarget, int piData) throws Exception; /** * Scan an element type * * @param entityReader reader to read from * @param fastchar hint - character likely to terminate the element type * @return StringPool handle for the element type * @exception java.lang.Exception */ public int scanElementType(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception; /** * Scan for an element type at a point in the grammar where parameter * entity references are allowed. If such a reference is encountered, * the replacement text will be scanned, skipping any white space that * may be found, expanding references in this manner until an element * type is scanned, or we fail to find one. * * @param entityReader reader to read from * @param fastchar hint - character likely to terminate the element type * @return StringPool handle for the element type * @exception java.lang.Exception */ public int checkForElementTypeWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception; /** * Scan for an attribute name at a point in the grammar where parameter * entity references are allowed. If such a reference is encountered, * the replacement text will be scanned, skipping any white space that * may be found, expanding references in this manner until an attribute * name is scanned, or we fail to find one. * * @param entityReader reader to read from * @param fastchar hint - character likely to terminate the attribute name * @return StringPool handle for the attribute name * @exception java.lang.Exception */ public int checkForAttributeNameWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception; /** * Scan for a Name at a point in the grammar where parameter entity * references are allowed. If such a reference is encountered, the * replacement text will be scanned, skipping any white space that * may be found, expanding references in this manner until a name * is scanned, or we fail to find one. * * @param entityReader reader to read from * @param fastcheck hint - character likely to terminate the name * @return StringPool handle for the name * @exception java.lang.Exception */ public int checkForNameWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception; /** * Scan for a name token at a point in the grammar where parameter * entity references are allowed. If such a reference is encountered, * the replacement text will be scanned, skipping any white space that * may be found, expanding references in this manner until a name * token is scanned, or we fail to find one. * * @param entityReader reader to read from * @param fastcheck hint - character likely to terminate the name token * @return StringPool handle for the name token * @exception java.lang.Exception */ public int checkForNmtokenWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception; /** * Scan the default value for an attribute * * @param elementType handle to the element type that owns the attribute * @param attrName StringPool handle to the name of the attribute * @param attType the attribute type * @param enumeration StringPool handle to a string list containing enumeration values * @return StringPool handle to the default value * @exception java.lang.Exception */ public int scanDefaultAttValue(int elementType, int attrName, int attType, int enumeration) throws Exception; /** * Supports DOM Level 2 internalSubset additions. * Called when the internal subset is completely scanned. */ public void internalSubset(int internalSubset); } private void reportFatalXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } private void reportFatalXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } private void reportFatalXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } private void reportFatalXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } private void reportFatalXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } private void reportFatalXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } private void abortMarkup(int majorCode, int minorCode) throws Exception { reportFatalXMLError(majorCode, minorCode); skipPastEndOfCurrentMarkup(); } private void abortMarkup(int majorCode, int minorCode, int stringIndex1) throws Exception { reportFatalXMLError(majorCode, minorCode, stringIndex1); skipPastEndOfCurrentMarkup(); } private void abortMarkup(int majorCode, int minorCode, String string1) throws Exception { reportFatalXMLError(majorCode, minorCode, string1); skipPastEndOfCurrentMarkup(); } private void abortMarkup(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { reportFatalXMLError(majorCode, minorCode, stringIndex1, stringIndex2); skipPastEndOfCurrentMarkup(); } private void skipPastEndOfCurrentMarkup() throws Exception { fEntityReader.skipToChar('>'); if (fEntityReader.lookingAtChar('>', true)) decreaseMarkupDepth(); } static private final int SCANNER_STATE_INVALID = -1; static private final int SCANNER_STATE_END_OF_INPUT = 0; static private final int SCANNER_STATE_DOCTYPEDECL = 50; static private final int SCANNER_STATE_MARKUP_DECL = 51; static private final int SCANNER_STATE_TEXTDECL = 53; static private final int SCANNER_STATE_COMMENT = 54; static private final int SCANNER_STATE_PI = 55; static private final int SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE = 56; static private final int SCANNER_STATE_CONTENTSPEC = 57; static private final int SCANNER_STATE_ENTITY_VALUE = 58; static private final int SCANNER_STATE_SYSTEMLITERAL = 59; static private final int SCANNER_STATE_PUBIDLITERAL = 60; private int setScannerState(int scannerState) { int prevState = fScannerState; fScannerState = scannerState; return prevState; } private int getScannerState() { return fScannerState; } private void restoreScannerState(int scannerState) { if (fScannerState != SCANNER_STATE_END_OF_INPUT) fScannerState = scannerState; } /** * Change readers * * @param nextReader the new reader that the scanner will use * @param nextReaderId id of the reader to change to * @exception throws java.lang.Exception */ public void readerChange(XMLEntityHandler.EntityReader nextReader, int nextReaderId) throws Exception { fEntityReader = nextReader; fReaderId = nextReaderId; if (fScannerState == SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE) { fDefaultAttValueOffset = fEntityReader.currentOffset(); fDefaultAttValueMark = fDefaultAttValueOffset; } else if (fScannerState == SCANNER_STATE_ENTITY_VALUE) { fEntityValueMark = fEntityReader.currentOffset(); } } /** * Handle the end of input * * @param entityName the handle in the string pool of the name of the entity which has reached end of input * @param moreToFollow if true, there is still input left to process in other readers * @exception java.lang.Exception */ public void endOfInput(int entityNameIndex, boolean moreToFollow) throws Exception { moreToFollow = fReaderId != fExternalSubsetReader; switch (fScannerState) { case SCANNER_STATE_INVALID: throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 2"+"\n2"); case SCANNER_STATE_END_OF_INPUT: break; case SCANNER_STATE_MARKUP_DECL: if (!moreToFollow && fIncludeSectDepth > 0) { reportFatalXMLError(XMLMessages.MSG_INCLUDESECT_UNTERMINATED, XMLMessages.P62_UNTERMINATED); } break; case SCANNER_STATE_DOCTYPEDECL: throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 2.5"+"\n2.5"); // break; case SCANNER_STATE_TEXTDECL: // REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0); break; case SCANNER_STATE_SYSTEMLITERAL: if (!moreToFollow) { reportFatalXMLError(XMLMessages.MSG_SYSTEMID_UNTERMINATED, XMLMessages.P11_UNTERMINATED); } else { // REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0); } break; case SCANNER_STATE_PUBIDLITERAL: if (!moreToFollow) { reportFatalXMLError(XMLMessages.MSG_PUBLICID_UNTERMINATED, XMLMessages.P12_UNTERMINATED); } else { // REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0); } break; case SCANNER_STATE_COMMENT: if (!moreToFollow && !getReadingExternalEntity()) { reportFatalXMLError(XMLMessages.MSG_COMMENT_UNTERMINATED, XMLMessages.P15_UNTERMINATED); } else { // REVISIT - HACK !!! code changed to pass incorrect OASIS test 'invalid--001' // Uncomment the next line to conform to the spec... //reportFatalXMLError(XMLMessages.MSG_COMMENT_NOT_IN_ONE_ENTITY, // XMLMessages.P78_NOT_WELLFORMED); } break; case SCANNER_STATE_PI: if (!moreToFollow) { reportFatalXMLError(XMLMessages.MSG_PI_UNTERMINATED, XMLMessages.P16_UNTERMINATED); } else { reportFatalXMLError(XMLMessages.MSG_PI_NOT_IN_ONE_ENTITY, XMLMessages.P78_NOT_WELLFORMED); } break; case SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE: if (!moreToFollow) { reportFatalXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_UNTERMINATED, XMLMessages.P10_UNTERMINATED, fDefaultAttValueElementType, fDefaultAttValueAttrName); } else if (fReaderId == fDefaultAttValueReader) { // REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0); } else { fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); } break; case SCANNER_STATE_CONTENTSPEC: break; case SCANNER_STATE_ENTITY_VALUE: if (fReaderId == fEntityValueReader) { // REVISIT reportFatalXMLError(XMLMessages.MSG_ATTVAL0); } else { fEntityReader.append(fLiteralData, fEntityValueMark, fEntityReader.currentOffset() - fEntityValueMark); } break; default: throw new RuntimeException("FWK004 XMLDTDScanner.endOfInput: cannot happen: 3"+"\n3"); } if (!moreToFollow) { setScannerState(SCANNER_STATE_END_OF_INPUT); } } // [66] CharRef ::= '&#' [0-9]+ ';' | '&#x' [0-9a-fA-F]+ ';' private int scanCharRef() throws Exception { int valueOffset = fEntityReader.currentOffset(); boolean hex = fEntityReader.lookingAtChar('x', true); int num = fEntityReader.scanCharRef(hex); if (num < 0) { switch (num) { case XMLEntityHandler.CHARREF_RESULT_SEMICOLON_REQUIRED: reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_CHARREF, XMLMessages.P66_SEMICOLON_REQUIRED); return -1; case XMLEntityHandler.CHARREF_RESULT_INVALID_CHAR: int majorCode = hex ? XMLMessages.MSG_HEXDIGIT_REQUIRED_IN_CHARREF : XMLMessages.MSG_DIGIT_REQUIRED_IN_CHARREF; int minorCode = hex ? XMLMessages.P66_HEXDIGIT_REQUIRED : XMLMessages.P66_DIGIT_REQUIRED; reportFatalXMLError(majorCode, minorCode); return -1; case XMLEntityHandler.CHARREF_RESULT_OUT_OF_RANGE: num = 0x110000; // this will cause the right error to be reported below... break; } } // [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] // any Unicode character, excluding the // | [#xE000-#xFFFD] | [#x10000-#x10FFFF] // surrogate blocks, FFFE, and FFFF. if (num < 0x20) { if (num == 0x09 || num == 0x0A || num == 0x0D) { return num; } } else if (num <= 0xD7FF || (num >= 0xE000 && (num <= 0xFFFD || (num >= 0x10000 && num <= 0x10FFFF)))) { return num; } int valueLength = fEntityReader.currentOffset() - valueOffset; reportFatalXMLError(XMLMessages.MSG_INVALID_CHARREF, XMLMessages.WFC_LEGAL_CHARACTER, fEntityReader.addString(valueOffset, valueLength)); return -1; } // From the standard: // [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->' // Called after scanning past '<!--' private void scanComment() throws Exception { int commentOffset = fEntityReader.currentOffset(); boolean sawDashDash = false; int previousState = setScannerState(SCANNER_STATE_COMMENT); while (fScannerState == SCANNER_STATE_COMMENT) { if (fEntityReader.lookingAtChar('-', false)) { int nextEndOffset = fEntityReader.currentOffset(); int endOffset = 0; fEntityReader.lookingAtChar('-', true); int offset = fEntityReader.currentOffset(); int count = 1; while (fEntityReader.lookingAtChar('-', true)) { count++; endOffset = nextEndOffset; nextEndOffset = offset; offset = fEntityReader.currentOffset(); } if (count > 1) { if (fEntityReader.lookingAtChar('>', true)) { if (!sawDashDash && count > 2) { reportFatalXMLError(XMLMessages.MSG_DASH_DASH_IN_COMMENT, XMLMessages.P15_DASH_DASH); sawDashDash = true; } decreaseMarkupDepth(); fEventHandler.callComment(fEntityReader.addString(commentOffset, endOffset - commentOffset)); restoreScannerState(previousState); return; } else if (!sawDashDash) { reportFatalXMLError(XMLMessages.MSG_DASH_DASH_IN_COMMENT, XMLMessages.P15_DASH_DASH); sawDashDash = true; } } } else { if (!fEntityReader.lookingAtValidChar(true)) { int invChar = fEntityReader.scanInvalidChar(); if (fScannerState != SCANNER_STATE_END_OF_INPUT) { if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_COMMENT, XMLMessages.P15_INVALID_CHARACTER, Integer.toHexString(invChar)); } } } } } restoreScannerState(previousState); } // From the standard: // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) private void scanPI(int piTarget) throws Exception { String piTargetString = fStringPool.toString(piTarget); if (piTargetString.length() == 3 && (piTargetString.charAt(0) == 'X' || piTargetString.charAt(0) == 'x') && (piTargetString.charAt(1) == 'M' || piTargetString.charAt(1) == 'm') && (piTargetString.charAt(2) == 'L' || piTargetString.charAt(2) == 'l')) { abortMarkup(XMLMessages.MSG_RESERVED_PITARGET, XMLMessages.P17_RESERVED_PITARGET); return; } int prevState = setScannerState(SCANNER_STATE_PI); int piDataOffset = -1; int piDataLength = 0; if (!fEntityReader.lookingAtSpace(true)) { if (!fEntityReader.lookingAtChar('?', true) || !fEntityReader.lookingAtChar('>', true)) { if (fScannerState != SCANNER_STATE_END_OF_INPUT) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_IN_PI, XMLMessages.P16_WHITESPACE_REQUIRED); restoreScannerState(prevState); } return; } decreaseMarkupDepth(); restoreScannerState(prevState); } else { fEntityReader.skipPastSpaces(); piDataOffset = fEntityReader.currentOffset(); while (fScannerState == SCANNER_STATE_PI) { while (fEntityReader.lookingAtChar('?', false)) { int offset = fEntityReader.currentOffset(); fEntityReader.lookingAtChar('?', true); if (fEntityReader.lookingAtChar('>', true)) { piDataLength = offset - piDataOffset; decreaseMarkupDepth(); restoreScannerState(prevState); break; } } if (fScannerState != SCANNER_STATE_PI) break; if (!fEntityReader.lookingAtValidChar(true)) { int invChar = fEntityReader.scanInvalidChar(); if (fScannerState != SCANNER_STATE_END_OF_INPUT) { if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_PI, XMLMessages.P16_INVALID_CHARACTER, Integer.toHexString(invChar)); } skipPastEndOfCurrentMarkup(); restoreScannerState(prevState); } return; } } } int piData = piDataLength == 0 ? StringPool.EMPTY_STRING : fEntityReader.addString(piDataOffset, piDataLength); fEventHandler.callProcessingInstruction(piTarget, piData); } // From the standard: // [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? // ('[' (markupdecl | PEReference | S)* ']' S?)? '>' // [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl // | NotationDecl | PI | Comment // Called after scanning '<!DOCTYPE' /** * This routine is called after the &lt;!DOCTYPE portion of a DOCTYPE * line has been called. scanDocTypeDecl goes onto scan the rest of the DOCTYPE * decl. If an internal DTD subset exists, it is scanned. If an external DTD * subset exists, scanDocTypeDecl sets up the state necessary to process it. * * @return true if successful * @exception java.lang.Exception */ public boolean scanDoctypeDecl() throws Exception { increaseMarkupDepth(); fEntityReader = fEntityHandler.getEntityReader(); fReaderId = fEntityHandler.getReaderId(); fDoctypeReader = fReaderId; setScannerState(SCANNER_STATE_DOCTYPEDECL); if (!fEntityReader.lookingAtSpace(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL, XMLMessages.P28_SPACE_REQUIRED); return false; } fEntityReader.skipPastSpaces(); int rootElementType = fEventHandler.scanElementType(fEntityReader, ' '); if (rootElementType == -1) { abortMarkup(XMLMessages.MSG_ROOT_ELEMENT_TYPE_REQUIRED, XMLMessages.P28_ROOT_ELEMENT_TYPE_REQUIRED); return false; } boolean lbrkt; boolean scanExternalSubset = false; int publicId = -1; int systemId = -1; if (fEntityReader.lookingAtSpace(true)) { fEntityReader.skipPastSpaces(); if (!(lbrkt = fEntityReader.lookingAtChar('[', true)) && !fEntityReader.lookingAtChar('>', false)) { if (!scanExternalID(false)) { skipPastEndOfCurrentMarkup(); return false; } scanExternalSubset = true; publicId = fPubidLiteral; systemId = fSystemLiteral; fEntityReader.skipPastSpaces(); lbrkt = fEntityReader.lookingAtChar('[', true); } } else lbrkt = fEntityReader.lookingAtChar('[', true); fEventHandler.doctypeDecl(rootElementType, publicId, systemId); if (lbrkt) { scanDecls(false); fEntityReader.skipPastSpaces(); } if (!fEntityReader.lookingAtChar('>', true)) { if (fScannerState != SCANNER_STATE_END_OF_INPUT) { abortMarkup(XMLMessages.MSG_DOCTYPEDECL_UNTERMINATED, XMLMessages.P28_UNTERMINATED, rootElementType); } return false; } decreaseMarkupDepth(); if (scanExternalSubset) fEventHandler.startReadingFromExternalSubset(publicId, systemId); return true; } // [75] ExternalID ::= 'SYSTEM' S SystemLiteral // | 'PUBLIC' S PubidLiteral S SystemLiteral // [83] PublicID ::= 'PUBLIC' S PubidLiteral private boolean scanExternalID(boolean scanPublicID) throws Exception { fSystemLiteral = -1; fPubidLiteral = -1; int offset = fEntityReader.currentOffset(); if (fEntityReader.skippedString(system_string)) { if (!fEntityReader.lookingAtSpace(true)) { reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_SYSTEMLITERAL_IN_EXTERNALID, XMLMessages.P75_SPACE_REQUIRED); return false; } fEntityReader.skipPastSpaces(); return scanSystemLiteral(); } if (fEntityReader.skippedString(public_string)) { if (!fEntityReader.lookingAtSpace(true)) { reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_PUBIDLITERAL_IN_EXTERNALID, XMLMessages.P75_SPACE_REQUIRED); return false; } fEntityReader.skipPastSpaces(); if (!scanPubidLiteral()) return false; if (scanPublicID) { // [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' if (!fEntityReader.lookingAtSpace(true)) return true; // no S, not an ExternalID fEntityReader.skipPastSpaces(); if (fEntityReader.lookingAtChar('>', false)) // matches end of NotationDecl return true; } else { if (!fEntityReader.lookingAtSpace(true)) { reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_AFTER_PUBIDLITERAL_IN_EXTERNALID, XMLMessages.P75_SPACE_REQUIRED); return false; } fEntityReader.skipPastSpaces(); } return scanSystemLiteral(); } reportFatalXMLError(XMLMessages.MSG_EXTERNALID_REQUIRED, XMLMessages.P75_INVALID); return false; } // [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") // REVISIT - need to look into uri escape mechanism for non-ascii characters. private boolean scanSystemLiteral() throws Exception { boolean single; if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) { reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_SYSTEMID, XMLMessages.P11_QUOTE_REQUIRED); return false; } int prevState = setScannerState(SCANNER_STATE_SYSTEMLITERAL); int offset = fEntityReader.currentOffset(); char qchar = single ? '\'' : '\"'; boolean dataok = true; boolean fragment = false; while (!fEntityReader.lookingAtChar(qchar, false)) { if (fEntityReader.lookingAtChar('#', true)) { fragment = true; } else if (!fEntityReader.lookingAtValidChar(true)) { dataok = false; int invChar = fEntityReader.scanInvalidChar(); if (fScannerState == SCANNER_STATE_END_OF_INPUT) return false; if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_SYSTEMID, XMLMessages.P11_INVALID_CHARACTER, Integer.toHexString(invChar)); } } } if (dataok) { fSystemLiteral = fEntityReader.addString(offset, fEntityReader.currentOffset() - offset); // ndw@nwalsh.com // An fSystemLiteral value from an entity declaration may be // a relative URI. If so, it's important that we make it // absolute with respect to the context of the document that // we are currently reading. If we don't, the XMLParser will // make it absolute with respect to the point of *reference*, // before attempting to read it. That's definitely wrong. String litSystemId = fStringPool.toString(fSystemLiteral); String absSystemId = fEntityHandler.expandSystemId(litSystemId); if (!absSystemId.equals(litSystemId)) { // REVISIT - Is it kosher to touch fStringPool directly? // Is there a better way? fEntityReader doesn't seem to // have an addString method that takes a literal string. fSystemLiteral = fStringPool.addString(absSystemId); } if (fragment) { // NOTE: RECOVERABLE ERROR Object[] args = { fStringPool.toString(fSystemLiteral) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_URI_FRAGMENT_IN_SYSTEMID, XMLMessages.P11_URI_FRAGMENT, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } fEntityReader.lookingAtChar(qchar, true); restoreScannerState(prevState); return dataok; } // [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] private boolean scanPubidLiteral() throws Exception { boolean single; if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) { reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_PUBLICID, XMLMessages.P12_QUOTE_REQUIRED); return false; } char qchar = single ? '\'' : '\"'; int prevState = setScannerState(SCANNER_STATE_PUBIDLITERAL); boolean dataok = true; while (true) { if (fEntityReader.lookingAtChar((char)0x09, true)) { dataok = false; reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL, XMLMessages.P12_INVALID_CHARACTER, "9"); } if (!fEntityReader.lookingAtSpace(true)) break; } int offset = fEntityReader.currentOffset(); int dataOffset = fLiteralData.length(); int toCopy = offset; while (true) { if (fEntityReader.lookingAtChar(qchar, true)) { if (dataok && offset - toCopy > 0) fEntityReader.append(fLiteralData, toCopy, offset - toCopy); break; } if (fEntityReader.lookingAtChar((char)0x09, true)) { dataok = false; reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL, XMLMessages.P12_INVALID_CHARACTER, "9"); continue; } if (fEntityReader.lookingAtSpace(true)) { if (dataok && offset - toCopy > 0) fEntityReader.append(fLiteralData, toCopy, offset - toCopy); while (true) { if (fEntityReader.lookingAtChar((char)0x09, true)) { dataok = false; reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL, XMLMessages.P12_INVALID_CHARACTER, "9"); break; } else if (!fEntityReader.lookingAtSpace(true)) { break; } } if (fEntityReader.lookingAtChar(qchar, true)) break; if (dataok) { fLiteralData.append(' '); offset = fEntityReader.currentOffset(); toCopy = offset; } continue; } if (!fEntityReader.lookingAtValidChar(true)) { int invChar = fEntityReader.scanInvalidChar(); if (fScannerState == SCANNER_STATE_END_OF_INPUT) return false; dataok = false; if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_PUBLICID, XMLMessages.P12_INVALID_CHARACTER, Integer.toHexString(invChar)); } } if (dataok) offset = fEntityReader.currentOffset(); } if (dataok) { int dataLength = fLiteralData.length() - dataOffset; fPubidLiteral = fLiteralData.addString(dataOffset, dataLength); String publicId = fStringPool.toString(fPubidLiteral); int invCharIndex = fEventHandler.validPublicId(publicId); if (invCharIndex >= 0) { reportFatalXMLError(XMLMessages.MSG_PUBIDCHAR_ILLEGAL, XMLMessages.P12_INVALID_CHARACTER, Integer.toHexString(publicId.charAt(invCharIndex))); return false; } } restoreScannerState(prevState); return dataok; } // [??] intSubsetDecl = '[' (markupdecl | PEReference | S)* ']' // [31] extSubsetDecl ::= ( markupdecl | conditionalSect | PEReference | S )* // [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' // [29] markupdecl ::= elementdecl | AttlistDecl | EntityDecl // | NotationDecl | PI | Comment // [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>' // [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>' // [70] EntityDecl ::= GEDecl | PEDecl // [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>' // [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>' // [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' // [15] Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->' // [61] conditionalSect ::= includeSect | ignoreSect // [62] includeSect ::= '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' // [63] ignoreSect ::= '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>' // [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)* // [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*) /** * Scan markup declarations * * @param extSubset true if the scanner is scanning an external subset, false * if it is scanning an internal subset * @exception java.lang.Exception */ public void scanDecls(boolean extSubset) throws Exception { int subsetOffset = fEntityReader.currentOffset(); if (extSubset) fExternalSubsetReader = fReaderId; fIncludeSectDepth = 0; boolean parseTextDecl = extSubset; int prevState = setScannerState(SCANNER_STATE_MARKUP_DECL); while (fScannerState == SCANNER_STATE_MARKUP_DECL) { boolean newParseTextDecl = false; if (!extSubset && fEntityReader.lookingAtChar(']', true)) { fEventHandler.internalSubset( fEntityReader.addString(subsetOffset, (fEntityReader.currentOffset()-subsetOffset)-1)); restoreScannerState(prevState); return; } if (fEntityReader.lookingAtChar('<', true)) { int olddepth = markupDepth(); increaseMarkupDepth(); if (fEntityReader.lookingAtChar('!', true)) { if (fEntityReader.lookingAtChar('-', true)) { if (fEntityReader.lookingAtChar('-', true)) { scanComment(); } else { abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); } } else if (fEntityReader.lookingAtChar('[', true) && getReadingExternalEntity()) { checkForPEReference(false); if (fEntityReader.skippedString(include_string)) { checkForPEReference(false); if (!fEntityReader.lookingAtChar('[', true)) { abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); } else { fIncludeSectDepth++; } } else if (fEntityReader.skippedString(ignore_string)) { checkForPEReference(false); if (!fEntityReader.lookingAtChar('[', true)) { abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); } else scanIgnoreSectContents(); } else { abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); } } else if (fEntityReader.skippedString(element_string)) scanElementDecl(); else if (fEntityReader.skippedString(attlist_string)) scanAttlistDecl(); else if (fEntityReader.skippedString(entity_string)) scanEntityDecl(); else if (fEntityReader.skippedString(notation_string)) scanNotationDecl(); else { abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); } } else if (fEntityReader.lookingAtChar('?', true)) { int piTarget = fEntityReader.scanName(' '); if (piTarget == -1) { abortMarkup(XMLMessages.MSG_PITARGET_REQUIRED, XMLMessages.P16_REQUIRED); } else if ("xml".equals(fStringPool.toString(piTarget))) { if (fEntityReader.lookingAtSpace(true)) { if (parseTextDecl) { // a TextDecl looks like a PI with the target 'xml' scanTextDecl(); } else { abortMarkup(XMLMessages.MSG_TEXTDECL_MUST_BE_FIRST, XMLMessages.P30_TEXTDECL_MUST_BE_FIRST); } } else { // a PI target matching 'xml' abortMarkup(XMLMessages.MSG_RESERVED_PITARGET, XMLMessages.P17_RESERVED_PITARGET); } } else scanPI(piTarget); } else { abortMarkup(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); } } else if (fEntityReader.lookingAtSpace(true)) { fEntityReader.skipPastSpaces(); } else if (fEntityReader.lookingAtChar('%', true)) { // [69] PEReference ::= '%' Name ';' int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength == 0) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_NAME_REQUIRED); } else if (!fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_SEMICOLON_REQUIRED, fEntityReader.addString(nameOffset, nameLength)); } else { int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength); newParseTextDecl = fEntityHandler.startReadingFromEntity(peNameIndex, markupDepth(), XMLEntityHandler.CONTEXT_IN_DTD_AS_MARKUP); } } else if (fIncludeSectDepth > 0 && fEntityReader.lookingAtChar(']', true)) { if (!fEntityReader.lookingAtChar(']', true) || !fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_INCLUDESECT_UNTERMINATED, XMLMessages.P62_UNTERMINATED); } else decreaseMarkupDepth(); fIncludeSectDepth } else { if (!fEntityReader.lookingAtValidChar(false)) { int invChar = fEntityReader.scanInvalidChar(); if (fScannerState == SCANNER_STATE_END_OF_INPUT) break; if (invChar >= 0) { if (!extSubset) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_INTERNAL_SUBSET, XMLMessages.P28_INVALID_CHARACTER, Integer.toHexString(invChar)); } else { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_EXTERNAL_SUBSET, XMLMessages.P30_INVALID_CHARACTER, Integer.toHexString(invChar)); } } } else { reportFatalXMLError(XMLMessages.MSG_MARKUP_NOT_RECOGNIZED_IN_DTD, XMLMessages.P29_NOT_RECOGNIZED); fEntityReader.lookingAtValidChar(true); } } parseTextDecl = newParseTextDecl; } if (extSubset) fEventHandler.stopReadingFromExternalSubset(); else fEventHandler.internalSubset( fEntityReader.addString(subsetOffset, (fEntityReader.currentOffset()-subsetOffset))); } // [64] ignoreSectContents ::= Ignore ('<![' ignoreSectContents ']]>' Ignore)* // [65] Ignore ::= Char* - (Char* ('<![' | ']]>') Char*) private void scanIgnoreSectContents() throws Exception { int initialDepth = ++fIncludeSectDepth; while (true) { if (fEntityReader.lookingAtChar('<', true)) { // These tests are split so that we handle cases like // '<<![' and '<!<![' which we might otherwise miss. if (fEntityReader.lookingAtChar('!', true) && fEntityReader.lookingAtChar('[', true)) fIncludeSectDepth++; } else if (fEntityReader.lookingAtChar(']', true)) { // The same thing goes for ']<![' and '<]]>', etc. if (fEntityReader.lookingAtChar(']', true)) { while (fEntityReader.lookingAtChar(']', true)) { /* empty loop body */ } if (fEntityReader.lookingAtChar('>', true)) { if (fIncludeSectDepth-- == initialDepth) { decreaseMarkupDepth(); return; } } } } else if (!fEntityReader.lookingAtValidChar(true)) { int invChar = fEntityReader.scanInvalidChar(); if (fScannerState == SCANNER_STATE_END_OF_INPUT) return; if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_IGNORESECT, XMLMessages.P65_INVALID_CHARACTER, Integer.toHexString(invChar)); } } } } // From the standard: // [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>' // [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ") // [80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) // [81] EncName ::= [A-Za-z] ([A-Za-z0-9._] | '-')* private void scanTextDecl() throws Exception { final int TEXTDECL_START = 0; final int TEXTDECL_VERSION = 1; final int TEXTDECL_ENCODING = 2; final int TEXTDECL_FINISHED = 3; int prevState = setScannerState(SCANNER_STATE_TEXTDECL); int state = TEXTDECL_START; do { fEntityReader.skipPastSpaces(); int offset = fEntityReader.currentOffset(); if (state == TEXTDECL_START && fEntityReader.skippedString(version_string)) { state = TEXTDECL_VERSION; } else if (fEntityReader.skippedString(encoding_string)) { state = TEXTDECL_ENCODING; } else { abortMarkup(XMLMessages.MSG_ENCODINGDECL_REQUIRED, XMLMessages.P77_ENCODINGDECL_REQUIRED); restoreScannerState(prevState); return; } int length = fEntityReader.currentOffset() - offset; fEntityReader.skipPastSpaces(); if (!fEntityReader.lookingAtChar('=', true)) { int minorCode = state == TEXTDECL_VERSION ? XMLMessages.P24_EQ_REQUIRED : XMLMessages.P80_EQ_REQUIRED; abortMarkup(XMLMessages.MSG_EQ_REQUIRED_IN_TEXTDECL, minorCode, fEntityReader.addString(offset, length)); restoreScannerState(prevState); return; } fEntityReader.skipPastSpaces(); int index = fEntityReader.scanStringLiteral(); switch (index) { case XMLEntityHandler.STRINGLIT_RESULT_QUOTE_REQUIRED: { int minorCode = state == TEXTDECL_VERSION ? XMLMessages.P24_QUOTE_REQUIRED : XMLMessages.P80_QUOTE_REQUIRED; abortMarkup(XMLMessages.MSG_QUOTE_REQUIRED_IN_TEXTDECL, minorCode, fEntityReader.addString(offset, length)); restoreScannerState(prevState); return; } case XMLEntityHandler.STRINGLIT_RESULT_INVALID_CHAR: int invChar = fEntityReader.scanInvalidChar(); if (fScannerState != SCANNER_STATE_END_OF_INPUT) { if (invChar >= 0) { int minorCode = state == TEXTDECL_VERSION ? XMLMessages.P26_INVALID_CHARACTER : XMLMessages.P81_INVALID_CHARACTER; reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_TEXTDECL, minorCode, Integer.toHexString(invChar)); } skipPastEndOfCurrentMarkup(); restoreScannerState(prevState); } return; default: break; } switch (state) { case TEXTDECL_VERSION: // version="..." String version = fStringPool.toString(index); if (!"1.0".equals(version)) { if (!fEventHandler.validVersionNum(version)) { abortMarkup(XMLMessages.MSG_VERSIONINFO_INVALID, XMLMessages.P26_INVALID_VALUE, version); restoreScannerState(prevState); return; } // NOTE: RECOVERABLE ERROR Object[] args = { version }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_VERSION_NOT_SUPPORTED, XMLMessages.P26_NOT_SUPPORTED, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); // REVISIT - hope it is a compatible version... // skipPastEndOfCurrentMarkup(); // return; } if (!fEntityReader.lookingAtSpace(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_IN_TEXTDECL, XMLMessages.P80_WHITESPACE_REQUIRED); restoreScannerState(prevState); return; } break; case TEXTDECL_ENCODING: // encoding = "..." String encoding = fStringPool.toString(index); if (!fEventHandler.validEncName(encoding)) { abortMarkup(XMLMessages.MSG_ENCODINGDECL_INVALID, XMLMessages.P81_INVALID_VALUE, encoding); restoreScannerState(prevState); return; } fEntityReader.skipPastSpaces(); state = TEXTDECL_FINISHED; break; } } while (state != TEXTDECL_FINISHED); if (!fEntityReader.lookingAtChar('?', true) || !fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_TEXTDECL_UNTERMINATED, XMLMessages.P77_UNTERMINATED); restoreScannerState(prevState); return; } decreaseMarkupDepth(); restoreScannerState(prevState); } // [45] elementdecl ::= '<!ELEMENT' S Name S contentspec S? '>' private void scanElementDecl() throws Exception { if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL, XMLMessages.P45_SPACE_REQUIRED); return; } int elementType = fEventHandler.checkForElementTypeWithPEReference(fEntityReader, ' '); if (elementType == -1) { abortMarkup(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL, XMLMessages.P45_ELEMENT_TYPE_REQUIRED); return; } if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL, XMLMessages.P45_SPACE_REQUIRED, elementType); return; } int contentSpecType = -1; int contentSpec = -1; if (fEntityReader.skippedString(empty_string)) { contentSpecType = fEMPTY; } else if (fEntityReader.skippedString(any_string)) { contentSpecType = fANY; } else if (!fEntityReader.lookingAtChar('(', true)) { abortMarkup(XMLMessages.MSG_CONTENTSPEC_REQUIRED_IN_ELEMENTDECL, XMLMessages.P45_CONTENTSPEC_REQUIRED, elementType); return; } else { int contentSpecReader = fReaderId; int contentSpecReaderDepth = fEntityHandler.getReaderDepth(); int prevState = setScannerState(SCANNER_STATE_CONTENTSPEC); int oldDepth = parenDepth(); fEntityHandler.setReaderDepth(oldDepth); increaseParenDepth(); checkForPEReference(false); boolean skippedPCDATA = fEntityReader.skippedString(pcdata_string); if (skippedPCDATA) { contentSpecType = fMIXED; contentSpec = scanMixed(elementType); } else { contentSpecType = fCHILDREN; contentSpec = scanChildren(elementType); } boolean success = contentSpec != -1; restoreScannerState(prevState); fEntityHandler.setReaderDepth(contentSpecReaderDepth); if (!success) { setParenDepth(oldDepth); skipPastEndOfCurrentMarkup(); return; } else { if (parenDepth() != oldDepth) // REVISIT - should not be needed // System.out.println("nesting depth mismatch"); ; } } checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_ELEMENTDECL_UNTERMINATED, XMLMessages.P45_UNTERMINATED, elementType); return; } decreaseMarkupDepth(); int elementIndex = fEventHandler.addElementDecl(elementType, contentSpecType, contentSpec); } // [51] Mixed ::= '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')' // Called after scanning past '(' S? '#PCDATA' private int scanMixed(int elementType) throws Exception { int valueIndex = -1; // -1 is special value for #PCDATA int prevNodeIndex = -1; boolean starRequired = false; while (true) { int nodeIndex = fEventHandler.addUniqueLeafNode(valueIndex); checkForPEReference(false); if (!fEntityReader.lookingAtChar('|', true)) { if (!fEntityReader.lookingAtChar(')', true)) { reportFatalXMLError(XMLMessages.MSG_CLOSE_PAREN_REQUIRED_IN_MIXED, XMLMessages.P51_CLOSE_PAREN_REQUIRED, elementType); return -1; } decreaseParenDepth(); if (nodeIndex == -1) { nodeIndex = prevNodeIndex; } else if (prevNodeIndex != -1) { nodeIndex = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_CHOICE, prevNodeIndex, nodeIndex); } if (fEntityReader.lookingAtChar('*', true)) { nodeIndex = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE, nodeIndex); } else if (starRequired) { reportFatalXMLError(XMLMessages.MSG_MIXED_CONTENT_UNTERMINATED, XMLMessages.P51_UNTERMINATED, fStringPool.toString(elementType), fEventHandler.getContentSpecNodeAsString(nodeIndex)); return -1; } return nodeIndex; } if (nodeIndex != -1) { if (prevNodeIndex != -1) { nodeIndex = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_CHOICE, prevNodeIndex, nodeIndex); } prevNodeIndex = nodeIndex; } starRequired = true; checkForPEReference(false); valueIndex = fEventHandler.checkForElementTypeWithPEReference(fEntityReader, ')'); if (valueIndex == -1) { reportFatalXMLError(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_MIXED_CONTENT, XMLMessages.P51_ELEMENT_TYPE_REQUIRED, elementType); return -1; } } } // [47] children ::= (choice | seq) ('?' | '*' | '+')? // [49] choice ::= '(' S? cp ( S? '|' S? cp )* S? ')' // [50] seq ::= '(' S? cp ( S? ',' S? cp )* S? ')' // [48] cp ::= (Name | choice | seq) ('?' | '*' | '+')? private int scanChildren(int elementType) throws Exception { int depth = 1; initializeContentModelStack(depth); while (true) { if (fEntityReader.lookingAtChar('(', true)) { increaseParenDepth(); checkForPEReference(false); depth++; initializeContentModelStack(depth); continue; } int valueIndex = fEventHandler.checkForElementTypeWithPEReference(fEntityReader, ')'); if (valueIndex == -1) { reportFatalXMLError(XMLMessages.MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN, XMLMessages.P47_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED, elementType); return -1; } nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF, valueIndex); if (fEntityReader.lookingAtChar('?', true)) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE, nodeIndexStack[depth]); } else if (fEntityReader.lookingAtChar('*', true)) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE, nodeIndexStack[depth]); } else if (fEntityReader.lookingAtChar('+', true)) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE, nodeIndexStack[depth]); } while (true) { checkForPEReference(false); if (opStack[depth] != XMLContentSpecNode.CONTENTSPECNODE_SEQ && fEntityReader.lookingAtChar('|', true)) { if (prevNodeIndexStack[depth] != -1) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(opStack[depth], prevNodeIndexStack[depth], nodeIndexStack[depth]); } prevNodeIndexStack[depth] = nodeIndexStack[depth]; opStack[depth] = XMLContentSpecNode.CONTENTSPECNODE_CHOICE; break; } else if (opStack[depth] != XMLContentSpecNode.CONTENTSPECNODE_CHOICE && fEntityReader.lookingAtChar(',', true)) { if (prevNodeIndexStack[depth] != -1) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(opStack[depth], prevNodeIndexStack[depth], nodeIndexStack[depth]); } prevNodeIndexStack[depth] = nodeIndexStack[depth]; opStack[depth] = XMLContentSpecNode.CONTENTSPECNODE_SEQ; break; } else { if (!fEntityReader.lookingAtChar(')', true)) { reportFatalXMLError(XMLMessages.MSG_CLOSE_PAREN_REQUIRED_IN_CHILDREN, XMLMessages.P47_CLOSE_PAREN_REQUIRED, elementType); } decreaseParenDepth(); if (prevNodeIndexStack[depth] != -1) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(opStack[depth], prevNodeIndexStack[depth], nodeIndexStack[depth]); } int nodeIndex = nodeIndexStack[depth nodeIndexStack[depth] = nodeIndex; if (fEntityReader.lookingAtChar('?', true)) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE, nodeIndexStack[depth]); } else if (fEntityReader.lookingAtChar('*', true)) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE, nodeIndexStack[depth]); } else if (fEntityReader.lookingAtChar('+', true)) { nodeIndexStack[depth] = fEventHandler.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE, nodeIndexStack[depth]); } if (depth == 0) { return nodeIndexStack[0]; } } } checkForPEReference(false); } } // [52] AttlistDecl ::= '<!ATTLIST' S Name AttDef* S? '>' // [53] AttDef ::= S Name S AttType S DefaultDecl // [60] DefaultDecl ::= '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue) private void scanAttlistDecl() throws Exception { if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ATTLISTDECL, XMLMessages.P52_SPACE_REQUIRED); return; } int elementTypeIndex = fEventHandler.checkForElementTypeWithPEReference(fEntityReader, ' '); if (elementTypeIndex == -1) { abortMarkup(XMLMessages.MSG_ELEMENT_TYPE_REQUIRED_IN_ATTLISTDECL, XMLMessages.P52_ELEMENT_TYPE_REQUIRED); return; } int elementIndex = fEventHandler.addElementDecl(elementTypeIndex); while (true) { boolean sawSpace = checkForPEReference(true); if (fEntityReader.lookingAtChar('>', true)) { decreaseMarkupDepth(); return; } // REVISIT - review this code... if (!sawSpace) { if (fEntityReader.lookingAtSpace(true)) { fEntityReader.skipPastSpaces(); } else reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTRIBUTE_NAME_IN_ATTDEF, XMLMessages.P53_SPACE_REQUIRED); } else { if (fEntityReader.lookingAtSpace(true)) { fEntityReader.skipPastSpaces(); } } int attDefName = fEventHandler.checkForAttributeNameWithPEReference(fEntityReader, ' '); if (attDefName == -1) { abortMarkup(XMLMessages.MSG_ATTRIBUTE_NAME_REQUIRED_IN_ATTDEF, XMLMessages.P53_NAME_REQUIRED, elementTypeIndex); return; } if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ATTTYPE_IN_ATTDEF, XMLMessages.P53_SPACE_REQUIRED); return; } int attDefType = -1; int attDefEnumeration = -1; if (fEntityReader.skippedString(cdata_string)) { attDefType = fCDATA; } else if (fEntityReader.skippedString(id_string)) { if (!fEntityReader.skippedString(ref_string)) { attDefType = fID; } else if (!fEntityReader.lookingAtChar('S', true)) { attDefType = fIDREF; } else { attDefType = fIDREFS; } } else if (fEntityReader.skippedString(entit_string)) { if (fEntityReader.lookingAtChar('Y', true)) { attDefType = fENTITY; } else if (fEntityReader.skippedString(ies_string)) { attDefType = fENTITIES; } else { abortMarkup(XMLMessages.MSG_ATTTYPE_REQUIRED_IN_ATTDEF, XMLMessages.P53_ATTTYPE_REQUIRED, elementTypeIndex, attDefName); return; } } else if (fEntityReader.skippedString(nmtoken_string)) { if (fEntityReader.lookingAtChar('S', true)) { attDefType = fNMTOKENS; } else { attDefType = fNMTOKEN; } } else if (fEntityReader.skippedString(notation_string)) { if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_NOTATION_IN_NOTATIONTYPE, XMLMessages.P58_SPACE_REQUIRED, elementTypeIndex, attDefName); return; } if (!fEntityReader.lookingAtChar('(', true)) { abortMarkup(XMLMessages.MSG_OPEN_PAREN_REQUIRED_IN_NOTATIONTYPE, XMLMessages.P58_OPEN_PAREN_REQUIRED, elementTypeIndex, attDefName); return; } increaseParenDepth(); attDefType = fNOTATION; attDefEnumeration = scanEnumeration(elementTypeIndex, attDefName, true); if (attDefEnumeration == -1) { skipPastEndOfCurrentMarkup(); return; } } else if (fEntityReader.lookingAtChar('(', true)) { increaseParenDepth(); attDefType = fENUMERATION; attDefEnumeration = scanEnumeration(elementTypeIndex, attDefName, false); if (attDefEnumeration == -1) { skipPastEndOfCurrentMarkup(); return; } } else { abortMarkup(XMLMessages.MSG_ATTTYPE_REQUIRED_IN_ATTDEF, XMLMessages.P53_ATTTYPE_REQUIRED, elementTypeIndex, attDefName); return; } if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_DEFAULTDECL_IN_ATTDEF, XMLMessages.P53_SPACE_REQUIRED, elementTypeIndex, attDefName); return; } int attDefDefaultType = -1; int attDefDefaultValue = -1; if (fEntityReader.skippedString(required_string)) { attDefDefaultType = fREQUIRED; } else if (fEntityReader.skippedString(implied_string)) { attDefDefaultType = fIMPLIED; } else { if (fEntityReader.skippedString(fixed_string)) { if (!fEntityReader.lookingAtSpace(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_FIXED_IN_DEFAULTDECL, XMLMessages.P60_SPACE_REQUIRED, elementTypeIndex, attDefName); return; } fEntityReader.skipPastSpaces(); attDefDefaultType = fFIXED; } else attDefDefaultType = fDEFAULT; attDefDefaultValue = fEventHandler.scanDefaultAttValue(elementTypeIndex, attDefName, attDefType, attDefEnumeration); if (attDefDefaultValue == -1) { skipPastEndOfCurrentMarkup(); return; } } if (attDefName == fXMLSpace) { boolean ok = false; if (attDefType == fENUMERATION) { int index = attDefEnumeration; if (index != -1) { ok = (fStringPool.stringListLength(index) == 1 && (fStringPool.stringInList(index, fDefault) || fStringPool.stringInList(index, fPreserve))) || (fStringPool.stringListLength(index) == 2 && fStringPool.stringInList(index, fDefault) && fStringPool.stringInList(index, fPreserve)); } } if (!ok) { reportFatalXMLError(XMLMessages.MSG_XML_SPACE_DECLARATION_ILLEGAL, XMLMessages.S2_10_DECLARATION_ILLEGAL, elementTypeIndex); } } int attDefIndex = fEventHandler.addAttDef(elementIndex, attDefName, attDefType, attDefEnumeration, attDefDefaultType, attDefDefaultValue); } } // [58] NotationType ::= 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' // [59] Enumeration ::= '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' private int scanEnumeration(int elementType, int attrName, boolean isNotationType) throws Exception { int enumIndex = fEventHandler.startEnumeration(); while (true) { checkForPEReference(false); int nameIndex = isNotationType ? fEventHandler.checkForNameWithPEReference(fEntityReader, ')') : fEventHandler.checkForNmtokenWithPEReference(fEntityReader, ')'); if (nameIndex == -1) { if (isNotationType) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_NOTATIONTYPE, XMLMessages.P58_NAME_REQUIRED, elementType, attrName); } else { reportFatalXMLError(XMLMessages.MSG_NMTOKEN_REQUIRED_IN_ENUMERATION, XMLMessages.P59_NMTOKEN_REQUIRED, elementType, attrName); } fEventHandler.endEnumeration(enumIndex); return -1; } fEventHandler.addNameToEnumeration(enumIndex, elementType, attrName, nameIndex, isNotationType); checkForPEReference(false); if (!fEntityReader.lookingAtChar('|', true)) { fEventHandler.endEnumeration(enumIndex); if (!fEntityReader.lookingAtChar(')', true)) { if (isNotationType) { reportFatalXMLError(XMLMessages.MSG_NOTATIONTYPE_UNTERMINATED, XMLMessages.P58_UNTERMINATED, elementType, attrName); } else { reportFatalXMLError(XMLMessages.MSG_ENUMERATION_UNTERMINATED, XMLMessages.P59_UNTERMINATED, elementType, attrName); } return -1; } decreaseParenDepth(); return enumIndex; } } } // [10] AttValue ::= '"' ([^<&"] | Reference)* '"' // | "'" ([^<&'] | Reference)* "'" /** * Scan the default value in an attribute declaration * * @param elementType handle to the element that owns the attribute * @param attrName handle in the string pool for the attribute name * @return handle in the string pool for the default attribute value * @exception java.lang.Exception */ public int scanDefaultAttValue(int elementType, int attrName) throws Exception { boolean single; if (!(single = fEntityReader.lookingAtChar('\'', true)) && !fEntityReader.lookingAtChar('\"', true)) { reportFatalXMLError(XMLMessages.MSG_QUOTE_REQUIRED_IN_ATTVALUE, XMLMessages.P10_QUOTE_REQUIRED, elementType, attrName); return -1; } int previousState = setScannerState(SCANNER_STATE_DEFAULT_ATTRIBUTE_VALUE); char qchar = single ? '\'' : '\"'; fDefaultAttValueReader = fReaderId; fDefaultAttValueElementType = elementType; fDefaultAttValueAttrName = attrName; boolean setMark = true; int dataOffset = fLiteralData.length(); while (true) { fDefaultAttValueOffset = fEntityReader.currentOffset(); if (setMark) { fDefaultAttValueMark = fDefaultAttValueOffset; setMark = false; } if (fEntityReader.lookingAtChar(qchar, true)) { if (fReaderId == fDefaultAttValueReader) break; continue; } if (fEntityReader.lookingAtChar(' ', true)) { continue; } boolean skippedCR; if ((skippedCR = fEntityReader.lookingAtChar((char)0x0D, true)) || fEntityReader.lookingAtSpace(true)) { if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); setMark = true; fLiteralData.append(' '); if (skippedCR) fEntityReader.lookingAtChar((char)0x0A, true); continue; } if (fEntityReader.lookingAtChar('&', true)) { if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); setMark = true; // Check for character reference first. if (fEntityReader.lookingAtChar('#', true)) { int ch = scanCharRef(); if (ch != -1) { if (ch < 0x10000) fLiteralData.append((char)ch); else { fLiteralData.append((char)(((ch-0x00010000)>>10)+0xd800)); fLiteralData.append((char)(((ch-0x00010000)&0x3ff)+0xdc00)); } } } else { // Entity reference int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength == 0) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_REFERENCE, XMLMessages.P68_NAME_REQUIRED); } else if (!fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_REFERENCE, XMLMessages.P68_SEMICOLON_REQUIRED, fEntityReader.addString(nameOffset, nameLength)); } else { int entityNameIndex = fEntityReader.addSymbol(nameOffset, nameLength); fEntityHandler.startReadingFromEntity(entityNameIndex, markupDepth(), XMLEntityHandler.CONTEXT_IN_DEFAULTATTVALUE); } } continue; } if (fEntityReader.lookingAtChar('<', true)) { if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); setMark = true; reportFatalXMLError(XMLMessages.MSG_LESSTHAN_IN_ATTVALUE, XMLMessages.WFC_NO_LESSTHAN_IN_ATTVALUE, elementType, attrName); continue; } // REVISIT - HACK !!! code added to pass incorrect OASIS test 'valid-sa-094' // Remove this next section to conform to the spec... if (!getReadingExternalEntity() && fEntityReader.lookingAtChar('%', true)) { int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength != 0 && fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_PEREFERENCE_WITHIN_MARKUP, XMLMessages.WFC_PES_IN_INTERNAL_SUBSET, fEntityReader.addString(nameOffset, nameLength)); } } // END HACK !!! if (!fEntityReader.lookingAtValidChar(true)) { if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); setMark = true; int invChar = fEntityReader.scanInvalidChar(); if (fScannerState == SCANNER_STATE_END_OF_INPUT) return -1; if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_ATTVALUE, XMLMessages.P10_INVALID_CHARACTER, fStringPool.toString(elementType), fStringPool.toString(attrName), Integer.toHexString(invChar)); } continue; } } restoreScannerState(previousState); int dataLength = fLiteralData.length() - dataOffset; if (dataLength == 0) { return fEntityReader.addString(fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); } if (fDefaultAttValueOffset - fDefaultAttValueMark > 0) { fEntityReader.append(fLiteralData, fDefaultAttValueMark, fDefaultAttValueOffset - fDefaultAttValueMark); dataLength = fLiteralData.length() - dataOffset; } return fLiteralData.addString(dataOffset, dataLength); } // [82] NotationDecl ::= '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' private void scanNotationDecl() throws Exception { if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_NOTATIONDECL, XMLMessages.P82_SPACE_REQUIRED); return; } int notationName = fEventHandler.checkForNameWithPEReference(fEntityReader, ' '); if (notationName == -1) { abortMarkup(XMLMessages.MSG_NOTATION_NAME_REQUIRED_IN_NOTATIONDECL, XMLMessages.P82_NAME_REQUIRED); return; } if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_NOTATION_NAME_IN_NOTATIONDECL, XMLMessages.P82_SPACE_REQUIRED, notationName); return; } if (!scanExternalID(true)) { skipPastEndOfCurrentMarkup(); return; } checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_NOTATIONDECL_UNTERMINATED, XMLMessages.P82_UNTERMINATED, notationName); return; } decreaseMarkupDepth(); int notationIndex = fEventHandler.addNotationDecl(notationName, fPubidLiteral, fSystemLiteral); } // [70] EntityDecl ::= GEDecl | PEDecl // [71] GEDecl ::= '<!ENTITY' S Name S EntityDef S? '>' // [72] PEDecl ::= '<!ENTITY' S '%' S Name S PEDef S? '>' // [73] EntityDef ::= EntityValue | (ExternalID NDataDecl?) // [74] PEDef ::= EntityValue | ExternalID // [75] ExternalID ::= 'SYSTEM' S SystemLiteral // | 'PUBLIC' S PubidLiteral S SystemLiteral // [76] NDataDecl ::= S 'NDATA' S Name // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' // | "'" ([^%&'] | PEReference | Reference)* "'" // Called after scanning 'ENTITY' private void scanEntityDecl() throws Exception { boolean isPEDecl = false; boolean sawPERef = false; if (fEntityReader.lookingAtSpace(true)) { fEntityReader.skipPastSpaces(); if (!fEntityReader.lookingAtChar('%', true)) { isPEDecl = false; // <!ENTITY x "x"> } else if (fEntityReader.lookingAtSpace(true)) { checkForPEReference(false); // <!ENTITY % x "x"> isPEDecl = true; } else if (!getReadingExternalEntity()) { reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_PEDECL, XMLMessages.P72_SPACE); isPEDecl = true; } else if (fEntityReader.lookingAtChar('%', false)) { checkForPEReference(false); isPEDecl = true; } else { sawPERef = true; } } else if (!getReadingExternalEntity() || !fEntityReader.lookingAtChar('%', true)) { // <!ENTITY[^ ]...> or <!ENTITY[^ %]...> reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_ENTITYDECL, XMLMessages.P70_SPACE); isPEDecl = false; } else if (fEntityReader.lookingAtSpace(false)) { // <!ENTITY% ...> reportFatalXMLError(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_PERCENT_IN_PEDECL, XMLMessages.P72_SPACE); isPEDecl = false; } else { sawPERef = true; } if (sawPERef) { while (true) { int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength == 0) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_NAME_REQUIRED); } else if (!fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_SEMICOLON_REQUIRED, fEntityReader.addString(nameOffset, nameLength)); } else { int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength); int readerDepth = (fScannerState == SCANNER_STATE_CONTENTSPEC) ? parenDepth() : markupDepth(); fEntityHandler.startReadingFromEntity(peNameIndex, readerDepth, XMLEntityHandler.CONTEXT_IN_DTD_WITHIN_MARKUP); } fEntityReader.skipPastSpaces(); if (!fEntityReader.lookingAtChar('%', true)) break; if (!isPEDecl) { if (fEntityReader.lookingAtSpace(true)) { checkForPEReference(false); isPEDecl = true; break; } isPEDecl = fEntityReader.lookingAtChar('%', true); } } } int entityName = fEventHandler.checkForNameWithPEReference(fEntityReader, ' '); if (entityName == -1) { abortMarkup(XMLMessages.MSG_ENTITY_NAME_REQUIRED_IN_ENTITYDECL, XMLMessages.P70_REQUIRED_NAME); return; } if (!fEntityHandler.startEntityDecl(isPEDecl, entityName)) { skipPastEndOfCurrentMarkup(); return; } if (!checkForPEReference(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_AFTER_ENTITY_NAME_IN_ENTITYDECL, XMLMessages.P70_REQUIRED_SPACE, entityName); fEntityHandler.endEntityDecl(); return; } if (isPEDecl) { boolean single; if ((single = fEntityReader.lookingAtChar('\'', true)) || fEntityReader.lookingAtChar('\"', true)) { int location = fEventHandler.saveCurrentLocation(); int value = scanEntityValue(single); if (value == -1) { skipPastEndOfCurrentMarkup(); fEntityHandler.endEntityDecl(); return; } checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED, XMLMessages.P72_UNTERMINATED, entityName); fEntityHandler.endEntityDecl(); return; } decreaseMarkupDepth(); fEntityHandler.endEntityDecl(); int entityIndex = fEventHandler.addInternalPEDecl(entityName, value, location); } else { if (!scanExternalID(false)) { skipPastEndOfCurrentMarkup(); fEntityHandler.endEntityDecl(); return; } checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED, XMLMessages.P72_UNTERMINATED, entityName); fEntityHandler.endEntityDecl(); return; } decreaseMarkupDepth(); fEntityHandler.endEntityDecl(); int entityIndex = fEventHandler.addExternalPEDecl(entityName, fPubidLiteral, fSystemLiteral); } } else { boolean single; if ((single = fEntityReader.lookingAtChar('\'', true)) || fEntityReader.lookingAtChar('\"', true)) { int location = fEventHandler.saveCurrentLocation(); int value = scanEntityValue(single); if (value == -1) { skipPastEndOfCurrentMarkup(); fEntityHandler.endEntityDecl(); return; } checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED, XMLMessages.P71_UNTERMINATED, entityName); fEntityHandler.endEntityDecl(); return; } decreaseMarkupDepth(); fEntityHandler.endEntityDecl(); int entityIndex = fEventHandler.addInternalEntityDecl(entityName, value, location); } else { if (!scanExternalID(false)) { skipPastEndOfCurrentMarkup(); fEntityHandler.endEntityDecl(); return; } boolean unparsed = false; if (fEntityReader.lookingAtSpace(true)) { fEntityReader.skipPastSpaces(); unparsed = fEntityReader.skippedString(ndata_string); } if (!unparsed) { checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED, XMLMessages.P72_UNTERMINATED, entityName); fEntityHandler.endEntityDecl(); return; } decreaseMarkupDepth(); fEntityHandler.endEntityDecl(); int entityIndex = fEventHandler.addExternalEntityDecl(entityName, fPubidLiteral, fSystemLiteral); } else { if (!fEntityReader.lookingAtSpace(true)) { abortMarkup(XMLMessages.MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_UNPARSED_ENTITYDECL, XMLMessages.P76_SPACE_REQUIRED, entityName); fEntityHandler.endEntityDecl(); return; } fEntityReader.skipPastSpaces(); int ndataOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName('>'); int ndataLength = fEntityReader.currentOffset() - ndataOffset; if (ndataLength == 0) { abortMarkup(XMLMessages.MSG_NOTATION_NAME_REQUIRED_FOR_UNPARSED_ENTITYDECL, XMLMessages.P76_REQUIRED, entityName); fEntityHandler.endEntityDecl(); return; } int notationName = fEntityReader.addSymbol(ndataOffset, ndataLength); checkForPEReference(false); if (!fEntityReader.lookingAtChar('>', true)) { abortMarkup(XMLMessages.MSG_ENTITYDECL_UNTERMINATED, XMLMessages.P72_UNTERMINATED, entityName); fEntityHandler.endEntityDecl(); return; } decreaseMarkupDepth(); fEntityHandler.endEntityDecl(); int entityIndex = fEventHandler.addUnparsedEntityDecl(entityName, fPubidLiteral, fSystemLiteral, notationName); } } } } // [9] EntityValue ::= '"' ([^%&"] | PEReference | Reference)* '"' // | "'" ([^%&'] | PEReference | Reference)* "'" private int scanEntityValue(boolean single) throws Exception { char qchar = single ? '\'' : '\"'; fEntityValueMark = fEntityReader.currentOffset(); int entityValue = fEntityReader.scanEntityValue(qchar, true); if (entityValue < 0) entityValue = scanComplexEntityValue(qchar, entityValue); return entityValue; } private int scanComplexEntityValue(char qchar, int result) throws Exception { int previousState = setScannerState(SCANNER_STATE_ENTITY_VALUE); fEntityValueReader = fReaderId; int dataOffset = fLiteralData.length(); while (true) { switch (result) { case XMLEntityHandler.ENTITYVALUE_RESULT_FINISHED: { int offset = fEntityReader.currentOffset(); fEntityReader.lookingAtChar(qchar, true); restoreScannerState(previousState); int dataLength = fLiteralData.length() - dataOffset; if (dataLength == 0) { return fEntityReader.addString(fEntityValueMark, offset - fEntityValueMark); } if (offset - fEntityValueMark > 0) { fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark); dataLength = fLiteralData.length() - dataOffset; } return fLiteralData.addString(dataOffset, dataLength); } case XMLEntityHandler.ENTITYVALUE_RESULT_REFERENCE: { int offset = fEntityReader.currentOffset(); if (offset - fEntityValueMark > 0) fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark); fEntityReader.lookingAtChar('&', true); // Check for character reference first. if (fEntityReader.lookingAtChar('#', true)) { int ch = scanCharRef(); if (ch != -1) { if (ch < 0x10000) fLiteralData.append((char)ch); else { fLiteralData.append((char)(((ch-0x00010000)>>10)+0xd800)); fLiteralData.append((char)(((ch-0x00010000)&0x3ff)+0xdc00)); } } fEntityValueMark = fEntityReader.currentOffset(); } else { // Entity reference int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength == 0) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_REFERENCE, XMLMessages.P68_NAME_REQUIRED); fEntityValueMark = fEntityReader.currentOffset(); } else if (!fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_REFERENCE, XMLMessages.P68_SEMICOLON_REQUIRED, fEntityReader.addString(nameOffset, nameLength)); fEntityValueMark = fEntityReader.currentOffset(); } else { // 4.4.7 Bypassed // When a general entity reference appears in the EntityValue in an // entity declaration, it is bypassed and left as is. fEntityValueMark = offset; } } break; } case XMLEntityHandler.ENTITYVALUE_RESULT_PEREF: { int offset = fEntityReader.currentOffset(); if (offset - fEntityValueMark > 0) fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark); fEntityReader.lookingAtChar('%', true); int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength == 0) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_NAME_REQUIRED); } else if (!fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_SEMICOLON_REQUIRED, fEntityReader.addString(nameOffset, nameLength)); } else if (!getReadingExternalEntity()) { reportFatalXMLError(XMLMessages.MSG_PEREFERENCE_WITHIN_MARKUP, XMLMessages.WFC_PES_IN_INTERNAL_SUBSET, fEntityReader.addString(nameOffset, nameLength)); } else { int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength); fEntityHandler.startReadingFromEntity(peNameIndex, markupDepth(), XMLEntityHandler.CONTEXT_IN_ENTITYVALUE); } fEntityValueMark = fEntityReader.currentOffset(); break; } case XMLEntityHandler.ENTITYVALUE_RESULT_INVALID_CHAR: { int offset = fEntityReader.currentOffset(); if (offset - fEntityValueMark > 0) fEntityReader.append(fLiteralData, fEntityValueMark, offset - fEntityValueMark); int invChar = fEntityReader.scanInvalidChar(); if (fScannerState == SCANNER_STATE_END_OF_INPUT) return -1; if (invChar >= 0) { reportFatalXMLError(XMLMessages.MSG_INVALID_CHAR_IN_ENTITYVALUE, XMLMessages.P9_INVALID_CHARACTER, Integer.toHexString(invChar)); } fEntityValueMark = fEntityReader.currentOffset(); break; } case XMLEntityHandler.ENTITYVALUE_RESULT_END_OF_INPUT: // all the work is done by the previous reader, just invoke the next one now. break; default: break; } result = fEntityReader.scanEntityValue(fReaderId == fEntityValueReader ? qchar : -1, false); } } private boolean checkForPEReference(boolean spaceRequired) throws Exception { boolean sawSpace = true; if (spaceRequired) sawSpace = fEntityReader.lookingAtSpace(true); fEntityReader.skipPastSpaces(); if (!getReadingExternalEntity()) return sawSpace; if (!fEntityReader.lookingAtChar('%', true)) return sawSpace; while (true) { int nameOffset = fEntityReader.currentOffset(); fEntityReader.skipPastName(';'); int nameLength = fEntityReader.currentOffset() - nameOffset; if (nameLength == 0) { reportFatalXMLError(XMLMessages.MSG_NAME_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_NAME_REQUIRED); } else if (!fEntityReader.lookingAtChar(';', true)) { reportFatalXMLError(XMLMessages.MSG_SEMICOLON_REQUIRED_IN_PEREFERENCE, XMLMessages.P69_SEMICOLON_REQUIRED, fEntityReader.addString(nameOffset, nameLength)); } else { int peNameIndex = fEntityReader.addSymbol(nameOffset, nameLength); int readerDepth = (fScannerState == SCANNER_STATE_CONTENTSPEC) ? parenDepth() : markupDepth(); fEntityHandler.startReadingFromEntity(peNameIndex, readerDepth, XMLEntityHandler.CONTEXT_IN_DTD_WITHIN_MARKUP); } fEntityReader.skipPastSpaces(); if (!fEntityReader.lookingAtChar('%', true)) return true; } } // content model stack private void initializeContentModelStack(int depth) { if (opStack == null) { opStack = new int[8]; nodeIndexStack = new int[8]; prevNodeIndexStack = new int[8]; } else if (depth == opStack.length) { int[] newStack = new int[depth * 2]; System.arraycopy(opStack, 0, newStack, 0, depth); opStack = newStack; newStack = new int[depth * 2]; System.arraycopy(nodeIndexStack, 0, newStack, 0, depth); nodeIndexStack = newStack; newStack = new int[depth * 2]; System.arraycopy(prevNodeIndexStack, 0, newStack, 0, depth); prevNodeIndexStack = newStack; } opStack[depth] = -1; nodeIndexStack[depth] = -1; prevNodeIndexStack[depth] = -1; } }
package org.modmine.web; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import javax.servlet.ServletContext; import org.apache.log4j.Logger; import org.intermine.model.bio.DatabaseRecord; import org.intermine.model.bio.Experiment; import org.intermine.model.bio.LocatedSequenceFeature; import org.intermine.model.bio.Location; import org.intermine.model.bio.Project; import org.intermine.model.bio.ResultFile; import org.intermine.model.bio.Submission; import org.intermine.model.bio.ExpressionLevel; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryCollectionReference; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryFunction; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.util.PropertiesUtil; import org.intermine.util.TypeUtil; /** * Read modENCODE metadata into objects that simplify display code, cache results. * @author Richard Smith * */ public class MetadataCache { private static final Logger LOG = Logger.getLogger(MetadataCache.class); private static final String NO_FEAT_DESCR_LOG = "Unable to find /WEB-INF/featureTypeDescr.properties, no feature descriptions in webapp!"; private static final String GBROWSE_BASE_URL = getGBrowsePrefix(); private static final String GBROWSE_URL_END = "/?show_tracks=1"; private static final String GBROWSE_ST_URL_END = "/?action=scan"; private static final String GBROWSE_DEFAULT_URL = "http://modencode.oicr.on.ca/cgi-bin/gb2/gbrowse/"; /** * A GBrowse track, identified by * the organism, the track name, and eventually the subtrack name. * * subtracks are linked to modENCODE submissions * */ public static class GBrowseTrack { private String organism; // {fly,worm} private String track; // e.g. Snyder_PHA4_GFP_COMB private String subTrack; // e.g. PHA4_L2_GFP /** * Instantiates a GBrowseTrack only to track level. * * @param organismName e.g. fly, worm * @param trackName e.g. Snyder_PHA4_GFP_COMB */ public GBrowseTrack(String organismName, String trackName) { this.organism = organismName; this.track = trackName; } /** * Instantiates a GBrowse track fully. * * @param organism e.g. fly, worm * @param track e.g. Snyder_PHA4_GFP_COMB * @param subTrack e.g. PHA4_L2_GFP */ public GBrowseTrack(String organism, String track, String subTrack) { this.organism = organism; this.track = track; this.subTrack = subTrack; } /** * @return the organism */ public String getOrganism() { return organism; } /** * @return the track name */ public String getTrack() { return track; } /** * @return the subTrack */ public String getSubTrack() { return subTrack; } } private static Map<String, DisplayExperiment> experimentCache = null; private static Map<Integer, Map<String, Long>> submissionFeatureCounts = null; private static Map<Integer, Integer> submissionExpressionLevelCounts = null; private static Map<Integer, Integer> submissionIdCache = null; private static Map<Integer, List<GBrowseTrack>> submissionTracksCache = null; private static Map<Integer, Set<ResultFile>> submissionFilesCache = null; private static Map<Integer, Integer> filesPerSubmissionCache = null; private static Map<Integer, List<String>> submissionLocatedFeatureTypes = null; private static Map<Integer, List<String>> submissionUnlocatedFeatureTypes = null; private static Map<Integer, List<String[]>> submissionRepositedCache = null; private static Map<String, String> featDescriptionCache = null; private static long lastTrackCacheRefresh = 0; private static final long TWO_HOUR = 7200000; /** * Fetch experiment details for display. * @param os the production objectStore * @return a list of experiments */ public static synchronized List<DisplayExperiment> getExperiments(ObjectStore os) { if (experimentCache == null) { readExperiments(os); } return new ArrayList<DisplayExperiment>(experimentCache.values()); } /** * Fetch GBrowse tracks per submission fpr display. This updates automatically from the GBrowse * server and refreshes periodically (according to threshold). When refreshing another process * is spawned which will update tracks when finished, if GBrowse can't be accessed the current * list of tracks of tracks are preserved. * @return map from submission id to list of GBrowse tracks */ public static synchronized Map<Integer, List<GBrowseTrack>> getGBrowseTracks() { fetchGBrowseTracks(); while (submissionTracksCache == null) { try { MetadataCache.class.wait(); } catch (InterruptedException e) { } } return submissionTracksCache; } /** * Fetch unlocated feature types per submission. * @param os the production objectStore * @return map of unlocated feature types */ public static synchronized Map<Integer, List<String>> getLocatedFeatureTypes(ObjectStore os) { if (submissionLocatedFeatureTypes == null) { readSubmissionLocatedFeature(os); } return submissionLocatedFeatureTypes; } /** * Fetch unlocated feature types per submission. * @param os the production objectStore * @return map of unlocated feature types */ public static synchronized Map<Integer, List<String>> getUnlocatedFeatureTypes(ObjectStore os) { if (submissionUnlocatedFeatureTypes == null) { readUnlocatedFeatureTypes(os); } return submissionUnlocatedFeatureTypes; } /** * Fetch unlocated feature types per submission. * @param os the production objectStore * @param dccId the dccId * @return map of unlocated feature types */ public static synchronized Set<String> getUnlocatedFeatureTypesBySubId(ObjectStore os, Integer dccId) { if (submissionUnlocatedFeatureTypes == null) { readUnlocatedFeatureTypes(os); } Set<String> uf = new HashSet<String>(submissionUnlocatedFeatureTypes.get(dccId)); return uf; } /** * Fetch the collection of ResultFiles per submission. * @param os the production objectStore * @return map */ public static synchronized Map<Integer, Set<ResultFile>> getSubmissionFiles(ObjectStore os) { if (submissionFilesCache == null) { readSubmissionCollections(os); // readSubmissionFiles(os); } return submissionFilesCache; } /** * Fetch the collection of Expression Level Counts per submission. * @param os the production objectStore * @return map */ public static synchronized Map<Integer, Integer> getSubmissionExpressionLevelCounts(ObjectStore os) { if (submissionExpressionLevelCounts == null) { readSubmissionCollections(os); } return submissionExpressionLevelCounts; } /** * Fetch number of input/output file per submission. * @param os the production objectStore * @return map */ public static synchronized Map<Integer, Integer> getFilesPerSubmission(ObjectStore os) { if (submissionFilesCache == null) { readSubmissionCollections(os); } filesPerSubmissionCache = new HashMap<Integer, Integer>(); Iterator<Integer> dccId = submissionFilesCache.keySet().iterator(); while (dccId.hasNext()) { Integer thisSub = dccId.next(); Integer nrFiles = submissionFilesCache.get(thisSub).size(); filesPerSubmissionCache.put(thisSub, nrFiles); } return filesPerSubmissionCache; } /** * Fetch a list of file names for a given submission. * @param os the objectStore * @param dccId the modENCODE submission id * @return a list of file names */ public static synchronized List<ResultFile> getFilesByDccId(ObjectStore os, Integer dccId) { if (submissionFilesCache == null) { readSubmissionCollections(os); } return new ArrayList<ResultFile>(submissionFilesCache.get(dccId)); } /** * Fetch a list of GBrowse tracks for a given submission. * @param dccId the modENCODE submission id * @return a list of file names */ public static synchronized List<GBrowseTrack> getTracksByDccId(Integer dccId) { Map<Integer, List<GBrowseTrack>> tracks = getGBrowseTracks(); if (tracks.get(dccId) != null) { return new ArrayList<GBrowseTrack>(tracks.get(dccId)); } else { return new ArrayList<GBrowseTrack>(); } } /** * Fetch a list of file names for a given submission. * @param servletContext the context * @return a list of file names */ public static synchronized Map<String, String> getFeatTypeDescription(ServletContext servletContext) { if (featDescriptionCache == null) { readFeatTypeDescription(servletContext); } return featDescriptionCache; } /** * Fetch a map from feature type to count for a given submission. * @param os the objectStore * @param dccId the modENCODE submission id * @return a map from feature type to count */ public static synchronized Map<String, Long> getSubmissionFeatureCounts(ObjectStore os, Integer dccId) { if (submissionFeatureCounts == null) { readSubmissionFeatureCounts(os); } return submissionFeatureCounts.get(dccId); } /** * Fetch the number of expression levels for a given submission. * @param os the objectStore * @param dccId the modENCODE submission id * @return a map from submission to count */ public static synchronized Integer getSubmissionExpressionLevelCount(ObjectStore os, Integer dccId) { if (submissionExpressionLevelCounts == null) { getSubmissionExpressionLevelCounts(os); } return submissionExpressionLevelCounts.get(dccId); } /** * Fetch a submission by the modENCODE submission ids * @param os the objectStore * @param dccId the modENCODE submission id * @return the requested submission * @throws ObjectStoreException if error reading database */ public static synchronized Submission getSubmissionByDccId(ObjectStore os, Integer dccId) throws ObjectStoreException { if (submissionIdCache == null) { readSubmissionFeatureCounts(os); } return (Submission) os.getObjectById(submissionIdCache.get(dccId)); } /** * Get experiment information by name * @param os the objectStore * @param name of the experiment to fetch * @return details of the experiment * @throws ObjectStoreException if error reading database */ public static synchronized DisplayExperiment getExperimentByName(ObjectStore os, String name) throws ObjectStoreException { if (experimentCache == null) { readExperiments(os); } return experimentCache.get(name); } private static void fetchGBrowseTracks() { long timeSinceLastRefresh = System.currentTimeMillis() - lastTrackCacheRefresh; if (timeSinceLastRefresh > TWO_HOUR) { readGBrowseTracks(); lastTrackCacheRefresh = System.currentTimeMillis(); } } /** * Set the map of GBrowse tracks. * * @param tracks map of dccId:GBrowse tracks */ public static synchronized void setGBrowseTracks(Map<Integer, List<GBrowseTrack>> tracks) { MetadataCache.class.notifyAll(); submissionTracksCache = tracks; } /** * Method to obtain the map of unlocated feature types by submission id * * @param os the objectStore * @return submissionUnlocatedFeatureTypes */ private static Map<Integer, List<String>> readUnlocatedFeatureTypes(ObjectStore os) { long startTime = System.currentTimeMillis(); try { if (submissionUnlocatedFeatureTypes != null) { return submissionUnlocatedFeatureTypes; } submissionUnlocatedFeatureTypes = new HashMap<Integer, List<String>>(); if (submissionLocatedFeatureTypes == null) { readSubmissionLocatedFeature(os); } if (submissionFeatureCounts == null) { readSubmissionFeatureCounts(os); } for (Integer subId : submissionFeatureCounts.keySet()) { Set<String> allFeatures = submissionFeatureCounts.get(subId).keySet(); Set<String> difference = new HashSet<String>(allFeatures); if (submissionLocatedFeatureTypes.get(subId) != null) { difference.removeAll(submissionLocatedFeatureTypes.get(subId)); } if (!difference.isEmpty()) { List <String> thisUnlocated = new ArrayList<String>(); for (String fType : difference) { thisUnlocated.add(fType); } submissionUnlocatedFeatureTypes.put(subId, thisUnlocated); } } } catch (Exception err) { err.printStackTrace(); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed unlocated feature cache, took: " + timeTaken + "ms size = " + submissionUnlocatedFeatureTypes.size()); return submissionUnlocatedFeatureTypes; } /** * * @param os objectStore * @return map exp-tracks */ public static Map<String, List<GBrowseTrack>> getExperimentGBrowseTracks(ObjectStore os) { Map<String, List<GBrowseTrack>> tracks = new HashMap<String, List<GBrowseTrack>>(); Map<Integer, List<GBrowseTrack>> subTracksMap = getGBrowseTracks(); for (DisplayExperiment exp : getExperiments(os)) { List<GBrowseTrack> expTracks = new ArrayList<GBrowseTrack>(); tracks.put(exp.getName(), expTracks); for (Submission sub : exp.getSubmissions()) { List<GBrowseTrack> subTracks = subTracksMap.get(sub.getdCCid()); if (subTracks != null) { // check so it is unique // expTracks.addAll(subTracks); addToList(expTracks, subTracks); } } } return tracks; } /** * adds the elements of a list i to a list l only if they are not yet * there * @param l the receiving list * @param i the donating list */ private static void addToList(List<GBrowseTrack> l, List<GBrowseTrack> i) { Iterator <GBrowseTrack> it = i.iterator(); while (it.hasNext()) { GBrowseTrack thisId = it.next(); if (!l.contains(thisId)) { l.add(thisId); } } } /** * * @param os objectStore * @return map exp-repository entries */ public static Map<String, Set<String[]>> getExperimentRepositoryEntries(ObjectStore os) { Map<String, Set<String[]>> reposited = new HashMap<String, Set<String[]>>(); Map<Integer, List<String[]>> subRepositedMap = getRepositoryEntries(os); for (DisplayExperiment exp : getExperiments(os)) { Set<String[]> expReps = new HashSet<String[]>(); for (Submission sub : exp.getSubmissions()) { List<String[]> subReps = subRepositedMap.get(sub.getdCCid()); if (subReps != null) { expReps.addAll(subReps); } } // for each experiment, we don't to count twice the same repository // entry produced by 2 different submissions. Set<String[]> expRepsCleaned = removeDuplications(expReps); reposited.put(exp.getName(), expRepsCleaned); } return reposited; } private static Set<String[]> removeDuplications(Set<String[]> expReps) { // removing the same repository entry coming from different submissions // in the given experiment Set<String> db = new HashSet<String>(); Set<String> acc = new HashSet<String>(); Set<String[]> dup = new HashSet<String[]>(); for (String[] s : expReps) { if (db.contains(s[0]) && acc.contains(s[1])) { // we don't remove place holders if (!s[1].startsWith("To be")) { dup.add(s); } } db.add(s[0]); acc.add(s[1]); } // do the difference between sets and return it Set<String[]> uniques = new HashSet<String[]>(expReps); uniques.removeAll(dup); return uniques; } /** * * @param os objectStore * @return map exp-repository entries */ public static Map<String, Integer> getExperimentExpressionLevels(ObjectStore os) { Map<String, Integer> experimentELevel = new HashMap<String, Integer>(); Map<Integer, Integer> subELevelMap = getSubmissionExpressionLevelCounts(os); for (DisplayExperiment exp : getExperiments(os)) { Integer expCount = 0; for (Submission sub : exp.getSubmissions()) { Integer subCount = subELevelMap.get(sub.getdCCid()); if (subCount != null) { expCount = expCount + subCount; } } // if (expCount > 0) { experimentELevel.put(exp.getName(), expCount); } return experimentELevel; } /** * Fetch a map from project name to experiment. * @param os the production ObjectStore * @return a map from project name to experiment */ public static Map<String, List<DisplayExperiment>> getProjectExperiments(ObjectStore os) { long startTime = System.currentTimeMillis(); Map<String, List<DisplayExperiment>> projectExperiments = new TreeMap<String, List<DisplayExperiment>>(); for (DisplayExperiment exp : getExperiments(os)) { List<DisplayExperiment> exps = projectExperiments.get(exp.getProjectName()); if (exps == null) { exps = new ArrayList<DisplayExperiment>(); projectExperiments.put(exp.getProjectName(), exps); } exps.add(exp); } long totalTime = System.currentTimeMillis() - startTime; LOG.info("Made project map: " + projectExperiments.size() + " took: " + totalTime + " ms."); return projectExperiments; } private static void readExperiments(ObjectStore os) { long startTime = System.currentTimeMillis(); Map <String, Map<String, Long>> featureCounts = getExperimentFeatureCounts(os); try { Query q = new Query(); QueryClass qcProject = new QueryClass(Project.class); QueryField qcName = new QueryField(qcProject, "name"); q.addFrom(qcProject); q.addToSelect(qcProject); QueryClass qcExperiment = new QueryClass(Experiment.class); q.addFrom(qcExperiment); q.addToSelect(qcExperiment); QueryCollectionReference projExperiments = new QueryCollectionReference(qcProject, "experiments"); ContainsConstraint cc = new ContainsConstraint(projExperiments, ConstraintOp.CONTAINS, qcExperiment); q.setConstraint(cc); q.addToOrderBy(qcName); Results results = os.execute(q); experimentCache = new HashMap<String, DisplayExperiment>(); Iterator i = results.iterator(); while (i.hasNext()) { ResultsRow row = (ResultsRow) i.next(); Project project = (Project) row.get(0); Experiment experiment = (Experiment) row.get(1); Map<String, Long> expFeatureCounts = featureCounts.get(experiment.getName()); DisplayExperiment displayExp = new DisplayExperiment(experiment, project, expFeatureCounts, os); experimentCache.put(displayExp.getName(), displayExp); } } catch (Exception err) { err.printStackTrace(); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed experiment cache, took: " + timeTaken + "ms size = " + experimentCache.size()); } private static Map<String, Map<String, Long>> getExperimentFeatureCounts(ObjectStore os) { long startTime = System.currentTimeMillis(); Query q = new Query(); q.setDistinct(false); QueryClass qcExp = new QueryClass(Experiment.class); QueryClass qcSub = new QueryClass(Submission.class); QueryClass qcLsf = new QueryClass(LocatedSequenceFeature.class); QueryField qfName = new QueryField(qcExp, "name"); QueryField qfClass = new QueryField(qcLsf, "class"); q.addFrom(qcSub); q.addFrom(qcLsf); q.addFrom(qcExp); q.addToSelect(qfName); q.addToSelect(qfClass); q.addToSelect(new QueryFunction()); q.addToGroupBy(qfName); q.addToGroupBy(qfClass); q.addToOrderBy(qfName); q.addToOrderBy(qfClass); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryCollectionReference submissions = new QueryCollectionReference(qcExp, "submissions"); ContainsConstraint ccSubs = new ContainsConstraint(submissions, ConstraintOp.CONTAINS, qcSub); cs.addConstraint(ccSubs); QueryCollectionReference features = new QueryCollectionReference(qcSub, "features"); ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf); cs.addConstraint(ccFeats); q.setConstraint(cs); Results results = os.execute(q); Map<String, Map<String, Long>> featureCounts = new LinkedHashMap<String, Map<String, Long>>(); // for each classes set the values for jsp for (Iterator<ResultsRow> iter = results.iterator(); iter.hasNext(); ) { ResultsRow row = iter.next(); String expName = (String) row.get(0); Class feat = (Class) row.get(1); Long count = (Long) row.get(2); Map<String, Long> expFeatureCounts = featureCounts.get(expName); if (expFeatureCounts == null) { expFeatureCounts = new HashMap<String, Long>(); featureCounts.put(expName, expFeatureCounts); } expFeatureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Read experiment feature counts, took: " + timeTaken + "ms"); return featureCounts; } private static void readSubmissionFeatureCounts(ObjectStore os) { long startTime = System.currentTimeMillis(); submissionFeatureCounts = new LinkedHashMap<Integer, Map<String, Long>>(); submissionIdCache = new HashMap<Integer, Integer>(); Query q = new Query(); q.setDistinct(false); QueryClass qcSub = new QueryClass(Submission.class); QueryClass qcLsf = new QueryClass(LocatedSequenceFeature.class); QueryField qfClass = new QueryField(qcLsf, "class"); q.addFrom(qcSub); q.addFrom(qcLsf); q.addToSelect(qcSub); q.addToSelect(qfClass); q.addToSelect(new QueryFunction()); q.addToGroupBy(qcSub); q.addToGroupBy(qfClass); q.addToOrderBy(qcSub); q.addToOrderBy(qfClass); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryCollectionReference features = new QueryCollectionReference(qcSub, "features"); ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf); cs.addConstraint(ccFeats); q.setConstraint(cs); Results results = os.execute(q); // for each classes set the values for jsp for (Iterator<ResultsRow> iter = results.iterator(); iter.hasNext(); ) { ResultsRow row = iter.next(); Submission sub = (Submission) row.get(0); Class feat = (Class) row.get(1); Long count = (Long) row.get(2); submissionIdCache.put(sub.getdCCid(), sub.getId()); Map<String, Long> featureCounts = submissionFeatureCounts.get(sub.getdCCid()); if (featureCounts == null) { featureCounts = new HashMap<String, Long>(); submissionFeatureCounts.put(sub.getdCCid(), featureCounts); } featureCounts.put(TypeUtil.unqualifiedName(feat.getName()), count); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed submissionFeatureCounts cache, took: " + timeTaken + "ms size = " + submissionFeatureCounts.size()); } private static void readSubmissionCollections(ObjectStore os) { long startTime = System.currentTimeMillis(); try { Query q = new Query(); QueryClass qcSubmission = new QueryClass(Submission.class); QueryField qfDCCid = new QueryField(qcSubmission, "DCCid"); q.addFrom(qcSubmission); q.addToSelect(qcSubmission); q.addToOrderBy(qfDCCid); submissionFilesCache = new HashMap<Integer, Set<ResultFile>>(); submissionExpressionLevelCounts = new HashMap<Integer, Integer>(); Results results = os.executeSingleton(q); // for submission, get result files and expression level count Iterator i = results.iterator(); while (i.hasNext()) { Submission sub = (Submission) i.next(); Set<ResultFile> files = sub.getResultFiles(); submissionFilesCache.put(sub.getdCCid(), files); Set<ExpressionLevel> el = sub.getExpressionLevels(); submissionExpressionLevelCounts.put(sub.getdCCid(), el.size()); } } catch (Exception err) { err.printStackTrace(); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed submission collections caches, took: " + timeTaken + "ms size: files = " + submissionFilesCache.size() + ", expression levels = " + submissionExpressionLevelCounts.size()); } private static void readSubmissionFiles(ObjectStore os) { long startTime = System.currentTimeMillis(); try { Query q = new Query(); QueryClass qcSubmission = new QueryClass(Submission.class); QueryField qfDCCid = new QueryField(qcSubmission, "DCCid"); q.addFrom(qcSubmission); q.addToSelect(qcSubmission); q.addToOrderBy(qfDCCid); submissionFilesCache = new HashMap<Integer, Set<ResultFile>>(); Results results = os.executeSingleton(q); // for each project, get its labs Iterator i = results.iterator(); while (i.hasNext()) { Submission sub = (Submission) i.next(); Set<ResultFile> files = sub.getResultFiles(); submissionFilesCache.put(sub.getdCCid(), files); } } catch (Exception err) { err.printStackTrace(); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed file names cache, took: " + timeTaken + "ms size = " + submissionFilesCache.size()); } private static void readSubmissionLocatedFeature(ObjectStore os) { long startTime = System.currentTimeMillis(); submissionLocatedFeatureTypes = new LinkedHashMap<Integer, List<String>>(); Query q = new Query(); q.setDistinct(true); QueryClass qcSub = new QueryClass(Submission.class); QueryClass qcLsf = new QueryClass(LocatedSequenceFeature.class); QueryClass qcLoc = new QueryClass(Location.class); QueryField qfClass = new QueryField(qcLsf, "class"); q.addFrom(qcSub); q.addFrom(qcLsf); q.addFrom(qcLoc); q.addToSelect(qcSub); q.addToSelect(qfClass); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); QueryCollectionReference features = new QueryCollectionReference(qcSub, "features"); ContainsConstraint ccFeats = new ContainsConstraint(features, ConstraintOp.CONTAINS, qcLsf); cs.addConstraint(ccFeats); QueryObjectReference location = new QueryObjectReference(qcLsf, "chromosomeLocation"); ContainsConstraint ccLocs = new ContainsConstraint(location, ConstraintOp.CONTAINS, qcLoc); cs.addConstraint(ccLocs); q.setConstraint(cs); Results results = os.execute(q); // for each classes set the values for jsp for (Iterator<ResultsRow> iter = results.iterator(); iter.hasNext(); ) { ResultsRow row = iter.next(); Submission sub = (Submission) row.get(0); Class feat = (Class) row.get(1); addToMap(submissionLocatedFeatureTypes, sub.getdCCid(), TypeUtil.unqualifiedName(feat.getName())); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed located features cache, took: " + timeTaken + "ms size = " + submissionLocatedFeatureTypes.size()); } /** * Fetch reposited (GEO/SRA/AE..) entries per submission. * @param os the production objectStore * @return map */ public static synchronized Map<Integer, List<String[]>> getRepositoryEntries(ObjectStore os) { if (submissionRepositedCache == null) { readSubmissionRepositoryEntries(os); } return submissionRepositedCache; } private static void readSubmissionRepositoryEntries(ObjectStore os) { long startTime = System.currentTimeMillis(); try { Query q = new Query(); QueryClass qcSubmission = new QueryClass(Submission.class); QueryField qfDCCid = new QueryField(qcSubmission, "DCCid"); q.addFrom(qcSubmission); q.addToSelect(qfDCCid); QueryClass qcRepositoryEntry = new QueryClass(DatabaseRecord.class); QueryField qfDatabase = new QueryField(qcRepositoryEntry, "database"); QueryField qfAccession = new QueryField(qcRepositoryEntry, "accession"); QueryField qfUrl = new QueryField(qcRepositoryEntry, "url"); q.addFrom(qcRepositoryEntry); q.addToSelect(qfDatabase); q.addToSelect(qfAccession); q.addToSelect(qfUrl); // join the tables QueryCollectionReference ref1 = new QueryCollectionReference(qcSubmission, "databaseRecords"); ContainsConstraint cc = new ContainsConstraint(ref1, ConstraintOp.CONTAINS, qcRepositoryEntry); q.setConstraint(cc); q.addToOrderBy(qfDCCid); q.addToOrderBy(qfDatabase); Results results = os.execute(q); submissionRepositedCache = new HashMap<Integer, List<String[]>>(); Integer counter = 0; Integer prevSub = new Integer(-1); List<String[]> subRep = new ArrayList<String[]>(); Iterator i = results.iterator(); while (i.hasNext()) { ResultsRow row = (ResultsRow) i.next(); counter++; Integer dccId = (Integer) row.get(0); String db = (String) row.get(1); String acc = (String) row.get(2); String url = (String) row.get(3); String[] thisRecord = {db, acc, url}; if (!dccId.equals(prevSub) || counter.equals(results.size())) { if (prevSub > 0) { if (counter.equals(results.size())) { prevSub = dccId; subRep.add(thisRecord); } List<String[]> subRepIn = new ArrayList<String[]>(); subRepIn.addAll(subRep); submissionRepositedCache.put(prevSub, subRepIn); subRep.clear(); } prevSub = dccId; } subRep.add(thisRecord); } } catch (Exception err) { err.printStackTrace(); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed Repository entries cache, took: " + timeTaken + "ms size = " + submissionRepositedCache.size()); } /** * adds an element to a list which is the value of a map * @param m the map (<String, List<String>>) * @param key the key for the map * @param value the list */ private static void addToMap(Map<Integer, List<String>> m, Integer key, String value) { List<String> ids = new ArrayList<String>(); if (m.containsKey(key)) { ids = m.get(key); } if (!ids.contains(value)) { ids.add(value); m.put(key, ids); } } /** * Method to fill the cached map of submissions (ddcId) to list of * GBrowse tracks * */ private static void readGBrowseTracks() { Runnable r = new Runnable() { public void run() { threadedReadGBrowseTracks(); } }; Thread t = new Thread(r); t.start(); } private static void threadedReadGBrowseTracks() { long startTime = System.currentTimeMillis(); Map<Integer, List<GBrowseTrack>> tracks = new HashMap<Integer, List<GBrowseTrack>>(); Map<Integer, List<GBrowseTrack>> flyTracks = null; Map<Integer, List<GBrowseTrack>> wormTracks = null; try { flyTracks = readTracks("fly"); wormTracks = readTracks("worm"); } catch (Exception e) { LOG.error(e); } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed GBrowse tracks cache, took: " + timeTaken + "ms size = " + tracks.size()); if (flyTracks != null && wormTracks != null) { tracks.putAll(flyTracks); tracks.putAll(wormTracks); setGBrowseTracks(tracks); } } /** * Method to read the list of GBrowse tracks for a given organism * * @param organism (i.e. fly or worm) * @return submissionTracksCache */ private static Map<Integer, List<GBrowseTrack>> readTracks(String organism) { Map<Integer, List<GBrowseTrack>> submissionsToTracks = new HashMap<Integer, List<GBrowseTrack>>(); try { URL url = new URL(GBROWSE_BASE_URL + organism + GBROWSE_ST_URL_END); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; // examples of lines: // [Henikoff_Salt_H3_WIG] // key = H3.3 Chromatin fractions extracted with NaCl // select = 80mM fraction#2534 350mM fraction#2535 600mM fraction#2536 // citation = <h1> H3.3 NaCl Salt Extracted Chromatin .... // [LIEB_WIG_CHROMNUC_ENV] // key = Chromosome-Nuclear Envelope Interaction // select = SDQ3891_LEM2_N2_MXEMB_1#2729 SDQ3897_NPP13_N2_MXEMB_1#2738 // citation = <h1> Chromosome-Nuclear Envelope Interaction proteins... // note: subtracks have also names with spaces StringBuffer trackName = new StringBuffer(); StringBuffer toAppend = new StringBuffer(); while ((line = reader.readLine()) != null) { LOG.debug("SUBTRACK LINE: " + line); if (line.startsWith("[")) { // this is a track trackName.setLength(0); trackName.append(line.substring(1, line.indexOf(']'))); } if (line.startsWith("select")) { // here subtracks are listed String data = line.replace("select = ", ""); String[] result = data.split("\\s"); for (String token : result) { if (token.indexOf(' // we are dealing with a bit of name toAppend.append(token + " "); } else { // this is a token with subId String subTrack = toAppend.toString() + token.substring(0, token.indexOf(' Integer dccId = Integer.parseInt( token.substring(token.indexOf('#') + 1, token.length())); LOG.debug("SUBTRACK: " + subTrack); toAppend.setLength(0); // empty buffer GBrowseTrack newTrack = new GBrowseTrack(organism, trackName.toString(), subTrack); addToGBMap(submissionsToTracks, dccId, newTrack); } } } } reader.close(); } catch (Exception err) { err.printStackTrace(); } return submissionsToTracks; } /** * This method adds a GBrowse track to a map with * key = dccId * value = list of associated GBrowse tracks */ private static void addToGBMap( Map<Integer, List<GBrowseTrack>> m, Integer key, GBrowseTrack value) { List<GBrowseTrack> gbs = new ArrayList<GBrowseTrack>(); if (m.containsKey(key)) { gbs = m.get(key); } if (!gbs.contains(value)) { gbs.add(value); m.put(key, gbs); } } /** * This method get the GBrowse base URL from the properties * or default to one * @return the base URL */ private static String getGBrowsePrefix() { Properties props = PropertiesUtil.getProperties(); String gbURL = props.getProperty("gbrowse.prefix") + "/"; if (gbURL == null || gbURL.length() < 5) { return GBROWSE_DEFAULT_URL; } return gbURL; } /** * This method get the GBrowse base URL from the properties * or default to one * @return the base URL */ private static Map<String, String> readFeatTypeDescription(ServletContext servletContext) { long startTime = System.currentTimeMillis(); featDescriptionCache = new HashMap<String, String>(); Properties props = new Properties(); InputStream is = servletContext.getResourceAsStream("/WEB-INF/featureTypeDescr.properties"); if (is == null) { LOG.info(NO_FEAT_DESCR_LOG); } else { try { props.load(is); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace()); e.printStackTrace(); } Enumeration en = props.keys(); // while (props.keys().hasMoreElements()) { while (en.hasMoreElements()) { String expFeat = (String) en.nextElement(); String descr = props.getProperty(expFeat); featDescriptionCache.put(expFeat, descr); } } long timeTaken = System.currentTimeMillis() - startTime; LOG.info("Primed feature description cache, took: " + timeTaken + "ms size = " + featDescriptionCache.size()); return featDescriptionCache; } }
package org.apache.xerces.util; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.impl.dtd.XMLDTDDescription; //import org.apache.xerces.impl.xs.XSDDescription; import java.util.Hashtable; import java.util.Enumeration; /** * Stores grammars in a pool associated to a specific key. This grammar pool * implementation stores two types of grammars: those keyed by the root element * name, and those keyed by the grammar's target namespace. * * This is the default implementation of the GrammarPool interface. * As we move forward, this will become more function-rich and robust. * * @author Jeffrey Rodriguez, IBM * @author Andy Clark, IBM * @author Neil Graham, IBM * @author Pavani Mukthipudi, Sun Microsystems * @author Neeraj Bajaj, SUN Microsystems * * @version $Id$ */ public class XMLGrammarPoolImpl implements XMLGrammarPool { // Constants /** Default size. */ protected static final int TABLE_SIZE = 11; // Data /** Grammars. */ protected Entry[] fGrammars = null; // whether this pool is locked protected boolean fPoolIsLocked; // the number of grammars in the pool protected int fGrammarCount = 0; private static final boolean DEBUG = false ; // Constructors /** Constructs a grammar pool with a default number of buckets. */ public XMLGrammarPoolImpl() { fGrammars = new Entry[TABLE_SIZE]; fPoolIsLocked = false; } // <init>() /** Constructs a grammar pool with a specified number of buckets. */ public XMLGrammarPoolImpl(int initialCapacity) { fGrammars = new Entry[initialCapacity]; fPoolIsLocked = false; } // XMLGrammarPool methods /* <p> Retrieve the initial known set of grammars. This method is * called by a validator before the validation starts. The application * can provide an initial set of grammars available to the current * validation attempt. </p> * * @param grammarType The type of the grammar, from the * <code>org.apache.xerces.xni.grammars.XMLGrammarDescription</code> * interface. * @return The set of grammars the validator may put in its "bucket" */ public Grammar [] retrieveInitialGrammarSet (String grammarType) { synchronized (fGrammars) { int grammarSize = fGrammars.length ; Grammar [] tempGrammars = new Grammar[fGrammarCount]; int pos = 0; for (int i = 0; i < grammarSize; i++) { for (Entry e = fGrammars[i]; e != null; e = e.next) { if (e.desc.getGrammarType().equals(grammarType)) { tempGrammars[pos++] = e.grammar; } } } Grammar[] toReturn = new Grammar[pos]; System.arraycopy(tempGrammars, 0, toReturn, 0, pos); return toReturn; } } // retrieveInitialGrammarSet (String): Grammar[] /* <p> Return the final set of grammars that the validator ended up * with. This method is called after the validation finishes. The * application may then choose to cache some of the returned grammars.</p> * <p>In this implementation, we make our choice based on whether this object * is "locked"--that is, whether the application has instructed * us not to accept any new grammars.</p> * * @param grammarType The type of the grammars being returned; * @param grammars An array containing the set of grammars being * returned; order is not significant. */ public void cacheGrammars(String grammarType, Grammar[] grammars) { if(!fPoolIsLocked) { for (int i = 0; i < grammars.length; i++) { if(DEBUG) { System.out.println("CACHED GRAMMAR " + (i+1) ) ; Grammar temp = grammars[i] ; //print(temp.getGrammarDescription()); } putGrammar(grammars[i]); } } } // cacheGrammars(String, Grammar[]); /* <p> This method requests that the application retrieve a grammar * corresponding to the given GrammarIdentifier from its cache. * If it cannot do so it must return null; the parser will then * call the EntityResolver. </p> * <strong>An application must not call its EntityResolver itself * from this method; this may result in infinite recursions.</strong> * * This implementation chooses to use the root element name to identify a DTD grammar * and the target namespace to identify a Schema grammar. * * @param desc The description of the Grammar being requested. * @return The Grammar corresponding to this description or null if * no such Grammar is known. */ public Grammar retrieveGrammar(XMLGrammarDescription desc) { if(DEBUG){ System.out.println("RETRIEVING GRAMMAR FROM THE APPLICATION WITH FOLLOWING DESCRIPTION :"); //print(desc); } return getGrammar(desc); } // retrieveGrammar(XMLGrammarDescription): Grammar // Public methods /** * Puts the specified grammar into the grammar pool and associates it to * its root element name or its target namespace. * * @param grammar The Grammar. */ public void putGrammar(Grammar grammar) { if(!fPoolIsLocked) { synchronized (fGrammars) { XMLGrammarDescription desc = grammar.getGrammarDescription(); int hash = hashCode(desc); int index = (hash & 0x7FFFFFFF) % fGrammars.length; for (Entry entry = fGrammars[index]; entry != null; entry = entry.next) { if (entry.hash == hash && equals(entry.desc, desc)) { entry.grammar = grammar; return; } } // create a new entry Entry entry = new Entry(hash, desc, grammar, fGrammars[index]); fGrammars[index] = entry; fGrammarCount++; } } } // putGrammar(Grammar) /** * Returns the grammar associated to the specified grammar description. * Currently, the root element name is used as the key for DTD grammars * and the target namespace is used as the key for Schema grammars. * * @param desc The Grammar Description. */ public Grammar getGrammar(XMLGrammarDescription desc) { synchronized (fGrammars) { int hash = hashCode(desc); int index = (hash & 0x7FFFFFFF) % fGrammars.length; for (Entry entry = fGrammars[index] ; entry != null ; entry = entry.next) { if ((entry.hash == hash) && equals(entry.desc, desc)) { return entry.grammar; } } return null; } } // getGrammar(XMLGrammarDescription):Grammar /** * Removes the grammar associated to the specified grammar description from the * grammar pool and returns the removed grammar. Currently, the root element name * is used as the key for DTD grammars and the target namespace is used * as the key for Schema grammars. * * @param desc The Grammar Description. * @return The removed grammar. */ public Grammar removeGrammar(XMLGrammarDescription desc) { synchronized (fGrammars) { int hash = hashCode(desc); int index = (hash & 0x7FFFFFFF) % fGrammars.length; for (Entry entry = fGrammars[index], prev = null ; entry != null ; prev = entry, entry = entry.next) { if ((entry.hash == hash) && equals(entry.desc, desc)) { if (prev != null) { prev.next = entry.next; } else { fGrammars[index] = entry.next; } Grammar tempGrammar = entry.grammar; entry.grammar = null; fGrammarCount return tempGrammar; } } return null; } } // removeGrammar(XMLGrammarDescription):Grammar /** * Returns true if the grammar pool contains a grammar associated * to the specified grammar description. Currently, the root element name * is used as the key for DTD grammars and the target namespace is used * as the key for Schema grammars. * * @param desc The Grammar Description. */ public boolean containsGrammar(XMLGrammarDescription desc) { synchronized (fGrammars) { int hash = hashCode(desc); int index = (hash & 0x7FFFFFFF) % fGrammars.length; for (Entry entry = fGrammars[index] ; entry != null ; entry = entry.next) { if ((entry.hash == hash) && equals(entry.desc, desc)) { return true; } } return false; } } // containsGrammar(XMLGrammarDescription):boolean /* <p> Sets this grammar pool to a "locked" state--i.e., * no new grammars will be added until it is "unlocked". */ public void lockPool() { fPoolIsLocked = true; } // lockPool() /* <p> Sets this grammar pool to an "unlocked" state--i.e., * new grammars will be added when putGrammar or cacheGrammars * are called. */ public void unlockPool() { fPoolIsLocked = false; } // unlockPool() /* * <p>This method clears the pool-i.e., removes references * to all the grammars in it.</p> */ public void clear() { for (int i=0; i<fGrammars.length; i++) { if(fGrammars[i] != null) { fGrammars[i].clear(); fGrammars[i] = null; } } fGrammarCount = 0; } // clear() /** * This method checks whether two grammars are the same. Currently, we compare * the root element names for DTD grammars and the target namespaces for Schema grammars. * The application can override this behaviour and add its own logic. * * @param gDesc1 The grammar description * @param gDesc2 The grammar description of the grammar to be compared to * @return True if the grammars are equal, otherwise false */ public boolean equals(XMLGrammarDescription desc1, XMLGrammarDescription desc2) { return desc1.equals(desc2); } /** * Returns the hash code value for the given grammar description. * * @param desc The grammar description * @return The hash code value */ public int hashCode(XMLGrammarDescription desc) { return desc.hashCode(); } /** * This class is a grammar pool entry. Each entry acts as a node * in a linked list. */ protected static final class Entry { public int hash; public XMLGrammarDescription desc; public Grammar grammar; public Entry next; protected Entry(int hash, XMLGrammarDescription desc, Grammar grammar, Entry next) { this.hash = hash; this.desc = desc; this.grammar = grammar; this.next = next; } // clear this entry; useful to promote garbage collection // since reduces reference count of objects to be destroyed protected void clear () { desc = null; grammar = null; if(next != null) { next.clear(); next = null; } } // clear() } // class Entry /* For DTD build we can't import here XSDDescription. Thus, this method is commented out.. */ /* public void print(XMLGrammarDescription description){ if(description.getGrammarType().equals(XMLGrammarDescription.XML_DTD)){ } else if(description.getGrammarType().equals(XMLGrammarDescription.XML_SCHEMA)){ XSDDescription schema = (XSDDescription)description ; System.out.println("Context = " + schema.getContextType()); System.out.println("TargetNamespace = " + schema.getTargetNamespace()); String [] temp = schema.getLocationHints(); for (int i = 0 ; (temp != null && i < temp.length) ; i++){ System.out.println("LocationHint " + i + " = "+ temp[i]); } System.out.println("Triggering Component = " + schema.getTriggeringComponent()); System.out.println("EnclosingElementName =" + schema.getEnclosingElementName()); } }//print */ } // class XMLGrammarPoolImpl
package org.biojava.bio.alignment; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.biojava.bio.BioException; import org.biojava.bio.BioRuntimeException; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.SequenceIterator; import org.biojava.bio.seq.db.SequenceDB; import org.biojava.bio.seq.impl.SimpleGappedSequence; import org.biojava.bio.seq.impl.SimpleSequence; import org.biojava.bio.seq.io.SymbolTokenization; import org.biojava.bio.symbol.Alignment; import org.biojava.bio.symbol.SimpleAlignment; import org.biojava.bio.symbol.SimpleSymbolList; /** Needleman and Wunsch definied the problem of global sequence alignments, * from the first till the last symbol of a sequence. * This class is able to perform such global sequence comparisons efficiently * by dynamic programing. If inserts and deletes are equally expensive and * as expensive as the extension of a gap, the alignment method of this class * does not use affine gap panelties. Otherwise it does. Those costs need * four times as much memory, which has significant effects on the run time, * if the computer needs to swap. * * @author Andreas Dr&auml;ger * @author Gero Greiner * @since 1.5 */ public class NeedlemanWunsch extends SequenceAlignment { protected double[][] CostMatrix; protected SubstitutionMatrix subMatrix; protected Alignment pairalign; protected String alignment; private double insert, delete, gapExt, match, replace; /** Constructs a new Object with the given parameters based on the Needleman-Wunsch algorithm * The alphabet of sequences to be aligned will be taken from the given substitution matrix. * @param match This gives the costs for a match operation. It is only used, if there is no entry * for a certain match of two symbols in the substitution matrix (default value). * @param replace This is like the match parameter just the default, if there is no entry in the * substitution matrix object. * @param insert The costs of a single insert operation. * @param delete The expenses of a single delete operation. * @param gapExtend The expenses of an extension of a existing gap (that is a previous insert or * delete. If the costs for insert and delete are equal and also equal to gapExtend, no * affine gap penalties will be used, which saves a significant amount of memory. * @param subMat The substitution matrix object which gives the costs for matches and replaces. */ public NeedlemanWunsch( double match, double replace, double insert, double delete, double gapExtend, SubstitutionMatrix subMat) { this.subMatrix = subMat; this.insert = insert; this.delete = delete; this.gapExt = gapExtend; this.match = match; this.replace = replace; this.alignment = ""; } /** Sets the substitution matrix to be used to the specified one. * Afterwards it is only possible to align sequences of the alphabet * of this substitution matrix. * * @param matrix an instance of a substitution matrix. */ public void setSubstitutionMatrix(SubstitutionMatrix matrix) { this.subMatrix = matrix; } /** Sets the penalty for an insert operation to the specified value. * @param ins costs for a single insert operation */ public void setInsert(double ins) { this.insert = ins; } /** Sets the penalty for a delete operation to the specified value. * @param del costs for a single deletion operation */ public void setDelete(double del) { this.delete = del; } /** Sets the penalty for an extension of any gap (insert or delete) to the * specified value. * @param ge costs for any gap extension */ public void setGapExt(double ge) { this.gapExt = ge; } /** Sets the penalty for a match operation to the specified value. * @param ma costs for a single match operation */ public void setMatch(double ma) { this.match = ma; } /** Sets the penalty for a replace operation to the specified value. * @param rep costs for a single replace operation */ public void setReplace(double rep) { this.replace = rep; } /** Returns the current expenses of a single insert operation. * @return insert */ public double getInsert() { return insert; } /** Returns the current expenses of a single delete operation. * @return delete */ public double getDelete() { return delete; } /** Returns the current expenses of any extension of a gap operation. * @return gapExt */ public double getGapExt() { return gapExt; } /** Returns the current expenses of a single match operation. * @return match */ public double getMatch() { return match; } /** Returns the current expenses of a single replace operation. * @return replace */ public double getReplace() { return replace; } /** Prints a String representation of the CostMatrix for the given Alignment on the screen. * This can be used to get a better understanding of the algorithm. There is no other purpose. * This method also works for all extensions of this class with all kinds of matrices. * @param queryChar a character representation of the query sequence * (<code>mySequence.seqString().toCharArray()</code>). * @param targetChar a character representation of the target sequence. * @return a String representation of the matrix. */ public static String printCostMatrix (double[][] CostMatrix, char[] queryChar, char[] targetChar) { int line, col; String output = "\t"; for (col=0; col<=targetChar.length; col++) if (col==0) output += "["+col+"]\t"; else output += "["+targetChar[col-1]+"]\t"; for (line=0; line<=queryChar.length; line++) { if (line==0) output += "\n["+line+"]\t"; else output += "\n["+queryChar[line-1]+"]\t"; for (col=0; col<=targetChar.length; col++) output += CostMatrix[line][col]+"\t"; } output += "\ndelta[Edit] = "+CostMatrix[line-1][col-1]+"\n"; return output; } /** prints the alignment String on the screen (standard output). * @param align The parameter is typically given by the * {@link #getAlignmentString() getAlignmentString()} method. */ public static void printAlignment(String align) { System.out.print(align); } /** This method is good if one wants to reuse the alignment calculated by this class in another * BioJava class. It just performs {@link #pairwiseAlignment(Sequence, Sequence) pairwiseAlignment} and returns an <code>Alignment</code> * instance containing the two aligned sequences. * @return Alignment object containing the two gapped sequences constructed from query and target. * @throws Exception */ public Alignment getAlignment(Sequence query, Sequence target) throws Exception { pairwiseAlignment(query, target); return pairalign; } /** This gives the edit distance acording to the given parameters of this certain * object. It returns just the last element of the internal cost matrix (left side * down). So if you extend this class, you can just do the following: * <code>double myDistanceValue = foo; this.CostMatrix = new double[1][1]; this.CostMatrix[0][0] = myDistanceValue;</code> * @return returns the edit_distance computed with the given parameters. */ public double getEditDistance() { return CostMatrix[CostMatrix.length-1][CostMatrix[CostMatrix.length-1].length - 1]; } /** This just computes the minimum of three double values. * @param x * @param y * @param z * @return Gives the minimum of three doubles */ protected static double min (double x, double y, double z) { if ((x < y) && (x < z)) return x; if (y < z) return y; return z; } /* (non-Javadoc) * @see toolbox.align.SequenceAlignment#getAlignment() */ public String getAlignmentString() throws BioException { return alignment; } /* (non-Javadoc) * @see toolbox.align.SequenceAlignment#alignAll(org.biojava.bio.seq.SequenceIterator, org.biojava.bio.seq.db.SequenceDB) */ public List alignAll(SequenceIterator source, SequenceDB subjectDB) throws NoSuchElementException, BioException { List l = new LinkedList(); while (source.hasNext()) { Sequence query = source.nextSequence(); // compare all the sequences of both sets. SequenceIterator target = subjectDB.sequenceIterator(); while (target.hasNext()) try { l.add(getAlignment(query, target.nextSequence())); //pairwiseAlignment(query, target.nextSequence()); } catch (Exception exc) { exc.printStackTrace(); } } return l; } /** Global pairwise sequence alginment of two BioJava-Sequence objects according to the * Needleman-Wunsch-algorithm. * * @see org.biojava.bio.alignment.SequenceAlignment#pairwiseAlignment(org.biojava.bio.seq.Sequence, org.biojava.bio.seq.Sequence) */ public double pairwiseAlignment(Sequence query, Sequence subject) throws BioRuntimeException { if (query.getAlphabet().equals(subject.getAlphabet()) && query.getAlphabet().equals(subMatrix.getAlphabet())) { long time = System.currentTimeMillis(); int i, j; this.CostMatrix = new double[query.length()+1][subject.length()+1]; // Matrix CostMatrix /* * Variables for the traceback */ String[] align = new String[] {"", ""}; String path = ""; // construct the matrix: CostMatrix[0][0] = 0; /* If we want to have affine gap penalties, we have to initialise additional matrices: * If this is not necessary, we won't do that (because it's expensive). */ if ((gapExt != delete) || (gapExt != insert)) { double[][] E = new double[query.length()+1][subject.length()+1]; // Inserts double[][] F = new double[query.length()+1][subject.length()+1]; // Deletes E[0][0] = F[0][0] = Double.MAX_VALUE; for (i=1; i<=query.length(); i++) { CostMatrix[i][0] = CostMatrix[i-1][0] + delete; E[i][0] = Double.POSITIVE_INFINITY; F[i][0] = delete + i*gapExt; } for (j=1; j<=subject.length(); j++) { CostMatrix[0][j] = CostMatrix[0][j-1] + insert; F[0][j] = Double.POSITIVE_INFINITY; E[0][j] = insert + j*gapExt; } for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { E[i][j] = Math.min(E[i][j-1], CostMatrix[i][j-1] + insert) + gapExt; F[i][j] = Math.min(F[i-1][j], CostMatrix[i-1][j] + delete) + gapExt; CostMatrix[i][j] = min(E[i][j], F[i][j], CostMatrix[i-1][j-1] - matchReplace(query, subject, i, j)); } /* * Traceback for affine gap penalties. */ try { boolean[] gap_extend = {false, false}; j = this.CostMatrix[CostMatrix.length - 1].length -1; SymbolTokenization st = subMatrix.getAlphabet().getTokenization("default"); for (i = this.CostMatrix.length - 1; i>0; ) { do { // only Insert. if (i == 0) { align[0] = '~' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // only Delete. } else if (j == 0) { align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '~' + align[1]; path = ' ' + path; // Match/Replace } else if ((CostMatrix[i][j] == CostMatrix[i-1][j-1] - matchReplace(query, subject, i, j)) && !(gap_extend[0] || gap_extend[1])) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert || finish gap if extended gap is opened } else if (CostMatrix[i][j] == E[i][j] || gap_extend[0]) { // check if gap has been extended or freshly opened gap_extend[0] = (E[i][j] != CostMatrix[i][j-1] + insert + gapExt); align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete || finish gap if extended gap is opened } else { // check if gap has been extended or freshly opened gap_extend[1] = (F[i][j] != CostMatrix[i-1][j] + delete + gapExt); align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * No affine gap penalties, constant gap penalties, which is much faster and needs less memory. */ } else { for (i=1; i<=query.length(); i++) CostMatrix[i][0] = CostMatrix[i-1][0] + delete; for (j=1; j<=subject.length(); j++) CostMatrix[0][j] = CostMatrix[0][j-1] + insert; for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { CostMatrix[i][j] = min ( CostMatrix[i-1][j] + delete, CostMatrix[i][j-1] + insert, CostMatrix[i-1][j-1] - matchReplace(query, subject, i, j)); } /* * Traceback for constant gap penalties. */ try { j = this.CostMatrix[CostMatrix.length - 1].length -1; SymbolTokenization st = subMatrix.getAlphabet().getTokenization("default"); //System.out.println(printCostMatrix(CostMatrix, query.seqString().toCharArray(), subject.seqString().toCharArray())); for (i = this.CostMatrix.length - 1; i>0; ) { do { // only Insert. if (i == 0) { align[0] = '~' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // only Delete. } else if (j == 0) { align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '~' + align[1]; path = ' ' + path; // Match/Replace } else if (CostMatrix[i][j] == CostMatrix[i-1][j-1] - matchReplace(query, subject, i, j)) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert } else if (CostMatrix[i][j] == CostMatrix[i][j-1] + insert) { align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete } else { align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } } /* * From here both cases are equal again. */ try { query = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(query.getAlphabet().getTokenization("token"), align[0]), query.getURN(), query.getName(), query.getAnnotation())); subject = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(subject.getAlphabet().getTokenization("token"), align[1]), subject.getURN(), subject.getName(), subject.getAnnotation())); Map m = new HashMap(); m.put(query.getName(), query); m.put(subject.getName(), subject); pairalign = new SimpleAlignment(m); // this.printCostMatrix(queryChar, targetChar); // only for tests important this.alignment = formatOutput( query.getName(), // name of the query sequence subject.getName(), // name of the target sequence align, // the String representation of the alignment path, // String match/missmatch representation 0, // Start position of the alignment in the query sequence CostMatrix.length-1, // End position of the alignment in the query sequence CostMatrix.length-1, // length of the query sequence 0, // Start position of the alignment in the target sequence CostMatrix[0].length-1, // End position of the alignment in the target sequence CostMatrix[0].length-1, // length of the target sequence getEditDistance(), // the edit distance System.currentTimeMillis() - time) + "\n"; // time consumption //System.out.println(printCostMatrix(CostMatrix, query.seqString().toCharArray(), subject.seqString().toCharArray())); return getEditDistance(); } catch (BioException exc) { throw new BioRuntimeException(exc); } } else throw new BioRuntimeException( "Alphabet missmatch occured: sequences with different alphabet cannot be aligned."); } /** This method computes the scores for the substution of the i-th symbol * of query by the j-th symbol of subject. * * @param query The query sequence * @param subject The target sequence * @param i The position of the symbol under consideration within the * query sequence (starting from one) * @param j The position of the symbol under consideration within the * target sequence * @return The score for the given substitution. */ private double matchReplace(Sequence query, Sequence subject, int i, int j) { try { return subMatrix.getValueAt(query.symbolAt(i), subject.symbolAt(j)); } catch (Exception exc) { if (query.symbolAt(i).getMatches().contains(subject.symbolAt(j)) || subject.symbolAt(j).getMatches().contains(query.symbolAt(i))) return -match; return -replace; } } }
package org.bouncycastle.cms; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import org.bouncycastle.asn1.ASN1Null; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; public abstract class RecipientInformation { protected RecipientId _rid = new RecipientId(); protected AlgorithmIdentifier _encAlg; protected AlgorithmIdentifier _keyEncAlg; protected InputStream _data; protected RecipientInformation( AlgorithmIdentifier encAlg, AlgorithmIdentifier keyEncAlg, InputStream data) { this._encAlg = encAlg; this._keyEncAlg = keyEncAlg; this._data = data; } public RecipientId getRID() { return _rid; } private byte[] encodeObj( DEREncodable obj) throws IOException { if (obj != null) { return obj.getDERObject().getEncoded(); } return null; } /** * return the object identifier for the key encryption algorithm. * @return OID for key encryption algorithm. */ public String getKeyEncryptionAlgOID() { return _keyEncAlg.getObjectId().getId(); } /** * return the ASN.1 encoded key encryption algorithm parameters, or null if * there aren't any. * @return ASN.1 encoding of key encryption algorithm parameters. */ public byte[] getKeyEncryptionAlgParams() { try { return encodeObj(_keyEncAlg.getParameters()); } catch (Exception e) { throw new RuntimeException("exception getting encryption parameters " + e); } } /** * Return an AlgorithmParameters object giving the encryption parameters * used to encrypt the key this recipient holds. * * @param provider the provider to generate the parameters for. * @return the parameters object, null if there is not one. * @throws CMSException if the algorithm cannot be found, or the parameters can't be parsed. * @throws NoSuchProviderException if the provider cannot be found. */ public AlgorithmParameters getKeyEncryptionAlgorithmParameters( String provider) throws CMSException, NoSuchProviderException { return getKeyEncryptionAlgorithmParameters(CMSUtils.getProvider(provider)); } /** * Return an AlgorithmParameters object giving the encryption parameters * used to encrypt the key this recipient holds. * * @param provider the provider to generate the parameters for. * @return the parameters object, null if there is not one. * @throws CMSException if the algorithm cannot be found, or the parameters can't be parsed. */ public AlgorithmParameters getKeyEncryptionAlgorithmParameters( Provider provider) throws CMSException { try { byte[] enc = this.encodeObj(_keyEncAlg.getParameters()); if (enc == null) { return null; } AlgorithmParameters params = CMSEnvelopedHelper.INSTANCE.createAlgorithmParameters(getKeyEncryptionAlgOID(), provider); params.init(enc, "ASN.1"); return params; } catch (NoSuchAlgorithmException e) { throw new CMSException("can't find parameters for algorithm", e); } catch (IOException e) { throw new CMSException("can't find parse parameters", e); } } protected CMSTypedStream getContentFromSessionKey( Key sKey, Provider provider) throws CMSException { String encAlg = _encAlg.getObjectId().getId(); try { Cipher cipher; cipher = CMSEnvelopedHelper.INSTANCE.getSymmetricCipher(encAlg, provider); ASN1Object sParams = (ASN1Object)_encAlg.getParameters(); if (sParams != null && !(sParams instanceof ASN1Null)) { AlgorithmParameters params = CMSEnvelopedHelper.INSTANCE.createAlgorithmParameters(encAlg, cipher.getProvider()); params.init(sParams.getEncoded(), "ASN.1"); cipher.init(Cipher.DECRYPT_MODE, sKey, params); } else { if (encAlg.equals(CMSEnvelopedDataGenerator.DES_EDE3_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.IDEA_CBC) || encAlg.equals(CMSEnvelopedDataGenerator.CAST5_CBC)) { cipher.init(Cipher.DECRYPT_MODE, sKey, new IvParameterSpec(new byte[8])); } else { cipher.init(Cipher.DECRYPT_MODE, sKey); } } return new CMSTypedStream(new CipherInputStream(_data, cipher)); } catch (NoSuchAlgorithmException e) { throw new CMSException("can't find algorithm.", e); } catch (InvalidKeyException e) { throw new CMSException("key invalid in message.", e); } catch (NoSuchPaddingException e) { throw new CMSException("required padding not supported.", e); } catch (InvalidAlgorithmParameterException e) { throw new CMSException("algorithm parameters invalid.", e); } catch (IOException e) { throw new CMSException("error decoding algorithm parameters.", e); } } public byte[] getContent( Key key, String provider) throws CMSException, NoSuchProviderException { return getContent(key, CMSUtils.getProvider(provider)); } public byte[] getContent( Key key, Provider provider) throws CMSException { try { if (_data instanceof ByteArrayInputStream) { _data.reset(); } return CMSUtils.streamToByteArray(getContentStream(key, provider).getContentStream()); } catch (IOException e) { throw new RuntimeException("unable to parse internal stream: " + e); } } public CMSTypedStream getContentStream(Key key, String provider) throws CMSException, NoSuchProviderException { return getContentStream(key, CMSUtils.getProvider(provider)); } public abstract CMSTypedStream getContentStream(Key key, Provider provider) throws CMSException; }
package com.aos.testbed; import java.util.concurrent.PriorityBlockingQueue; import com.aos.client.TestClient; import com.aos.common.QueueObject; import com.aos.server.TestServer; public class Test { public static void main(String args[]) { PriorityBlockingQueue<QueueObject> sharedQueue = new PriorityBlockingQueue<QueueObject>(); int[] node1Quorum = findQuorum(1,16); System.out.println("Initiating Sequence"); TestServer node1Server = new TestServer(1,sharedQueue,node1Quorum,true); TestClient node1Client = new TestClient(1,sharedQueue,node1Quorum,true); node1Server.start(); try { Thread.sleep(50*1000); } catch(Exception ex) { System.out.println(ex); } node1Client.start(); } private static int[] findQuorum(int myNodeId,int quorumSize) { int matrixRowSize = (int) Math.ceil(Math.sqrt(quorumSize)); int[][] nodeGrid = new int[matrixRowSize][matrixRowSize]; int row = 0,column = 0, nodeId = 1; int myRow = 0, myColumn = 0; for(int[] gridColumn : nodeGrid) { for(int gridItem : gridColumn) { nodeGrid[row][column] = nodeId; if(nodeId == myNodeId) {myRow = row;myColumn=column;} column++;nodeId++; } row++; column = 0; } int[] quorum = new int[(2 * matrixRowSize) - 1]; int j = 0; for(int i=0;i<2*matrixRowSize - 1;i = i+2) { quorum[i] = nodeGrid[j][myColumn]; if(nodeGrid[myRow][j] == myNodeId) i else quorum[i + 1] = nodeGrid[myRow][j]; j++; } return quorum; } }
package org.clapper.util.classutil; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class AndClassFilter implements ClassFilter { private List<ClassFilter> filters = new LinkedList<ClassFilter>(); /** * Construct a new <tt>AndClassFilter</tt> with no contained filters. */ public AndClassFilter() { } /** * Construct a new <tt>AndClassFilter</tt> with a set of contained * filters. Additional filters may be added later, via calls to the * {@link #addFilter addFilter()} method. * * @param filters filters to add */ public AndClassFilter (ClassFilter... filters) { for (ClassFilter filter : filters) addFilter (filter); } /** * Add a filter to the set of contained filters. * * @param filter the <tt>ClassFilter</tt> to add. * * @return this object, to permit chained calls. * * @see #removeFilter */ public AndClassFilter addFilter (ClassFilter filter) { filters.add (filter); return this; } /** * Remove a filter from the set of contained filters. * * @param filter the <tt>ClassFilter</tt> to remove. * * @see #addFilter */ public void removeFilter (ClassFilter filter) { filters.remove (filter); } /** * Get the contained filters, as an unmodifiable collection. * * @return the unmodifable <tt>Collection</tt> */ public Collection<ClassFilter> getFilters() { return Collections.unmodifiableCollection (filters); } /** * Get the total number of contained filter objects (not counting any * filter objects <i>they</i>, in turn, contain). * * @return the total */ public int getTotalFilters() { return filters.size(); } /** * <p>Determine whether a class name is to be accepted or not, based on * the contained filters. The class name is accepted if any one of the * contained filters accepts it. This method stops looping over the * contained filters as soon as it encounters one whose * {@link ClassFilter#accept accept()} method returns * <tt>false</tt> (implementing a "short-circuited AND" operation.)</p> * * <p>If the set of contained filters is empty, then this method * returns <tt>true</tt>.</p> * * @param className the class name * * @return <tt>true</tt> if the name matches, <tt>false</tt> if it doesn't */ public boolean accept (String className) { boolean accepted = true; for (ClassFilter filter : filters) { accepted = filter.accept (className); if (! accepted) break; } return accepted; } }
package org.exist.memtree; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; import org.exist.dom.NodeProxy; import org.exist.dom.QName; import org.exist.dom.StoredNode; import org.exist.util.serializer.AttrList; import org.exist.util.serializer.Receiver; import org.exist.xquery.XQueryContext; import java.util.HashMap; import java.util.Map; /** * Builds an in-memory DOM tree from SAX {@link org.exist.util.serializer.Receiver} events. * * @author Wolfgang <wolfgang@exist-db.org> */ public class DocumentBuilderReceiver implements ContentHandler, LexicalHandler, Receiver { private MemTreeBuilder builder = null; private Map<String, String> namespaces = null; private boolean explicitNSDecl = false; public boolean checkNS = false; public DocumentBuilderReceiver() { super(); } public DocumentBuilderReceiver(MemTreeBuilder builder) { this(builder, false); } public DocumentBuilderReceiver(MemTreeBuilder builder, boolean declareNamespaces) { super(); this.builder = builder; this.explicitNSDecl = declareNamespaces; } @Override public Document getDocument() { return builder.getDocument(); } public XQueryContext getContext() { return builder.getContext(); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ @Override public void setDocumentLocator(Locator locator) { } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startDocument() */ @Override public void startDocument() throws SAXException { if(builder == null) { builder = new MemTreeBuilder(); builder.startDocument(); } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endDocument() */ @Override public void endDocument() throws SAXException { builder.endDocument(); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ @Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { if(prefix == null || prefix.length() == 0) { builder.setDefaultNamespace(namespaceURI); } if (!explicitNSDecl) { return; } if(namespaces == null) { namespaces = new HashMap<String, String>(); } namespaces.put(prefix, namespaceURI); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ @Override public void endPrefixMapping(String prefix) throws SAXException { if(prefix == null || prefix.length() == 0) { builder.setDefaultNamespace(""); } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { builder.startElement(namespaceURI, localName, qName, attrs); declareNamespaces(); } private void declareNamespaces() { if (explicitNSDecl && namespaces != null) { for(Map.Entry<String, String> entry : namespaces.entrySet()) { builder.namespaceNode(entry.getKey(), entry.getValue()); } namespaces.clear(); } } @Override public void startElement(QName qname, AttrList attribs) { qname = checkNS(true, qname); builder.startElement(qname, null); declareNamespaces(); if (attribs != null) { for (int i = 0; i < attribs.getLength(); i++) { builder.addAttribute( attribs.getQName(i), attribs.getValue(i)); } } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { builder.endElement(); } @Override public void endElement(QName qname) throws SAXException { builder.endElement(); } public void addReferenceNode(NodeProxy proxy) throws SAXException { builder.addReferenceNode(proxy); } public void addNamespaceNode(QName qname) throws SAXException { builder.namespaceNode(qname); } @Override public void characters(CharSequence seq) throws SAXException { builder.characters(seq); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int len) throws SAXException { builder.characters(ch, start, len); } @Override public void attribute(QName qname, String value) throws SAXException { try { qname = checkNS(false, qname); builder.addAttribute(qname, value); } catch(DOMException e) { throw new SAXException(e.getMessage()); } } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @Override public void ignorableWhitespace(char[] ch, int start, int len) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ @Override public void processingInstruction(String target, String data) throws SAXException { builder.processingInstruction(target, data); } /* (non-Javadoc) * @see org.exist.util.serializer.Receiver#cdataSection(char[], int, int) */ @Override public void cdataSection(char[] ch, int start, int len) throws SAXException { builder.cdataSection(new String(ch, start, len)); } /* (non-Javadoc) * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ @Override public void skippedEntity(String arg0) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endCDATA() */ @Override public void endCDATA() throws SAXException { // TODO ignored } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endDTD() */ @Override public void endDTD() throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startCDATA() */ @Override public void startCDATA() throws SAXException { // TODO Ignored } @Override public void documentType(String name, String publicId, String systemId) throws SAXException { builder.documentType(name, publicId, systemId); } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int) */ @Override public void comment(char[] ch, int start, int length) throws SAXException { builder.comment(ch, start, length); } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) */ @Override public void endEntity(String name) throws SAXException{ } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) */ @Override public void startEntity(String name) throws SAXException { } /* (non-Javadoc) * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) */ @Override public void startDTD(String name, String publicId, String systemId) throws SAXException { } @Override public void highlightText(CharSequence seq) { // not supported with this receiver } @Override public void setCurrentNode(StoredNode node) { // ignored } public QName checkNS(boolean isElement, QName qname) { if(checkNS) { XQueryContext context = builder.getContext(); if(qname.getPrefix() == null) { if (qname.getNamespaceURI() == null || qname.getNamespaceURI().isEmpty()) { return qname; } else if (isElement) { return qname; } else { String prefix = generatePrfix(context, context.getInScopePrefix(qname.getNamespaceURI())); context.declareInScopeNamespace(prefix, qname.getNamespaceURI()); qname.setPrefix(prefix); return qname; } } if(qname.getPrefix().isEmpty() && qname.getNamespaceURI() == null) return qname; String inScopeNamespace = context.getInScopeNamespace(qname.getPrefix()); if(inScopeNamespace == null) { context.declareInScopeNamespace(qname.getPrefix(), qname.getNamespaceURI()); } else if(!inScopeNamespace.equals(qname.getNamespaceURI())) { String prefix = generatePrfix(context, context.getInScopePrefix(qname.getNamespaceURI())); context.declareInScopeNamespace(prefix, qname.getNamespaceURI()); qname.setPrefix(prefix); } } return qname; } private String generatePrfix(XQueryContext context, String prefix) { int i = 0; while (prefix == null) { prefix = "XXX"; if(i > 0) { prefix += String.valueOf(i); } if(context.getInScopeNamespace(prefix) != null) { prefix = null; i++; } } return prefix; } }
package org.connectbot.service; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.util.LinkedList; import java.util.List; import org.connectbot.R; import org.connectbot.TerminalView; import org.connectbot.bean.HostBean; import org.connectbot.bean.PortForwardBean; import org.connectbot.bean.PubkeyBean; import org.connectbot.bean.SelectionArea; import org.connectbot.util.HostDatabase; import org.connectbot.util.PubkeyDatabase; import org.connectbot.util.PubkeyUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.Bitmap.Config; import android.graphics.Paint.FontMetrics; import android.os.Vibrator; import android.text.ClipboardManager; import android.util.Log; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import com.trilead.ssh2.ChannelCondition; import com.trilead.ssh2.Connection; import com.trilead.ssh2.ConnectionInfo; import com.trilead.ssh2.ConnectionMonitor; import com.trilead.ssh2.DynamicPortForwarder; import com.trilead.ssh2.InteractiveCallback; import com.trilead.ssh2.KnownHosts; import com.trilead.ssh2.LocalPortForwarder; import com.trilead.ssh2.ServerHostKeyVerifier; import com.trilead.ssh2.Session; import com.trilead.ssh2.crypto.PEMDecoder; import de.mud.terminal.VDUBuffer; import de.mud.terminal.VDUDisplay; import de.mud.terminal.vt320; /** * Provides a bridge between a MUD terminal buffer and a possible TerminalView. * This separation allows us to keep the TerminalBridge running in a background * service. A TerminalView shares down a bitmap that we can use for rendering * when available. * * This class also provides SSH hostkey verification prompting, and password * prompting. */ public class TerminalBridge implements VDUDisplay, OnKeyListener, InteractiveCallback, ConnectionMonitor { public final static String TAG = TerminalBridge.class.toString(); private final static int BUFFER_SIZE = 4096; public final static int DEFAULT_FONT_SIZE = 10; public static final String AUTH_PUBLICKEY = "publickey", AUTH_PASSWORD = "password", AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive"; protected final static int AUTH_TRIES = 20; private List<PortForwardBean> portForwards = new LinkedList<PortForwardBean>(); public int color[]; public final static int COLOR_FG_STD = 7; public final static int COLOR_BG_STD = 0; protected final TerminalManager manager; public HostBean host; public final Connection connection; protected Session session; private final Paint defaultPaint; protected OutputStream stdin; protected InputStream stdout; private InputStream stderr; private Thread relay; private final String emulation; private final int scrollback; public Bitmap bitmap = null; public VDUBuffer buffer = null; private TerminalView parent = null; private final Canvas canvas = new Canvas(); private int metaState = 0; public final static int META_CTRL_ON = 0x01; public final static int META_CTRL_LOCK = 0x02; public final static int META_ALT_ON = 0x04; public final static int META_ALT_LOCK = 0x08; public final static int META_SHIFT_ON = 0x10; public final static int META_SHIFT_LOCK = 0x20; public final static int META_SLASH = 0x40; public final static int META_TAB = 0x80; // The bit mask of momentary and lock states for each public final static int META_CTRL_MASK = META_CTRL_ON | META_CTRL_LOCK; public final static int META_ALT_MASK = META_ALT_ON | META_ALT_LOCK; public final static int META_SHIFT_MASK = META_SHIFT_ON | META_SHIFT_LOCK; // All the transient key codes public final static int META_TRANSIENT = META_CTRL_ON | META_ALT_ON | META_SHIFT_ON; private boolean pubkeysExhausted = false; private boolean authenticated = false; private boolean sessionOpen = false; private boolean disconnected = false; private boolean awaitingClose = false; private boolean forcedSize = false; private int termWidth; private int termHeight; private String keymode = null; private boolean selectingForCopy = false; private final SelectionArea selectionArea; private ClipboardManager clipboard; protected KeyCharacterMap keymap = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); public int charWidth = -1; public int charHeight = -1; private int charTop = -1; private float fontSize = -1; private final List<FontSizeChangedListener> fontSizeChangedListeners; private final List<String> localOutput; /** * Flag indicating if we should perform a full-screen redraw during our next * rendering pass. */ private boolean fullRedraw = false; public PromptHelper promptHelper; protected BridgeDisconnectedListener disconnectListener = null; protected ConnectionInfo connectionInfo; /** * @author kenny * */ private final class Relay implements Runnable { final String encoding = host.getEncoding(); public void run() { final byte[] b = new byte[BUFFER_SIZE]; final byte[] tmpBuff = new byte[BUFFER_SIZE]; final Charset charset = Charset.forName(encoding); /* Set up character set decoder to report any byte sequences * which are malformed so we can try to resume decoding it * on the next packet received. * * UTF-8 byte sequences have a tendency to get truncated at * times. */ final CharsetDecoder cd = charset.newDecoder(); cd.onUnmappableCharacter(CodingErrorAction.REPLACE); cd.onMalformedInput(CodingErrorAction.REPORT); final CharsetDecoder replacer = charset.newDecoder(); replacer.onUnmappableCharacter(CodingErrorAction.REPLACE); replacer.onMalformedInput(CodingErrorAction.REPLACE); ByteBuffer bb; CharBuffer cb = CharBuffer.allocate(BUFFER_SIZE); int n = 0; int offset = 0; int conditions = ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.CLOSED | ChannelCondition.EOF; int newConditions = 0; while((newConditions & ChannelCondition.CLOSED) == 0) { try { newConditions = session.waitForCondition(conditions, 0); if ((newConditions & ChannelCondition.STDOUT_DATA) != 0) { while (stdout.available() > 0) { n = offset + stdout.read(b, offset, BUFFER_SIZE - offset); bb = ByteBuffer.wrap(b, 0, n); CoderResult cr = cd.decode(bb, cb, true); if (cr.isMalformed()) { int curpos = bb.position() - cr.length(); if (curpos > 0) { /* There is good data before the malformed section, so * pass this on immediately. */ ((vt320)buffer).putString(cb.array(), 0, cb.position()); } while (bb.position() < n) { bb = ByteBuffer.wrap(b, curpos, cr.length()); cb.clear(); replacer.decode(bb, cb, true); ((vt320) buffer).putString(cb.array(), 0, cb.position()); curpos += cr.length(); bb = ByteBuffer.wrap(b, curpos, n - curpos); cb.clear(); cr = cd.decode(bb, cb, true); } if (cr.isMalformed()) { /* If we still have malformed input, save the bytes for the next * read and try to parse it again. */ offset = n - bb.position() + cr.length(); if ((bb.position() - cr.length()) < offset) { System.arraycopy(b, bb.position() - cr.length(), tmpBuff, 0, offset); System.arraycopy(tmpBuff, 0, b, 0, offset); } else { System.arraycopy(b, bb.position() - cr.length(), b, 0, offset); } Log.d(TAG, String.format("Copying out %d chars at %d: 0x%02x", offset, bb.position() - cr.length(), b[bb.position() - cr.length()] )); } else { // After discarding the previous offset, we only have valid data. ((vt320)buffer).putString(cb.array(), 0, cb.position()); offset = 0; } } else { // No errors at all. ((vt320)buffer).putString(cb.array(), 0, cb.position()); offset = 0; } cb.clear(); } redraw(); } if ((newConditions & ChannelCondition.STDERR_DATA) != 0) { while (stderr.available() > 0) { n = stderr.read(b); bb = ByteBuffer.wrap(b, 0, n); replacer.decode(bb, cb, false); // TODO I don't know.. do we want this? We were ignoring it before Log.d(TAG, String.format("Read data from stderr: %s", new String(cb.array(), 0, cb.position()))); cb.clear(); } } if ((newConditions & ChannelCondition.EOF) != 0) { // The other side closed our channel, so let's disconnect. // TODO review whether any tunnel is in use currently. dispatchDisconnect(false); break; } } catch (IOException e) { Log.e(TAG, "Problem while handling incoming data in relay thread", e); break; } } } } public class HostKeyVerifier implements ServerHostKeyVerifier { public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException { // read in all known hosts from hostdb KnownHosts hosts = manager.hostdb.getKnownHosts(); Boolean result; String matchName = String.format("%s:%d", hostname, port); String fingerprint = KnownHosts.createHexFingerprint(serverHostKeyAlgorithm, serverHostKey); String algorithmName; if ("ssh-rsa".equals(serverHostKeyAlgorithm)) algorithmName = "RSA"; else if ("ssh-dss".equals(serverHostKeyAlgorithm)) algorithmName = "DSA"; else algorithmName = serverHostKeyAlgorithm; switch(hosts.verifyHostkey(matchName, serverHostKeyAlgorithm, serverHostKey)) { case KnownHosts.HOSTKEY_IS_OK: outputLine(String.format("Verified host %s key: %s", algorithmName, fingerprint)); return true; case KnownHosts.HOSTKEY_IS_NEW: // prompt user outputLine(String.format("The authenticity of host '%s' can't be established.", hostname)); outputLine(String.format("Host %s key fingerprint is %s", algorithmName, fingerprint)); result = promptHelper.requestBooleanPrompt("Are you sure you want\nto continue connecting?"); if(result == null) return false; if(result.booleanValue()) { // save this key in known database manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey); } return result.booleanValue(); case KnownHosts.HOSTKEY_HAS_CHANGED: outputLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); outputLine("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @"); outputLine("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); outputLine("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!"); outputLine("Someone could be eavesdropping on you right now (man-in-the-middle attack)!"); outputLine("It is also possible that the host key has just been changed."); outputLine(String.format("Host %s key fingerprint is %s", algorithmName, fingerprint)); // Users have no way to delete keys, so we'll prompt them for now. result = promptHelper.requestBooleanPrompt("Are you sure you want\nto continue connecting?"); if(result == null) return false; if(result.booleanValue()) { // save this key in known database manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey); } return result.booleanValue(); default: return false; } } } /** * Create new terminal bridge with following parameters. We will immediately * launch thread to start SSH connection and handle any hostkey verification * and password authentication. */ public TerminalBridge(final TerminalManager manager, final HostBean host) throws IOException { this.manager = manager; this.host = host; emulation = manager.getEmulation(); scrollback = manager.getScrollback(); // create prompt helper to relay password and hostkey requests up to gui promptHelper = new PromptHelper(this); // create our default paint defaultPaint = new Paint(); defaultPaint.setAntiAlias(true); defaultPaint.setTypeface(Typeface.MONOSPACE); defaultPaint.setFakeBoldText(true); // more readable? localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); setFontSize(DEFAULT_FONT_SIZE); // create terminal buffer and handle outgoing data // this is probably status reply information buffer = new vt320() { @Override public void write(byte[] b) { try { if (b != null && stdin != null) stdin.write(b); } catch (IOException e) { Log.e(TAG, "Problem handling incoming data in vt320() thread", e); } } // We don't use telnet sequences. @Override public void sendTelnetCommand(byte cmd) { } // We don't want remote to resize our window. @Override public void setWindowSize(int c, int r) { } }; buffer.setBufferSize(scrollback); resetColors(); buffer.setDisplay(this); selectionArea = new SelectionArea(); portForwards = manager.hostdb.getPortForwardsForHost(host); // prepare the ssh connection for opening // we perform the actual connection later in startConnection() outputLine(String.format("Connecting to %s:%d", host.getHostname(), host.getPort())); connection = new Connection(host.getHostname(), host.getPort()); connection.addConnectionMonitor(this); connection.setCompression(host.getCompression()); } /** * Spawn thread to open connection and start login process. */ protected void startConnection() { new Thread(new Runnable() { public void run() { try { connectionInfo = connection.connect(new HostKeyVerifier()); if (connectionInfo.clientToServerCryptoAlgorithm .equals(connectionInfo.serverToClientCryptoAlgorithm) && connectionInfo.clientToServerMACAlgorithm .equals(connectionInfo.serverToClientMACAlgorithm)) { outputLine(String.format("Using algorithm: %s %s", connectionInfo.clientToServerCryptoAlgorithm, connectionInfo.clientToServerMACAlgorithm)); } else { outputLine(String.format( "Client-to-server algorithm: %s %s", connectionInfo.clientToServerCryptoAlgorithm, connectionInfo.clientToServerMACAlgorithm)); outputLine(String.format( "Server-to-client algorithm: %s %s", connectionInfo.serverToClientCryptoAlgorithm, connectionInfo.serverToClientMACAlgorithm)); } } catch (IOException e) { Log.e(TAG, "Problem in SSH connection thread during authentication", e); // Display the reason in the text. outputLine(e.getCause().getMessage()); dispatchDisconnect(false); return; } try { // enter a loop to keep trying until authentication int tries = 0; while(!connection.isAuthenticationComplete() && tries++ < AUTH_TRIES && !disconnected) { handleAuthentication(); // sleep to make sure we dont kill system Thread.sleep(1000); } } catch(Exception e) { Log.e(TAG, "Problem in SSH connection thread during authentication", e); } } }).start(); } /** * Attempt connection with database row pointed to by cursor. * @param cursor * @return true for successful authentication * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws IOException */ private boolean tryPublicKey(PubkeyBean pubkey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException { Object trileadKey = null; if(manager.isKeyLoaded(pubkey.getNickname())) { // load this key from memory if its already there Log.d(TAG, String.format("Found unlocked key '%s' already in-memory", pubkey.getNickname())); trileadKey = manager.getKey(pubkey.getNickname()); } else { // otherwise load key from database and prompt for password as needed String password = null; if (pubkey.isEncrypted()) { password = promptHelper.requestStringPrompt(String.format("Password for key '%s'", pubkey.getNickname())); // Something must have interrupted the prompt. if (password == null) return false; } if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) { // load specific key using pem format trileadKey = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password); } else { // load using internal generated format PrivateKey privKey; try { privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType(), password); } catch (Exception e) { String message = String.format("Bad password for key '%s'. Authentication failed.", pubkey.getNickname()); Log.e(TAG, message, e); outputLine(message); return false; } PublicKey pubKey = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType()); // convert key to trilead format trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey); Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey)); } Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname())); // save this key in-memory if option enabled if(manager.isSavingKeys()) { manager.addKey(pubkey.getNickname(), trileadKey); } } return this.tryPublicKey(host.getUsername(), pubkey.getNickname(), trileadKey); } private boolean tryPublicKey(String username, String keyNickname, Object trileadKey) throws IOException { //outputLine(String.format("Attempting 'publickey' with key '%s' [%s]...", keyNickname, trileadKey.toString())); boolean success = connection.authenticateWithPublicKey(username, trileadKey); if(!success) outputLine(String.format("Authentication method 'publickey' with key '%s' failed", keyNickname)); return success; } protected void handleAuthentication() { try { if (connection.authenticateWithNone(host.getUsername())) { finishConnection(); return; } } catch(Exception e) { Log.d(TAG, "Host does not support 'none' authentication."); } outputLine("Trying to authenticate"); try { long pubkeyId = host.getPubkeyId(); if (!pubkeysExhausted && pubkeyId != HostDatabase.PUBKEYID_NEVER && connection.isAuthMethodAvailable(host.getUsername(), AUTH_PUBLICKEY)) { // if explicit pubkey defined for this host, then prompt for password as needed // otherwise just try all in-memory keys held in terminalmanager if (pubkeyId == HostDatabase.PUBKEYID_ANY) { // try each of the in-memory keys outputLine("Attempting 'publickey' authentication with any in-memory SSH keys"); for(String nickname : manager.loadedPubkeys.keySet()) { Object trileadKey = manager.loadedPubkeys.get(nickname); if(this.tryPublicKey(host.getUsername(), nickname, trileadKey)) { finishConnection(); break; } } } else { outputLine("Attempting 'publickey' authentication with a specific public key"); // use a specific key for this host, as requested PubkeyBean pubkey = manager.pubkeydb.findPubkeyById(pubkeyId); if (pubkey == null) outputLine("Selected public key is invalid, try reselecting key in host editor"); else if (tryPublicKey(pubkey)) finishConnection(); } pubkeysExhausted = true; } else if (connection.isAuthMethodAvailable(host.getUsername(), AUTH_PASSWORD)) { outputLine("Attempting 'password' authentication"); String password = promptHelper.requestStringPrompt("Password"); if (password != null && connection.authenticateWithPassword(host.getUsername(), password)) { finishConnection(); } else { outputLine("Authentication method 'password' failed"); } } else if(connection.isAuthMethodAvailable(host.getUsername(), AUTH_KEYBOARDINTERACTIVE)) { // this auth method will talk with us using InteractiveCallback interface // it blocks until authentication finishes outputLine("Attempting 'keyboard-interactive' authentication"); if(connection.authenticateWithKeyboardInteractive(host.getUsername(), TerminalBridge.this)) { finishConnection(); } else { outputLine("Authentication method 'keyboard-interactive' failed"); } } else { outputLine("[Your host doesn't support 'password' or 'keyboard-interactive' authentication.]"); } } catch(Exception e) { Log.e(TAG, "Problem during handleAuthentication()", e); } } /** * Handle challenges from keyboard-interactive authentication mode. */ public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) { String[] responses = new String[numPrompts]; for(int i = 0; i < numPrompts; i++) { // request response from user for each prompt responses[i] = promptHelper.requestStringPrompt(prompt[i]); } return responses; } /** * Convenience method for writing a line into the underlying MUD buffer. * Should never be called once the session is established. */ protected final void outputLine(String line) { if (session != null) Log.e(TAG, "Session established, cannot use outputLine!", new IOException("outputLine call traceback")); synchronized (localOutput) { final String s = line + "\r\n"; localOutput.add(s); ((vt320) buffer).putString(s); } } /** * Inject a specific string into this terminal. Used for post-login strings * and pasting clipboard. */ public void injectString(final String string) { new Thread(new Runnable() { public void run() { if(string == null || string.length() == 0) return; KeyEvent[] events = keymap.getEvents(string.toCharArray()); if(events == null || events.length == 0) return; for(KeyEvent event : events) { onKey(null, event.getKeyCode(), event); } } }).start(); } /** * Internal method to request actual PTY terminal once we've finished * authentication. If called before authenticated, it will just fail. */ private void finishConnection() { setAuthenticated(true); // Start up predefined port forwards for (PortForwardBean pfb : portForwards) { try { enablePortForward(pfb); outputLine(String.format("Enable port forward: %s", pfb.getDescription())); } catch (Exception e) { Log.e(TAG, "Error setting up port forward during connect", e); } } if (!host.getWantSession()) { outputLine("Session will not be started due to host preference."); return; } try { session = connection.openSession(); ((vt320) buffer).reset(); // We no longer need our local output. localOutput.clear(); // previously tried vt100 and xterm for emulation modes // "screen" works the best for color and escape codes // TODO: pull this value from the preferences ((vt320) buffer).setAnswerBack(emulation); session.requestPTY(emulation, termWidth, termHeight, 0, 0, null); session.startShell(); // grab stdin/out from newly formed session stdin = session.getStdin(); stdout = session.getStdout(); stderr = session.getStderr(); // create thread to relay incoming connection data to buffer relay = new Thread(new Relay()); relay.start(); // force font-size to make sure we resizePTY as needed setFontSize(fontSize); sessionOpen = true; // finally send any post-login string, if requested injectString(host.getPostLogin()); } catch (IOException e1) { Log.e(TAG, "Problem while trying to create PTY in finishConnection()", e1); } } /** * @return whether a session is open or not */ public boolean isSessionOpen() { return sessionOpen; } public void setOnDisconnectedListener(BridgeDisconnectedListener disconnectListener) { this.disconnectListener = disconnectListener; } /** * Force disconnection of this terminal bridge. */ public void dispatchDisconnect(boolean immediate) { // We don't need to do this multiple times. if (disconnected && !immediate) return; // disconnection request hangs if we havent really connected to a host yet // temporary fix is to just spawn disconnection into a thread new Thread(new Runnable() { public void run() { if(session != null) session.close(); connection.close(); } }).start(); disconnected = true; authenticated = false; sessionOpen = false; if (immediate) { awaitingClose = true; if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } else { new Thread(new Runnable() { public void run() { Boolean result = promptHelper.requestBooleanPrompt("Host has disconnected.\nClose session?", true); if (result == null || result.booleanValue()) { awaitingClose = true; // Tell the TerminalManager that we can be destroyed now. if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } } }).start(); } } public void refreshKeymode() { keymode = manager.getKeyMode(); } private boolean bumpyArrows = false; public Vibrator vibrator = null; public static final long VIBRATE_DURATION = 30; /** * Handle onKey() events coming down from a {@link TerminalView} above us. * We might collect these for our internal buffer when working with hostkeys * or passwords, but otherwise we pass them directly over to the SSH host. */ public boolean onKey(View v, int keyCode, KeyEvent event) { try { // Ignore all key-up events except for the special keys if (event.getAction() == KeyEvent.ACTION_UP) { // skip keys if we aren't connected yet or have been disconnected if (disconnected || session == null) return false; if ("Use right-side keys".equals(keymode)) { if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT && (metaState & META_SLASH) != 0) { metaState &= metaState ^ META_SLASH ^ META_TRANSIENT; stdin.write('/'); return true; } else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT && (metaState & META_TAB) != 0) { metaState &= metaState ^ META_TAB ^ META_TRANSIENT; stdin.write(0x09); return true; } } else if ("Use left-side keys".equals(keymode)) { if (keyCode == KeyEvent.KEYCODE_ALT_LEFT && (metaState & META_SLASH) != 0) { metaState &= metaState ^ META_SLASH ^ META_TRANSIENT; stdin.write('/'); return true; } else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT && (metaState & META_TAB) != 0) { metaState &= metaState ^ META_TAB ^ META_TRANSIENT; stdin.write(0x09); return true; } } return false; } // check for terminal resizing keys if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { forcedSize = false; setFontSize(fontSize + 2); return true; } else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { forcedSize = false; setFontSize(fontSize - 2); return true; } // skip keys if we aren't connected yet or have been disconnected if (disconnected || session == null) return false; // if we're in scrollback, scroll to bottom of window on input if (buffer.windowBase != buffer.screenBase) buffer.setWindowBase(buffer.screenBase); boolean printing = (keymap.isPrintingKey(keyCode) || keyCode == KeyEvent.KEYCODE_SPACE); // otherwise pass through to existing session // print normal keys if (printing) { int curMetaState = event.getMetaState(); metaState &= metaState ^ META_SLASH ^ META_TAB; if ((metaState & META_SHIFT_MASK) != 0) { curMetaState |= KeyEvent.META_SHIFT_ON; metaState &= metaState ^ META_SHIFT_ON; redraw(); } if ((metaState & META_ALT_MASK) != 0) { curMetaState |= KeyEvent.META_ALT_ON; metaState &= metaState ^ META_ALT_ON; redraw(); } int key = keymap.get(keyCode, curMetaState); if ((metaState & META_CTRL_MASK) != 0) { // Support CTRL-a through CTRL-z if (key >= 0x61 && key <= 0x7A) key -= 0x60; // Support CTRL-A through CTRL-_ else if (key >= 0x41 && key <= 0x5F) key -= 0x40; else if (key == 0x20) key = 0x00; metaState &= metaState ^ META_CTRL_ON; redraw(); } // handle pressing f-keys if ((curMetaState & KeyEvent.META_SHIFT_ON) != 0) { switch(key) { case '!': ((vt320)buffer).keyPressed(vt320.KEY_F1, ' ', 0); return true; case '@': ((vt320)buffer).keyPressed(vt320.KEY_F2, ' ', 0); return true; case '#': ((vt320)buffer).keyPressed(vt320.KEY_F3, ' ', 0); return true; case '$': ((vt320)buffer).keyPressed(vt320.KEY_F4, ' ', 0); return true; case '%': ((vt320)buffer).keyPressed(vt320.KEY_F5, ' ', 0); return true; case '^': ((vt320)buffer).keyPressed(vt320.KEY_F6, ' ', 0); return true; case '&': ((vt320)buffer).keyPressed(vt320.KEY_F7, ' ', 0); return true; case '*': ((vt320)buffer).keyPressed(vt320.KEY_F8, ' ', 0); return true; case '(': ((vt320)buffer).keyPressed(vt320.KEY_F9, ' ', 0); return true; case ')': ((vt320)buffer).keyPressed(vt320.KEY_F10, ' ', 0); return true; } } stdin.write(key); return true; } // try handling keymode shortcuts if("Use right-side keys".equals(keymode)) { switch(keyCode) { case KeyEvent.KEYCODE_ALT_RIGHT: metaState |= META_SLASH; return true; case KeyEvent.KEYCODE_SHIFT_RIGHT: metaState |= META_TAB; return true; case KeyEvent.KEYCODE_SHIFT_LEFT: metaPress(META_SHIFT_ON); return true; case KeyEvent.KEYCODE_ALT_LEFT: metaPress(META_ALT_ON); return true; default: break; } } else if("Use left-side keys".equals(keymode)) { switch(keyCode) { case KeyEvent.KEYCODE_ALT_LEFT: metaState |= META_SLASH; return true; case KeyEvent.KEYCODE_SHIFT_LEFT: metaState |= META_TAB; return true; case KeyEvent.KEYCODE_SHIFT_RIGHT: metaPress(META_SHIFT_ON); return true; case KeyEvent.KEYCODE_ALT_RIGHT: metaPress(META_ALT_ON); return true; default: break; } } // look for special chars switch(keyCode) { case KeyEvent.KEYCODE_CAMERA: // check to see which shortcut the camera button triggers String camera = manager.prefs.getString(manager.res.getString(R.string.pref_camera), manager.res.getString(R.string.list_camera_ctrlaspace)); if(manager.res.getString(R.string.list_camera_ctrlaspace).equals(camera)) { stdin.write(0x01); stdin.write(' '); } else if(manager.res.getString(R.string.list_camera_ctrla).equals(camera)) { stdin.write(0x01); } else if(manager.res.getString(R.string.list_camera_esc).equals(camera)) { ((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0); } break; case KeyEvent.KEYCODE_DEL: ((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ', getStateForBuffer()); metaState &= metaState ^ META_TRANSIENT; return true; case KeyEvent.KEYCODE_ENTER: ((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0); metaState &= metaState ^ META_TRANSIENT; return true; case KeyEvent.KEYCODE_DPAD_LEFT: if (selectingForCopy) { if (selectionArea.isSelectingOrigin()) selectionArea.decrementLeft(); else selectionArea.decrementRight(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ', getStateForBuffer()); metaState &= metaState ^ META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_UP: if (selectingForCopy) { if (selectionArea.isSelectingOrigin()) selectionArea.decrementTop(); else selectionArea.decrementBottom(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_UP, ' ', getStateForBuffer()); metaState &= metaState ^ META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_DOWN: if (selectingForCopy) { if (selectionArea.isSelectingOrigin()) selectionArea.incrementTop(); else selectionArea.incrementBottom(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ', getStateForBuffer()); metaState &= metaState ^ META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (selectingForCopy) { if (selectionArea.isSelectingOrigin()) selectionArea.incrementLeft(); else selectionArea.incrementRight(); redraw(); } else { ((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ', getStateForBuffer()); metaState &= metaState ^ META_TRANSIENT; tryKeyVibrate(); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: if (selectingForCopy) { if (selectionArea.isSelectingOrigin()) selectionArea.finishSelectingOrigin(); else { if (parent != null && clipboard != null) { // copy selected area to clipboard String copiedText = selectionArea.copyFrom(buffer); clipboard.setText(copiedText); parent.notifyUser(parent.getContext().getString( R.string.console_copy_done, copiedText.length())); selectingForCopy = false; selectionArea.reset(); } } } else { if ((metaState & META_CTRL_ON) != 0) { ((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0); metaState &= metaState ^ META_CTRL_ON; } else metaState |= META_CTRL_ON; } redraw(); return true; } } catch (IOException e) { Log.e(TAG, "Problem while trying to handle an onKey() event", e); try { stdin.flush(); } catch (IOException ioe) { // Our stdin got blown away, so we must be closed. Log.d(TAG, "Our stdin was closed, dispatching disconnect event"); dispatchDisconnect(false); } } catch (NullPointerException npe) { Log.d(TAG, "Input before connection established ignored."); return true; } return false; } /** * Handle meta key presses where the key can be locked on. * <p> * 1st press: next key to have meta state<br /> * 2nd press: meta state is locked on<br /> * 3rd press: disable meta state * * @param code */ private void metaPress(int code) { if ((metaState & (code << 1)) != 0) { metaState &= metaState ^ (code << 1); } else if ((metaState & code) != 0) { metaState &= metaState ^ code; metaState |= code << 1; } else metaState |= code; redraw(); } public int getMetaState() { return metaState; } private int getStateForBuffer() { int bufferState = 0; if ((metaState & META_CTRL_MASK) != 0) bufferState |= vt320.KEY_CONTROL; if ((metaState & META_SHIFT_MASK) != 0) bufferState |= vt320.KEY_SHIFT; if ((metaState & META_ALT_MASK) != 0) bufferState |= vt320.KEY_ALT; return bufferState; } public void setSelectingForCopy(boolean selectingForCopy) { this.selectingForCopy = selectingForCopy; } public boolean isSelectingForCopy() { return selectingForCopy; } public SelectionArea getSelectionArea() { return selectionArea; } public synchronized void tryKeyVibrate() { if (bumpyArrows && vibrator != null) vibrator.vibrate(VIBRATE_DURATION); } /** * Request a different font size. Will make call to parentChanged() to make * sure we resize PTY if needed. */ private final void setFontSize(float size) { if (size <= 0.0) return; defaultPaint.setTextSize(size); fontSize = size; // read new metrics to get exact pixel dimensions FontMetrics fm = defaultPaint.getFontMetrics(); charTop = (int)Math.ceil(fm.top); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); charWidth = (int)Math.ceil(widths[0]); charHeight = (int)Math.ceil(fm.descent - fm.top); // refresh any bitmap with new font size if(parent != null) parentChanged(parent); for (FontSizeChangedListener ofscl : fontSizeChangedListeners) ofscl.onFontSizeChanged(size); } /** * Add an {@link FontSizeChangedListener} to the list of listeners for this * bridge. * * @param listener * listener to add */ public void addFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.add(listener); } /** * Remove an {@link FontSizeChangedListener} from the list of listeners for * this bridge. * * @param listener */ public void removeFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.remove(listener); } /** * Something changed in our parent {@link TerminalView}, maybe it's a new * parent, or maybe it's an updated font size. We should recalculate * terminal size information and request a PTY resize. */ public final synchronized void parentChanged(TerminalView parent) { this.parent = parent; int width = parent.getWidth(); int height = parent.getHeight(); bumpyArrows = manager.prefs.getBoolean(manager.res.getString(R.string.pref_bumpyarrows), true); vibrator = (Vibrator) parent.getContext().getSystemService(Context.VIBRATOR_SERVICE); clipboard = (ClipboardManager) parent.getContext().getSystemService(Context.CLIPBOARD_SERVICE); if (!forcedSize) { // recalculate buffer size int newTermWidth, newTermHeight; newTermWidth = width / charWidth; newTermHeight = height / charHeight; // If nothing has changed in the terminal dimensions and not an intial // draw then don't blow away scroll regions and such. if (newTermWidth == termWidth && newTermHeight == termHeight) return; termWidth = newTermWidth; termHeight = newTermHeight; } // reallocate new bitmap if needed boolean newBitmap = (bitmap == null); if(bitmap != null) newBitmap = (bitmap.getWidth() != width || bitmap.getHeight() != height); if (newBitmap) { if (bitmap != null) bitmap.recycle(); bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); canvas.setBitmap(bitmap); } // clear out any old buffer information defaultPaint.setColor(Color.BLACK); canvas.drawPaint(defaultPaint); // Stroke the border of the terminal if the size is being forced; if (forcedSize) { int borderX = (termWidth * charWidth) + 1; int borderY = (termHeight * charHeight) + 1; defaultPaint.setColor(Color.GRAY); defaultPaint.setStrokeWidth(0.0f); if (width >= borderX) canvas.drawLine(borderX, 0, borderX, borderY + 1, defaultPaint); if (height >= borderY) canvas.drawLine(0, borderY, borderX + 1, borderY, defaultPaint); } try { // request a terminal pty resize int prevRow = buffer.getCursorRow(); buffer.setScreenSize(termWidth, termHeight, true); // Work around weird vt320.java behavior where cursor is an offset from the bottom?? buffer.setCursorPosition(buffer.getCursorColumn(), prevRow); if(session != null) session.resizePTY(termWidth, termHeight, width, height); } catch(Exception e) { Log.e(TAG, "Problem while trying to resize screen or PTY", e); } // redraw local output if we don't have a sesson to receive our resize request if (session == null) { synchronized (localOutput) { ((vt320) buffer).reset(); for (String line : localOutput) ((vt320) buffer).putString(line); } } // force full redraw with new buffer size fullRedraw = true; redraw(); parent.notifyUser(String.format("%d x %d", termWidth, termHeight)); Log.i(TAG, String.format("parentChanged() now width=%d, height=%d", termWidth, termHeight)); } /** * Somehow our parent {@link TerminalView} was destroyed. Now we don't need * to redraw anywhere, and we can recycle our internal bitmap. */ public synchronized void parentDestroyed() { parent = null; canvas.setBitmap(null); if (bitmap != null) bitmap.recycle(); bitmap = null; } public void setVDUBuffer(VDUBuffer buffer) { this.buffer = buffer; } public VDUBuffer getVDUBuffer() { return buffer; } public void onDraw() { int fg, bg; boolean entireDirty = buffer.update[0] || fullRedraw; // walk through all lines in the buffer for(int l = 0; l < buffer.height; l++) { // check if this line is dirty and needs to be repainted // also check for entire-buffer dirty flags if (!entireDirty && !buffer.update[l + 1]) continue; // reset dirty flag for this line buffer.update[l + 1] = false; // walk through all characters in this line for (int c = 0; c < buffer.width; c++) { int addr = 0; int currAttr = buffer.charAttributes[buffer.windowBase + l][c]; // reset default colors fg = color[COLOR_FG_STD]; bg = color[COLOR_BG_STD]; // check if foreground color attribute is set if ((currAttr & VDUBuffer.COLOR_FG) != 0) { int fgcolor = ((currAttr & VDUBuffer.COLOR_FG) >> VDUBuffer.COLOR_FG_SHIFT) - 1; if (fgcolor < 8 && (currAttr & VDUBuffer.BOLD) != 0) fg = color[fgcolor + 8]; else fg = color[fgcolor]; } // check if background color attribute is set if ((currAttr & VDUBuffer.COLOR_BG) != 0) bg = color[((currAttr & VDUBuffer.COLOR_BG) >> VDUBuffer.COLOR_BG_SHIFT) - 1]; // support character inversion by swapping background and foreground color if ((currAttr & VDUBuffer.INVERT) != 0) { int swapc = bg; bg = fg; fg = swapc; } // set underlined attributes if requested defaultPaint.setUnderlineText((currAttr & VDUBuffer.UNDERLINE) != 0); // determine the amount of continuous characters with the same settings and print them all at once while(c + addr < buffer.width && buffer.charAttributes[buffer.windowBase + l][c + addr] == currAttr) { addr++; } // Save the current clip region canvas.save(Canvas.CLIP_SAVE_FLAG); // clear this dirty area with background color defaultPaint.setColor(bg); canvas.clipRect(c * charWidth, l * charHeight, (c + addr) * charWidth, (l + 1) * charHeight); canvas.drawPaint(defaultPaint); // write the text string starting at 'c' for 'addr' number of characters defaultPaint.setColor(fg); if((currAttr & VDUBuffer.INVISIBLE) == 0) canvas.drawText(buffer.charArray[buffer.windowBase + l], c, addr, c * charWidth, (l * charHeight) - charTop, defaultPaint); // Restore the previous clip region canvas.restore(); // advance to the next text block with different characteristics c += addr - 1; } } // reset entire-buffer flags buffer.update[0] = false; fullRedraw = false; } public void redraw() { if (parent != null) parent.postInvalidate(); } // We don't have a scroll bar. public void updateScrollBar() { } public void connectionLost(Throwable reason) { // weve lost our ssh connection, so pass along to manager and gui Log.e(TAG, "Somehow our underlying SSH socket died", reason); dispatchDisconnect(false); } /** * Resize terminal to fit [rows]x[cols] in screen of size [width]x[height] * @param rows * @param cols * @param width * @param height */ public synchronized void resizeComputed(int cols, int rows, int width, int height) { float size = 8.0f; float step = 8.0f; float limit = 0.125f; int direction; while ((direction = fontSizeCompare(size, cols, rows, width, height)) < 0) size += step; if (direction == 0) { Log.d("fontsize", String.format("Found match at %f", size)); return; } step /= 2.0f; size -= step; while ((direction = fontSizeCompare(size, cols, rows, width, height)) != 0 && step >= limit) { step /= 2.0f; if (direction > 0) { size -= step; } else { size += step; } } if (direction > 0) size -= step; forcedSize = true; termWidth = cols; termHeight = rows; setFontSize(size); } private int fontSizeCompare(float size, int cols, int rows, int width, int height) { // read new metrics to get exact pixel dimensions defaultPaint.setTextSize(size); FontMetrics fm = defaultPaint.getFontMetrics(); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); int termWidth = (int)widths[0] * cols; int termHeight = (int)Math.ceil(fm.descent - fm.top) * rows; Log.d("fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight)); // Check to see if it fits in resolution specified. if (termWidth > width || termHeight > height) return 1; if (termWidth == width || termHeight == height) return 0; return -1; } /** * Adds the {@link PortForwardBean} to the list. * @param portForward the port forward bean to add * @return true on successful addition */ public boolean addPortForward(PortForwardBean portForward) { return portForwards.add(portForward); } /** * Removes the {@link PortForwardBean} from the list. * @param portForward the port forward bean to remove * @return true on successful removal */ public boolean removePortForward(PortForwardBean portForward) { // Make sure we don't have a phantom forwarder. disablePortForward(portForward); return portForwards.remove(portForward); } /** * @return the list of port forwards */ public List<PortForwardBean> getPortForwards() { return portForwards; } /** * Enables a port forward member. After calling this method, the port forward should * be operational. * @param portForward member of our current port forwards list to enable * @return true on successful port forward setup */ public boolean enablePortForward(PortForwardBean portForward) { if (!portForwards.contains(portForward)) { Log.e(TAG, "Attempt to enable port forward not in list"); return false; } if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) { LocalPortForwarder lpf = null; try { lpf = connection.createLocalPortForwarder(portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort()); } catch (IOException e) { Log.e(TAG, "Could not create local port forward", e); return false; } if (lpf == null) { Log.e(TAG, "returned LocalPortForwarder object is null"); return false; } portForward.setIdentifier(lpf); portForward.setEnabled(true); return true; } else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) { try { connection.requestRemotePortForwarding("", portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort()); } catch (IOException e) { Log.e(TAG, "Could not create remote port forward", e); return false; } portForward.setEnabled(false); return true; } else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) { DynamicPortForwarder dpf = null; try { dpf = connection.createDynamicPortForwarder(portForward.getSourcePort()); } catch (IOException e) { Log.e(TAG, "Could not create dynamic port forward", e); return false; } portForward.setIdentifier(dpf); portForward.setEnabled(true); return true; } else { // Unsupported type Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType())); return false; } } /** * Disables a port forward member. After calling this method, the port forward should * be non-functioning. * @param portForward member of our current port forwards list to enable * @return true on successful port forward tear-down */ public boolean disablePortForward(PortForwardBean portForward) { if (!portForwards.contains(portForward)) { Log.e(TAG, "Attempt to disable port forward not in list"); return false; } if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) { LocalPortForwarder lpf = null; lpf = (LocalPortForwarder)portForward.getIdentifier(); if (!portForward.isEnabled() || lpf == null) { Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname())); return false; } portForward.setEnabled(false); try { lpf.close(); } catch (IOException e) { Log.e(TAG, "Could not stop local port forwarder, setting enabled to false", e); return false; } return true; } else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) { portForward.setEnabled(false); try { connection.cancelRemotePortForwarding(portForward.getSourcePort()); } catch (IOException e) { Log.e(TAG, "Could not stop remote port forwarding, setting enabled to false", e); return false; } return true; } else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) { DynamicPortForwarder dpf = null; dpf = (DynamicPortForwarder)portForward.getIdentifier(); if (!portForward.isEnabled() || dpf == null) { Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname())); return false; } portForward.setEnabled(false); try { dpf.close(); } catch (IOException e) { Log.e(TAG, "Could not stop dynamic port forwarder, setting enabled to false", e); return false; } return true; } else { // Unsupported type Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType())); return false; } } /** * @param authenticated the authenticated to set */ public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; } /** * @return the authenticated */ public boolean isAuthenticated() { return authenticated; } /** * @return whether the TerminalBridge should close */ public boolean isAwaitingClose() { return awaitingClose; } /** * @return whether this connection had started and subsequently disconnected */ public boolean isDisconnected() { return disconnected; } /* (non-Javadoc) * @see de.mud.terminal.VDUDisplay#setColor(byte, byte, byte, byte) */ public void setColor(int index, int red, int green, int blue) { // Don't allow the system colors to be overwritten for now. May violate specs. if (index < color.length && index >= 16) color[index] = 0xff000000 | red << 16 | green << 8 | blue; } public final void resetColors() { color = new int[] { 0xff000000, // black 0xffcc0000, // red 0xff00cc00, // green 0xffcccc00, // brown 0xff0000cc, // blue 0xffcc00cc, // purple 0xff00cccc, // cyan 0xffcccccc, // light grey 0xff444444, // dark grey 0xffff4444, // light red 0xff44ff44, // light green 0xffffff44, // yellow 0xff4444ff, // light blue 0xffff44ff, // light purple 0xff44ffff, // light cyan 0xffffffff, // white 0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7, 0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf, 0xff005fd7, 0xff005fff, 0xff008700, 0xff00875f, 0xff008787, 0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f, 0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff, 0xff00d700, 0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff, 0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7, 0xff00ffff, 0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af, 0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87, 0xff5f5faf, 0xff5f5fd7, 0xff5f5fff, 0xff5f8700, 0xff5f875f, 0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00, 0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff, 0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7, 0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf, 0xff5fffd7, 0xff5fffff, 0xff870000, 0xff87005f, 0xff870087, 0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f, 0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff, 0xff878700, 0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff, 0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7, 0xff87afff, 0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af, 0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87, 0xff87ffaf, 0xff87ffd7, 0xff87ffff, 0xffaf0000, 0xffaf005f, 0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00, 0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff, 0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7, 0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf, 0xffafafd7, 0xffafafff, 0xffafd700, 0xffafd75f, 0xffafd787, 0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f, 0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff, 0xffd70000, 0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff, 0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7, 0xffd75fff, 0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af, 0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87, 0xffd7afaf, 0xffd7afd7, 0xffd7afff, 0xffd7d700, 0xffd7d75f, 0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00, 0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff, 0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7, 0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf, 0xffff5fd7, 0xffff5fff, 0xffff8700, 0xffff875f, 0xffff8787, 0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f, 0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff, 0xffffd700, 0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff, 0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7, 0xffffffff, 0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626, 0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858, 0xff626262, 0xff6c6c6c, 0xff767676, 0xff808080, 0xff8a8a8a, 0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc, 0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee, }; } }
package org.helioviewer.jhv.astronomy; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import javax.swing.border.Border; import org.helioviewer.jhv.base.Colors; import org.helioviewer.jhv.gui.components.base.JHVTableCellRenderer; import com.google.common.collect.ImmutableMap; public class SpaceObject { private final String urlName; private final String name; private final double radius; private final byte[] color; private final Border border; public static final SpaceObject Sol = new SpaceObject("SUN", "Sun", 1, Colors.Yellow, JHVTableCellRenderer.cellEmphasisBorder); private static final ImmutableMap<String, SpaceObject> objectMap = new ImmutableMap.Builder<String, SpaceObject>(). put("Sun", Sol). put("Mercury", new SpaceObject("Mercury", "Mercury", 2439700 / Sun.RadiusMeter, Colors.Gray, JHVTableCellRenderer.cellBorder)). put("Venus", new SpaceObject("Venus", "Venus", 6051800 / Sun.RadiusMeter, Colors.bytes(181, 110, 26), JHVTableCellRenderer.cellBorder)). put("Earth", new SpaceObject("Earth", "Earth", 6371000 / Sun.RadiusMeter, Colors.Blue, JHVTableCellRenderer.cellBorder)). put("Moon", new SpaceObject("Moon", "Moon", 1737400 / Sun.RadiusMeter, Colors.LightGray, JHVTableCellRenderer.cellBorder)). put("Mars", new SpaceObject("Mars%20Barycenter", "Mars", 3389500 / Sun.RadiusMeter, Colors.bytes(135, 37, 18), JHVTableCellRenderer.cellBorder)). put("Jupiter", new SpaceObject("Jupiter%20Barycenter", "Jupiter", 69911000 / Sun.RadiusMeter, Colors.bytes(168, 172, 180), JHVTableCellRenderer.cellBorder)). put("Saturn", new SpaceObject("Saturn%20Barycenter", "Saturn", 58232000 / Sun.RadiusMeter, Colors.bytes(208, 198, 173), JHVTableCellRenderer.cellBorder)). put("Uranus", new SpaceObject("Uranus%20Barycenter", "Uranus", 25362000 / Sun.RadiusMeter, Colors.bytes(201, 239, 242), JHVTableCellRenderer.cellBorder)). put("Neptune", new SpaceObject("Neptune%20Barycenter", "Neptune", 24622000 / Sun.RadiusMeter, Colors.bytes(124, 157, 226), JHVTableCellRenderer.cellBorder)). put("Pluto", new SpaceObject("Pluto%20Barycenter", "Pluto", 1195000 / Sun.RadiusMeter, Colors.bytes(205, 169, 140), JHVTableCellRenderer.cellEmphasisBorder)). put("Comet 67P", new SpaceObject("CHURYUMOV-GERASIMENKO", "Comet 67P", 2200 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellEmphasisBorder)). put("SOHO", new SpaceObject("SOHO", "SOHO", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). put("STEREO Ahead", new SpaceObject("STEREO%20Ahead", "STEREO Ahead", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). put("STEREO Behind", new SpaceObject("STEREO%20Behind", "STEREO Behind", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). put("PROBA-2", new SpaceObject("PROBA2", "PROBA-2", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). put("SDO", new SpaceObject("SDO", "SDO", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellEmphasisBorder)). put("Solar Orbiter", new SpaceObject("Solar%20Orbiter", "Solar Orbiter", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). put("Parker Solar Probe", new SpaceObject("PSP", "Parker Solar Probe", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). put("PROBA-3", new SpaceObject("PROBA3", "PROBA-3", 2 / Sun.RadiusMeter, Colors.White, JHVTableCellRenderer.cellBorder)). build(); public static List<SpaceObject> getTargets(SpaceObject observer) { ArrayList<SpaceObject> list = new ArrayList<>(objectMap.values()); list.remove(observer); return list; } @Nullable public static SpaceObject get(String obj) { return objectMap.get(obj); } private SpaceObject(String _urlName, String _name, double _radius, byte[] _color, Border _border) { urlName = _urlName; name = _name; radius = _radius; color = _color; border = _border; } public String getUrlName() { return urlName; } public double getRadius() { return radius; } public byte[] getColor() { return color; } public Border getBorder() { return border; } @Override public boolean equals(Object o) { if (!(o instanceof SpaceObject)) return false; SpaceObject r = (SpaceObject) o; return urlName.equals(r.urlName); } @Override public int hashCode() { return urlName.hashCode(); } @Override public String toString() { return name; } }
package verification.platu.stategraph; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.common.IndexObjMap; import verification.platu.logicAnalysis.Constraint; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LpnTranList; import verification.platu.main.Main; import verification.platu.main.Options; import verification.platu.project.PrjState; public class StateGraph { protected State init = null; protected IndexObjMap<State> stateCache; protected IndexObjMap<State> localStateCache; protected HashMap<State, State> state2LocalMap; protected HashMap<State, LpnTranList> enabledSetTbl; protected HashMap<State, HashMap<Transition, State>> nextStateMap; protected List<State> stateSet = new LinkedList<State>(); protected List<State> frontierStateSet = new LinkedList<State>(); protected List<State> entryStateSet = new LinkedList<State>(); protected List<Constraint> oldConstraintSet = new LinkedList<Constraint>(); protected List<Constraint> newConstraintSet = new LinkedList<Constraint>(); protected List<Constraint> frontierConstraintSet = new LinkedList<Constraint>(); protected Set<Constraint> constraintSet = new HashSet<Constraint>(); protected LhpnFile lpn; public StateGraph(LhpnFile lpn) { this.lpn = lpn; this.stateCache = new IndexObjMap<State>(); this.localStateCache = new IndexObjMap<State>(); this.state2LocalMap = new HashMap<State, State>(); this.enabledSetTbl = new HashMap<State, LpnTranList>(); this.nextStateMap = new HashMap<State, HashMap<Transition, State>>(); } public LhpnFile getLpn(){ return this.lpn; } public void printStates(){ System.out.println(String.format("%-8s %5s", this.lpn.getLabel(), "|States| = " + stateCache.size())); } public Set<Transition> getTranList(State currentState){ return this.nextStateMap.get(currentState).keySet(); } /** * Finds reachable states from the given state. * Also generates new constraints from the state transitions. * @param baseState - State to start from * @return Number of new transitions. */ public int constrFindSG(final State baseState){ boolean newStateFlag = false; int ptr = 1; int newTransitions = 0; Stack<State> stStack = new Stack<State>(); Stack<LpnTranList> tranStack = new Stack<LpnTranList>(); LpnTranList currentEnabledTransitions = getEnabled(baseState); stStack.push(baseState); tranStack.push((LpnTranList) currentEnabledTransitions); while (true){ ptr State currentState = stStack.pop(); currentEnabledTransitions = tranStack.pop(); for (Transition firedTran : currentEnabledTransitions) { State newState = constrFire(firedTran,currentState); State nextState = addState(newState); newStateFlag = false; if(nextState == newState){ addFrontierState(nextState); newStateFlag = true; } // StateTran stTran = new StateTran(currentState, firedTran, state); if(nextState != currentState){ // this.addStateTran(currentState, nextState, firedTran); this.addStateTran(currentState, firedTran, nextState); newTransitions++; // TODO: (original) check that a variable was changed before creating a constraint if(!firedTran.local()){ for(LhpnFile lpn : firedTran.getDstLpnList()){ // TODO: (temp) Hack here. Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn); // TODO: (temp) Ignore constraint. } } } if(!newStateFlag) continue; LpnTranList nextEnabledTransitions = getEnabled(nextState); if (nextEnabledTransitions.isEmpty()) continue; // currentEnabledTransitions = getEnabled(nexState); // Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions); // if(disabledTran != null) { // System.out.println("Verification failed: " +disabledTran.getFullLabel() + " is disabled by " + // firedTran.getFullLabel()); // currentState.setFailure(); // return -1; stStack.push(nextState); tranStack.push(nextEnabledTransitions); ptr++; } if (ptr == 0) { break; } } return newTransitions; } /** * Finds reachable states from the given state. * Also generates new constraints from the state transitions. * Synchronized version of constrFindSG(). Method is not synchronized, but uses synchronized methods * @param baseState State to start from * @return Number of new transitions. */ public int synchronizedConstrFindSG(final State baseState){ boolean newStateFlag = false; int ptr = 1; int newTransitions = 0; Stack<State> stStack = new Stack<State>(); Stack<LpnTranList> tranStack = new Stack<LpnTranList>(); LpnTranList currentEnabledTransitions = getEnabled(baseState); stStack.push(baseState); tranStack.push((LpnTranList) currentEnabledTransitions); while (true){ ptr State currentState = stStack.pop(); currentEnabledTransitions = tranStack.pop(); for (Transition firedTran : currentEnabledTransitions) { State st = constrFire(firedTran,currentState); State nextState = addState(st); newStateFlag = false; if(nextState == st){ newStateFlag = true; addFrontierState(nextState); } if(nextState != currentState){ newTransitions++; if(!firedTran.local()){ // TODO: (original) check that a variable was changed before creating a constraint for(LhpnFile lpn : firedTran.getDstLpnList()){ // TODO: (temp) Hack here. Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn); // TODO: (temp) Ignore constraints. } } } if(!newStateFlag) continue; LpnTranList nextEnabledTransitions = getEnabled(nextState); if (nextEnabledTransitions == null || nextEnabledTransitions.isEmpty()) { continue; } // currentEnabledTransitions = getEnabled(nexState); // Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions); // if(disabledTran != null) { // prDbg(10, "Verification failed: " +disabledTran.getFullLabel() + " is disabled by " + // firedTran.getFullLabel()); // currentState.setFailure(); // return -1; stStack.push(nextState); tranStack.push(nextEnabledTransitions); ptr++; } if (ptr == 0) { break; } } return newTransitions; } public List<State> getFrontierStateSet(){ return this.frontierStateSet; } public List<State> getStateSet(){ return this.stateSet; } public void addFrontierState(State st){ this.entryStateSet.add(st); } public List<Constraint> getOldConstraintSet(){ return this.oldConstraintSet; } /** * Adds constraint to the constraintSet. * @param c - Constraint to be added. * @return True if added, otherwise false. */ public boolean addConstraint(Constraint c){ if(this.constraintSet.add(c)){ this.frontierConstraintSet.add(c); return true; } return false; } /** * Adds constraint to the constraintSet. Synchronized version of addConstraint(). * @param c - Constraint to be added. * @return True if added, otherwise false. */ public synchronized boolean synchronizedAddConstraint(Constraint c){ if(this.constraintSet.add(c)){ this.frontierConstraintSet.add(c); return true; } return false; } public List<Constraint> getNewConstraintSet(){ return this.newConstraintSet; } public void genConstraints(){ oldConstraintSet.addAll(newConstraintSet); newConstraintSet.clear(); newConstraintSet.addAll(frontierConstraintSet); frontierConstraintSet.clear(); } public void genFrontier(){ this.stateSet.addAll(this.frontierStateSet); this.frontierStateSet.clear(); this.frontierStateSet.addAll(this.entryStateSet); this.entryStateSet.clear(); } public void setInitialState(State init){ this.init = init; } public State getInitialState(){ return this.init; } public void draw(){ String dotFile = Options.getDotPath(); if(!dotFile.endsWith("/") && !dotFile.endsWith("\\")){ String dirSlash = "/"; if(Main.isWindows) dirSlash = "\\"; dotFile = dotFile += dirSlash; } dotFile += this.lpn.getLabel() + ".dot"; PrintStream graph = null; try { graph = new PrintStream(new FileOutputStream(dotFile)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } graph.println("digraph SG{"); //graph.println(" fixedsize=true"); int size = this.lpn.getAllOutputs().size() + this.lpn.getAllInputs().size() + this.lpn.getAllInternals().size(); String[] variables = new String[size]; DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap(); int i; for(i = 0; i < size; i++){ variables[i] = varIndexMap.getKey(i); } //for(State state : this.reachableSet.keySet()){ for(int stateIdx = 0; stateIdx < this.reachSize(); stateIdx++) { State state = this.getState(stateIdx); String dotLabel = state.getIndex() + ": "; int[] vector = state.getVector(); for(i = 0; i < size; i++){ dotLabel += variables[i]; if(vector[i] == 0) dotLabel += "'"; if(i < size-1) dotLabel += " "; } int[] mark = state.getMarking(); dotLabel += "\\n"; for(i = 0; i < mark.length; i++){ if(i == 0) dotLabel += "["; dotLabel += mark[i]; if(i < mark.length - 1) dotLabel += ", "; else dotLabel += "]"; } String attributes = ""; if(state == this.init) attributes += " peripheries=2"; if(state.failure()) attributes += " style=filled fillcolor=\"red\""; graph.println(" " + state.getIndex() + "[shape=ellipse width=.3 height=.3 " + "label=\"" + dotLabel + "\"" + attributes + "]"); for(Entry<Transition, State> stateTran : this.nextStateMap.get(state).entrySet()){ State tailState = state; State headState = stateTran.getValue(); Transition lpnTran = stateTran.getKey(); String edgeLabel = lpnTran.getName() + ": "; int[] headVector = headState.getVector(); int[] tailVector = tailState.getVector(); for(i = 0; i < size; i++){ if(headVector[i] != tailVector[i]){ if(headVector[i] == 0){ edgeLabel += variables[i]; edgeLabel += "-"; } else{ edgeLabel += variables[i]; edgeLabel += "+"; } } } graph.println(" " + tailState.getIndex() + " -> " + headState.getIndex() + "[label=\"" + edgeLabel + "\"]"); } } graph.println("}"); graph.close(); } /** * Return the enabled transitions in the state with index 'stateIdx'. * @param stateIdx * @return */ public LpnTranList getEnabled(int stateIdx) { State curState = this.getState(stateIdx); return this.getEnabled(curState); } /** * Return the set of all LPN transitions that are enabled in 'state'. * @param curState * @return */ public LpnTranList getEnabled(State curState) { if (curState == null) { throw new NullPointerException(); } if(enabledSetTbl.containsKey(curState) == true){ return (LpnTranList)enabledSetTbl.get(curState).clone(); } LpnTranList curEnabled = new LpnTranList(); for (Transition tran : this.lpn.getAllTransitions()) { if (isEnabled(tran,curState)) { if(tran.local()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } this.enabledSetTbl.put(curState, curEnabled); return curEnabled; } /** * Return the set of all LPN transitions that are enabled in 'state'. * @param curState * @return */ public LpnTranList getEnabled(State curState, boolean init) { if (curState == null) { throw new NullPointerException(); } if(enabledSetTbl.containsKey(curState) == true){ if (Options.getDebugMode()) { System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN" + curState.getLpn().getLabel() + ": S" + curState.getIndex() + "~~~~~~~~"); printTransitionSet((LpnTranList)enabledSetTbl.get(curState), "enabled trans at this state "); } return (LpnTranList)enabledSetTbl.get(curState).clone(); } LpnTranList curEnabled = new LpnTranList(); if (init) { for (Transition tran : this.lpn.getAllTransitions()) { if (isEnabled(tran,curState)) { if (Options.getDebugMode()) System.out.println("Transition " + tran.getLpn().getLabel() + "(" + tran.getName() + ") is enabled"); if(tran.local()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } } else { for (int i=0; i < this.lpn.getAllTransitions().length; i++) { Transition tran = this.lpn.getAllTransitions()[i]; if (curState.getTranVector()[i]) if(tran.local()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } this.enabledSetTbl.put(curState, curEnabled); if (Options.getDebugMode()) { System.out.println("~~~~~~~~ State S" + curState.getIndex() + " does not exist in enabledSetTbl for LPN " + curState.getLpn().getLabel() + ". Add to enabledSetTbl."); printEnabledSetTbl(); } return curEnabled; } private void printEnabledSetTbl() { System.out.println("******* enabledSetTbl**********"); for (State s : enabledSetTbl.keySet()) { System.out.print("S" + s.getIndex() + " -> "); printTransitionSet(enabledSetTbl.get(s), ""); } } public boolean isEnabled(Transition tran, State curState) { int[] varValuesVector = curState.getVector(); String tranName = tran.getName(); int tranIndex = tran.getIndex(); if (Options.getDebugMode()) System.out.println("Checking " + tran); if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0 && !(tran.isPersistent() && curState.getTranVector()[tranIndex])) { if (Options.getDebugMode()) System.out.println(tran.getName() + " " + "Enabling condition is false"); return false; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0) { if (Options.getDebugMode()) System.out.println("Rate is zero"); return false; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { int[] curMarking = curState.getMarking(); for (int place : this.lpn.getPresetIndex(tranName)) { if (curMarking[place]==0) { if (Options.getDebugMode()) System.out.println(tran.getName() + " " + "Missing a preset token"); return false; } } // if a transition is enabled and it is not recorded in the enabled transition vector curState.getTranVector()[tranIndex] = true; } return true; } public int reachSize() { if(this.stateCache == null){ return this.stateSet.size(); } return this.stateCache.size(); } public boolean stateOnStack(State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); for (State s : stateArray) { if (s == curState) { isStateOnStack = true; break; } } if (isStateOnStack) break; } return isStateOnStack; } /* * Add the module state mState into the local cache, and also add its local portion into * the local portion cache, and build the mapping between the mState and lState for fast lookup * in the future. */ public State addState(State mState) { State cachedState = this.stateCache.add(mState); State lState = this.state2LocalMap.get(cachedState); if(lState == null) { lState = cachedState.getLocalState(); lState = this.localStateCache.add(lState); this.state2LocalMap.put(cachedState, lState); } return cachedState; } /* * Get the local portion of mState from the cache.. */ public State getLocalState(State mState) { return this.state2LocalMap.get(mState); } public State getState(int stateIdx) { return this.stateCache.get(stateIdx); } public void addStateTran(State curSt, Transition firedTran, State nextSt) { HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt); if(nextMap == null) { nextMap = new HashMap<Transition,State>(); nextMap.put(firedTran, nextSt); this.nextStateMap.put(curSt, nextMap); } else nextMap.put(firedTran, nextSt); } public State getNextState(State curSt, Transition firedTran) { HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt); if(nextMap == null) return null; return nextMap.get(firedTran); } private static Set<Entry<Transition, State>> emptySet = new HashSet<Entry<Transition, State>>(0); public Set<Entry<Transition, State>> getOutgoingTrans(State currentState){ HashMap<Transition, State> tranMap = this.nextStateMap.get(currentState); if(tranMap == null){ return emptySet; } return tranMap.entrySet(); } public int numConstraints(){ if(this.constraintSet == null){ return this.oldConstraintSet.size(); } return this.constraintSet.size(); } public void clear(){ this.constraintSet.clear(); this.frontierConstraintSet.clear(); this.newConstraintSet.clear(); this.frontierStateSet.clear(); this.entryStateSet.clear(); this.constraintSet = null; this.frontierConstraintSet = null; this.newConstraintSet = null; this.frontierStateSet = null; this.entryStateSet = null; this.stateCache = null; } public State getInitState() { // create initial vector int size = this.lpn.getVarIndexMap().size(); int[] initialVector = new int[size]; for(int i = 0; i < size; i++) { String var = this.lpn.getVarIndexMap().getKey(i); int val = this.lpn.getInitVector(var);// this.initVector.get(var); initialVector[i] = val; } return new State(this.lpn, this.lpn.getInitialMarkingsArray(), initialVector, this.lpn.getInitEnabledTranArray(initialVector)); } /** * Fire a transition on a state array, find new local states, and return the new state array formed by the new local states. * @param firedTran * @param curLpnArray * @param curStateArray * @param curLpnIndex * @return */ public State[] fire(final StateGraph[] curSgArray, final int[] curStateIdxArray, Transition firedTran) { State[] stateArray = new State[curSgArray.length]; for(int i = 0; i < curSgArray.length; i++) stateArray[i] = curSgArray[i].getState(curStateIdxArray[i]); return this.fire(curSgArray, stateArray, firedTran); } // This method is called by search_dfs(StateGraph[], State[]). public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran) { int thisLpnIndex = this.getLpn().getLpnIndex(); State[] nextStateArray = curStateArray.clone(); State curState = curStateArray[thisLpnIndex]; State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran); //int[] nextVector = nextState.getVector(); //int[] curVector = curState.getVector(); // TODO: (future) assertions in our LPN? /* for(Expression e : assertions){ if(e.evaluate(nextVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ nextStateArray[thisLpnIndex] = nextState; if(firedTran.local()==true) { // nextStateArray[thisLpnIndex] = curSgArray[thisLpnIndex].addState(nextState); return nextStateArray; } HashMap<String, Integer> vvSet = new HashMap<String, Integer>(); vvSet = this.lpn.getAllVarsWithValuesAsInt(nextState.getVector()); // for (String key : this.lpn.getAllVarsWithValuesAsString(curState.getVector()).keySet()) { // if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); // // TODO: (temp) type cast continuous variable to int. // if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); // if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); /* for (VarExpr s : this.getAssignments()) { int newValue = nextVector[s.getVar().getIndex(curVector)]; vvSet.put(s.getVar().getName(), newValue); } */ // Update other local states with the new values generated for the shared variables. //nextStateArray[this.lpn.getIndex()] = nextState; // if (!firedTran.getDstLpnList().contains(this.lpn)) // firedTran.getDstLpnList().add(this.lpn); for(LhpnFile curLPN : firedTran.getDstLpnList()) { int curIdx = curLPN.getLpnIndex(); // System.out.println("Checking " + curLPN.getLabel() + " " + curIdx); State newState = curSgArray[curIdx].getNextState(curStateArray[curIdx], firedTran); if(newState != null) { nextStateArray[curIdx] = newState; } else { State newOther = curStateArray[curIdx].update(curSgArray[curIdx], vvSet, curSgArray[curIdx].getLpn().getVarIndexMap()); if (newOther == null) nextStateArray[curIdx] = curStateArray[curIdx]; else { State cachedOther = curSgArray[curIdx].addState(newOther); //nextStateArray[curIdx] = newOther; nextStateArray[curIdx] = cachedOther; // System.out.println("ADDING TO " + curIdx + ":\n" + curStateArray[curIdx].getIndex() + ":\n" + // curStateArray[curIdx].print() + firedTran.getName() + "\n" + // cachedOther.getIndex() + ":\n" + cachedOther.print()); curSgArray[curIdx].addStateTran(curStateArray[curIdx], firedTran, cachedOther); } } } return nextStateArray; } // TODO: (original) add transition that fires to parameters public State fire(final StateGraph thisSg, final State curState, Transition firedTran) { // Search for and return cached next state first. // if(this.nextStateMap.containsKey(curState) == true) // return (State)this.nextStateMap.get(curState); State nextState = thisSg.getNextState(curState, firedTran); if(nextState != null) return nextState; // If no cached next state exists, do regular firing. // Marking update int[] curOldMarking = curState.getMarking(); int[] curNewMarking = null; if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0) curNewMarking = curOldMarking; else { curNewMarking = new int[curOldMarking.length]; curNewMarking = curOldMarking.clone(); for (int prep : this.lpn.getPresetIndex(firedTran.getName())) { curNewMarking[prep]=0; } for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) { curNewMarking[postp]=1; } } // State vector update int[] newVectorArray = curState.getVector().clone(); int[] curVector = curState.getVector(); for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) { if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } // TODO: (temp) type cast continuous variable to int. if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } } /* for (VarExpr s : firedTran.getAssignments()) { int newValue = (int) s.getExpr().evaluate(curVector); newVectorArray[s.getVar().getIndex(curVector)] = newValue; } */ // Enabled transition vector update boolean[] newEnabledTranVector = updateEnabledTranVector(curState.getTranVector(), curNewMarking, newVectorArray, firedTran); State newState = thisSg.addState(new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector)); // TODO: (future) assertions in our LPN? /* int[] newVector = newState.getVector(); for(Expression e : assertions){ if(e.evaluate(newVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ thisSg.addStateTran(curState, firedTran, newState); return newState; } public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring, int[] newMarking, int[] newVectorArray, Transition firedTran) { boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone(); // firedTran is disabled if (firedTran != null) { enabledTranAfterFiring[firedTran.getIndex()] = false; for (Iterator<Integer> conflictIter = firedTran.getConflictSetTransIndices().iterator(); conflictIter.hasNext();) { Integer curConflictingTranIndex = conflictIter.next(); enabledTranAfterFiring[curConflictingTranIndex] = false; } } // find newly enabled transition(s) based on the updated markings and variables for (Transition tran : this.lpn.getAllTransitions()) { boolean needToUpdate = true; String tranName = tran.getName(); int tranIndex = tran.getIndex(); //System.out.println("Checking " + tran); if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { //System.out.println(tran.getName() + " " + "Enabling condition is false"); continue; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { //System.out.println("Rate is zero"); continue; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { for (int place : this.lpn.getPresetIndex(tranName)) { if (newMarking[place]==0) { //System.out.println(tran.getName() + " " + "Missing a preset token"); needToUpdate = false; break; } } } if (needToUpdate) { // if a transition is enabled and it is not recorded in the enabled transition vector enabledTranAfterFiring[tranIndex] = true; } } return enabledTranAfterFiring; } public State constrFire(Transition firedTran, final State curState) { // Marking update int[] curOldMarking = curState.getMarking(); int[] curNewMarking = null; if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0){ curNewMarking = curOldMarking; } else { curNewMarking = new int[curOldMarking.length - firedTran.getPreset().length + firedTran.getPostset().length]; int index = 0; for (int i : curOldMarking) { boolean existed = false; for (int prep : this.lpn.getPresetIndex(firedTran.getName())) { if (i == prep) { existed = true; break; } // TODO: (??) prep > i else if(prep > i){ break; } } if (existed == false) { curNewMarking[index] = i; index++; } } for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) { curNewMarking[index] = postp; index++; } } // State vector update int[] oldVector = curState.getVector(); int size = oldVector.length; int[] newVectorArray = new int[size]; System.arraycopy(oldVector, 0, newVectorArray, 0, size); int[] curVector = curState.getVector(); for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) { if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } // TODO: (temp) type cast continuous variable to int. if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } } // TODO: (check) Is the update is equivalent to the one below? /* for (VarExpr s : getAssignments()) { int newValue = s.getExpr().evaluate(curVector); newVectorArray[s.getVar().getIndex(curVector)] = newValue; } */ // Enabled transition vector update boolean[] newEnabledTranArray = curState.getTranVector(); newEnabledTranArray[firedTran.getIndex()] = false; State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranArray); // TODO: (future) assertions in our LPN? /* int[] newVector = newState.getVector(); for(Expression e : assertions){ if(e.evaluate(newVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ return newState; } public void outputLocalStateGraph(String file) { try { int size = this.lpn.getVarIndexMap().size(); String varNames = ""; for(int i = 0; i < size; i++) { varNames = varNames + ", " + this.lpn.getVarIndexMap().getKey(i); } varNames = varNames.replaceFirst(", ", ""); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write("digraph G {\n"); out.write("Inits [shape=plaintext, label=\"<" + varNames + ">\"]\n"); for (State curState : nextStateMap.keySet()) { String markings = intArrayToString("markings", curState); String vars = intArrayToString("vars", curState); String enabledTrans = boolArrayToString("enabledTrans", curState); String curStateName = "S" + curState.getIndex(); out.write(curStateName + "[shape=\"ellipse\",label=\"" + curStateName + "\\n<"+vars+">" + "\\n<"+enabledTrans+">" + "\\n<"+markings+">" + "\"]\n"); } for (State curState : nextStateMap.keySet()) { HashMap<Transition, State> stateTransitionPair = nextStateMap.get(curState); for (Transition curTran : stateTransitionPair.keySet()) { String curStateName = "S" + curState.getIndex(); String nextStateName = "S" + stateTransitionPair.get(curTran).getIndex(); String curTranName = curTran.getName(); if (curTran.isFail() && !curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=red]\n"); else if (!curTran.isFail() && curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=blue]\n"); else if (curTran.isFail() && curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=purple]\n"); else out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\"]\n"); } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } private String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVector().length; i++) { arrayStr = arrayStr + curState.getVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabledTrans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ","; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } private void printTransitionSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " "); if (transitionSet.isEmpty()) { System.out.println("empty"); } else { for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { Transition tranInDisable = curTranIter.next(); System.out.print(tranInDisable.getName() + " "); } System.out.print("\n"); } } private static void printAmpleSet(LpnTranList transitionSet, String setName) { if (!setName.isEmpty()) System.out.print(setName + " "); if (transitionSet.isEmpty()) { System.out.println("empty"); } else { for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { Transition tranInDisable = curTranIter.next(); System.out.print(tranInDisable.getName() + " "); } System.out.print("\n"); } } public HashMap<State,LpnTranList> copyEnabledSetTbl() { HashMap<State,LpnTranList> copyEnabledSetTbl = new HashMap<State,LpnTranList>(); for (State s : enabledSetTbl.keySet()) { LpnTranList tranList = enabledSetTbl.get(s).clone(); copyEnabledSetTbl.put(s.clone(), tranList); } return copyEnabledSetTbl; } public void setEnabledSetTbl(HashMap<State, LpnTranList> enabledSetTbl) { this.enabledSetTbl = enabledSetTbl; } public HashMap<State, LpnTranList> getEnabledSetTbl() { return this.enabledSetTbl; } public HashMap<State, HashMap<Transition, State>> getNextStateMap() { return this.nextStateMap; } }
package org.intellij.scratch; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Key; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.CollectionComboBoxModel; import com.intellij.ui.ComboboxSpeedSearch; import com.intellij.ui.ListCellRendererWrapper; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.generate.tostring.util.StringUtil; import javax.swing.*; import java.awt.*; import java.util.Comparator; import java.util.List; import java.util.Set; /** * @author ignatov */ public class NewScratchFileAction extends AnAction implements DumbAware { private static final Key<Language> SCRATCH_LANGUAGE = Key.create("SCRATCH_LANGUAGE"); @Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); if (project == null) return; MyDialog myDialog = new MyDialog(project); myDialog.show(); if (myDialog.isOK()) { Language language = myDialog.getType(); project.putUserData(SCRATCH_LANGUAGE, language); LanguageFileType associatedFileType = language.getAssociatedFileType(); String defaultExtension = associatedFileType != null ? associatedFileType.getDefaultExtension() : "unknown"; VirtualFile virtualFile = new LightVirtualFile("scratch." + defaultExtension, language, ""); OpenFileDescriptor descriptor = new OpenFileDescriptor(project, virtualFile); FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } } private static class MyDialog extends DialogWrapper { @Nullable private Project myProject; @NotNull private JComboBox myComboBox; protected MyDialog(@Nullable Project project) { super(project); myProject = project; setTitle("Specify the Language"); init(); } @Nullable @Override protected JComponent createCenterPanel() { JPanel panel = new JPanel(new BorderLayout()); myComboBox = createCombo(getLanguages()); panel.add(myComboBox, BorderLayout.CENTER); return panel; } public Language getType() { return ((Language) myComboBox.getSelectedItem()); } private JComboBox createCombo(List<Language> languages) { JComboBox jComboBox = new ComboBox(new CollectionComboBoxModel(languages)); jComboBox.setRenderer(new ListCellRendererWrapper<Language>() { @Override public void customize(JList list, Language lang, int index, boolean selected, boolean hasFocus) { if (lang != null) { setText(lang.getDisplayName()); LanguageFileType associatedLanguage = lang.getAssociatedFileType(); if (associatedLanguage != null) setIcon(associatedLanguage.getIcon()); } } }); new ComboboxSpeedSearch(jComboBox) { @Override protected String getElementText(Object element) { return element instanceof Language ? ((Language) element).getDisplayName() : null; } }; Language previous = myProject != null ? myProject.getUserData(SCRATCH_LANGUAGE) : null; if (previous != null) { jComboBox.setSelectedItem(previous); } return jComboBox; } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myComboBox; } } private static List<Language> getLanguages() { Set<Language> result = ContainerUtil.newTreeSet(new Comparator<Language>() { @Override public int compare(Language l1, Language l2) { return l1.getDisplayName().compareTo(l2.getDisplayName()); } }); for (Language lang : Language.getRegisteredLanguages()) { if (!StringUtil.isEmpty(lang.getDisplayName())) result.add(lang); for (Language dialect : lang.getDialects()) { if (!"$XSLT".equals(dialect.getDisplayName())) result.add(dialect); } } return ContainerUtil.newArrayList(result); } }